Unit test stuck in instantiating tests mode - unit-testing

After installing dataspell and anaconda, I tried to perform a testing of my classes. However, the testing is taking forever.
A simple function
def add(x, y):
return x + y
Test
import unittest
from calculator import add
class TestCalculator(unittest.TestCase):
def test_add(self):
x = 2
y = 3
actual_result = 5
expected_result = add(x, y)
self.assertEqual(actual_result, expected_result)
if __name__ == '__main__':
unittest.main()
It's working on my other computer. Is there settings to change or something else to install?

Can you perhaps share a profile dump?
import cProfile
profile = cProfile.Profile()
profile.enable()
try:
import unittest
from calculator import add
class TestCalculator(unittest.TestCase):
def test_add(self):
x = 2
y = 3
actual_result = 5
expected_result = add(x, y)
self.assertEqual(actual_result, expected_result)
if __name__ == '__main__':
unittest.main()
finally:
profile.dump_stats('test.profile')

Related

I'm struggling to create a unit test, if someone could please have a look on my code to figure out the possible issue:

The code below is supposed to simulate a ATM, I have to create 5 unit tests for the code, and to be honest I have no idea why it is not working! :(
It should show on the Terminal that ran 5 tests in x s, however it keeps saying that Ran 0 tests and OK. Should I import a library? Any suggestion?
import unittest
def withdraw(wdra):
balanace_account = 100
if wdra < balanace_account:
balanace_account -= wdra
return balanace_account
class AtmTest(unittest.TestCase):
def correct_amount(self):
expected = 29.50 #withdraw de 70.50
result = withdraw(70.5)
self.assertEqual(expected,result)
def invalid_error(self):
expected = 1
result = withdraw(1/0)
self.assertEqual(expected, result)
def incorrect_amount(self):
expected = 50.00
result = withdraw(60)
self.assertEqual(expected,result)
def greater_withdraw(self):
expected = -10
result = withdraw(110)
self.assertEqual(expected,result)
def invalid_data_type(selfS):
expected = 100
result = withdraw('0')
self.assertEqual(expected, result)
if __name__ == '__main__':
unittest.main()
pass
You should name your test methods with test prefix so that the test runner can identify test methods. See here for example.

How to mock a method on an object in a class?

I'm trying to figure out how to mock with one additional level of indirection - a method on an object in a class.
import serial
class MyClass(object):
def __init__(self, com_port, baudrate):
self.sp = serial.Serial(com_port, baudrate)
def do_something(self, data):
num_bytes_written = self.sp.write(data)
if num_bytes_written != len(data):
return -1
return 0
In testfile:
import mock
...
#mock.patch('serial.Serial', return_value='')
#mock.patch('serial.Serial.write', return_value=0)
def test_do_something_fails_on_bad_write(self, mock_write):
...
want = -1
dummy_data = b'123'
inst = myfile.MyClass('COM8', 115200)
got = c.do_something(dummy_data)
self.assertEqual(got, want)
Unit test solution:
serial.py:
class Serial(object):
def __init__(self, port, baudrate):
self.port = port
self.baudrate = baudrate
def write(self, data):
return 100
myclass.py:
import serial
class MyClass(object):
def __init__(self, com_port, baudrate):
self.sp = serial.Serial(com_port, baudrate)
def do_something(self, data):
num_bytes_written = self.sp.write(data)
if num_bytes_written != len(data):
return -1
return 0
test_myclass.py:
import unittest
from unittest import mock
import serial
import myclass
class TestMyClass(unittest.TestCase):
#mock.patch('myclass.serial.Serial')
def test_do_something_fails_on_bad_write(self, mock_Serial):
serial_instance = mock_Serial()
serial_instance.write.return_value = 1
want = -1
dummy_data = b'123'
c = myclass.MyClass('COM8', 115200)
got = c.do_something(dummy_data)
self.assertEqual(got, want)
serial_instance.write.assert_called_once_with(b'123')
#mock.patch('myclass.serial.Serial')
def test_do_something_success(self, mock_Serial):
serial_instance = mock_Serial()
serial_instance.write.return_value = 3
want = 0
dummy_data = b'123'
c = myclass.MyClass('COM8', 115200)
got = c.do_something(dummy_data)
self.assertEqual(got, want)
serial_instance.write.assert_called_once_with(b'123')
if __name__ == '__main__':
unittest.main()
unit test result with coverage report:
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
Name Stmts Miss Cover Missing
--------------------------------------------------------------------------
src/stackoverflow/61333922/myclass.py 9 0 100%
src/stackoverflow/61333922/serial.py 6 3 50% 3-4, 7
src/stackoverflow/61333922/test_myclass.py 25 0 100%
--------------------------------------------------------------------------
TOTAL 40 3 92%

Bound task in celery is not able to access instance variable in django project

I have setup celery in my django project using official documentation at
http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django
So my MyApp/tasks.py have content
from celery import shared_task
class Someclass():
def __init__(self, x, y):
self.x = x
self.y = y
#shared_task(bind=True)
def func1(self):
'''This does not work'''
return self.x + self.y
#shared_task(bind=True)
def func2(self, a, b):
'''This works well'''
return a + b
When I run
In [9]: o = Someclass(3, 4)
In [10]: o.func1.delay()
Out[10]: <AsyncResult: afc6b151-d71c-4f46-a916-6917f98c681f>
I get the error
AttributeError: 'func1' object has no attribute 'x'
When I run
In [11]: o.func2.delay(3, 4)
Out[11]: <AsyncResult: 3b227f00-8d9c-472b-b7d8-8b4b6261f689>
This works perfectly
How can I make func1 working so that it can use instance variables e.g. x and y?
from celery import shared_task
#shared_task(bind=True)
def func(self, a, b):
return a + b
class Someclass():
def __init__(self, x, y):
self.x = x
self.y = y
def func1(self):
return func.delay(self.x, self.y)

Error using multiprocessing library: "got multiple values for keyword argument 'x' "

I am trying to parallelize a penalized linear model using the multiprocessing library in python.
I created a function that solves my model:
from __future__ import division
import numpy as np
from cvxpy import *
def lm_lasso_solver(x, y, lambda1):
n = x.shape[0]
m = x.shape[1]
lambda1_param = Parameter(sign="positive")
betas_var = Variable(m)
response = dict(model='lm', penalization='l')
response["parameters"] = {"lambda_vector": lambda1}
lasso_penalization = lambda1_param * norm(betas_var, 1)
lm_penalization = 0.5 * sum_squares(y - x * betas_var)
objective = Minimize(lm_penalization + lasso_penalization)
problem = Problem(objective)
lambda1_param.value = lambda1
try:
problem.solve(solver=ECOS)
except:
try:
problem.solve(solver=CVXOPT)
except:
problem.solve(solver=SCS)
beta_sol = np.asarray(betas_var.value).flatten()
response["solution"] = beta_sol
return response
In this function x is a matrix of predictors and y is the response variable. lambda1 is the parameter that must be optimized, and so, is the parameter that I want to parallelize. I saved this script in a python file called "ms.py"
Then I created another python file called "parallelization.py" and in that file I defined the following:
import multiprocessing as mp
import ms
import functools
def myFunction(x, y, lambda1):
pool = mp.Pool(processes=mp.cpu_count())
results = pool.map(functools.partial(ms.lm_lasso_solver, x=x, y=y), lambda1)
return results
So the idea was now, on the python interpreter, execute:
from sklearn.datasets import load_boston
boston = load_boston()
x = boston.data
y = boston.target
runfile('parallelization.py')
lambda_vector = np.array([1,2,3])
myFunction(x, y, lambda_vector)
But when I do this, I get the following error message:
The problem is on the line:
results = pool.map(functools.partial(ms.lm_lasso_solver, x=x, y=y), lambda1)
You are calling the functools.partial() method with keyworded arguments whereas in your lm_lasso_solver method, you don't define them as keyworded arguments. You should call it with x and y as positional arguments as follows:
results = pool.map(functools.partial(ms.lm_lasso_solver, x, y), lambda1)
or simply use the apply_async() method the pool object :
results = pool.apply_async(ms.lm_lasso_solver, args=[x, y, lambda1])

pyinstaller for python 2.7.9 get executable that when ran just flashes on screen

Hi I installed pyinstaller and pywin32 64 bit version to get an .exe.
I did get a .exe built, but when I double click on it, it just flashes on the screen and closes. I used this as a setup.py
from distutils.core import setup
import py2exe
setup(console=['BP.py'])
The script BP.py asks the user to input some values and make some plots.
Any ideas?
Thanks
Below is the code
Code for BP.py is below
##
##BP.py
import matplotlib.pyplot as plt
import numpy as np
# A function to plot the lines
def plot_lines(x,y,colors,j):
ax = plt.subplot(2,2,j)
for i in range(len(colors)):
plt.plot(x,y[i],colors[i])
def plot_setup():
fig = plt.figure()
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
def Max_avg(row,col,x,colors,ao1,ao2,j,a_list):
for a in a_list:
i = 0
y_a1 = np.zeros((row,col))
y_a2 = np.zeros((row,col))
y = np.zeros((row,col))
for ao1_v,ao2_v in zip(ao1,ao2):
y_a1[i] = 3*x**2
y_a2[i] = 5*x
y[i] = np.add(y_a1[i],y_a2[i])
i = i+1
plot_lines(x,y,colors,j)`enter code here`
j = j+1
def main():
x1 = -10
x2 = 10
numpts = 100
x = np.linspace(x1,x2,numpts,endpoint=True)
col = len(x)
# a_list = [-1.7,-5]
print "Please enter a list of coefficients seperated by a white space."
string_input = raw_input()
a_list = string_input.split()
a_list = [int(a) for a in a_list]
ao1 = (-5.0,2.0)
ao2 = (1.0,10.0)
col_plt = 2
colors = ['b','g']
j = 1
plot_setup()
Max_avg(2,col,x,colors,ao1,ao2,j,a_list)
plt.show()
if __name__ == "__main__":
main()