How do i make a unittest ? what does it look like? - python-3.x

def abn_abc(voteslist):
sums = {}
for vote in votes:
if vote in sums:
sums[vote] += 1
else:
sums[vote] = 1
return tally_ballots(sums)
How do I write a unit test for this function?

Something like this:
import unittest
from wherever import abn_abc
class AbnAbcTest(unittest.TestCase):
def test_abn_abc(self):
list_for_testing with = [<insert list here>]
self.assertEqual(abn_abc(list_for_testing_with), <expected result>)
if __name__ == '__main__':
unittest.main()
Here's the documentation.

Related

Assert whether a function is being called inside another function

I have 2 functions and the other one is called only when the parameter passed is True.
def func1(para1 = True):
// Some lines of code
if para1 == True:
func2()
def func2():
// Some lines of code
Now, I'm trying to create a unittest that checks whether the nested function func2 is being called(When parameter passed to func1 is true). I checked online and found something related to Mock() but did not understand how to use for this particular test case. How can I proceed with this?
example.py:
def func1(para1=True):
if para1 == True:
func2()
def func2():
pass
test_example.py:
from unittest import TestCase
import unittest
from unittest.mock import patch
from example import func1
class TestExample(TestCase):
#patch('example.func2')
def test_func1__should_call_func2(self, mock_func2):
func1()
mock_func2.assert_called_once()
#patch('example.func2')
def test_func1__should_not_call_func2(self, mock_func2):
func1(False)
mock_func2.assert_not_called()
if __name__ == '__main__':
unittest.main()
Test result:
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK

how to write a unittest for a class?

class Hand:
def __init__(self,cards, total, soft_ace_count):
self.cards = cards
self.total = total
self.soft_ace_count = soft_ace_count
def __str__(self):
return(str(self.cards)+','+str(self.total)+','+str(self.soft_ace_count))
def add_card(self):
self.cards.append(get_card())
self.score()
def is_blackjack(self):
return len(self.cards)==2 and self.total==21
def is_bust(self):
return self.total > 21
def score(self):
self.total=0
self.soft_ace_count=0
for x in self.cards:
if x > 10:
x=10
self.total+=x
#the following code will decide 1 =11 or 1 = 1
if self.total <= 11 and 1 in self.cards:
self.total+=10
self.soft_ace_count+=1
I am trying to write the unittest for this 'Hand' class. Do I need a init setup for this particular unittest?
Here is part of code of my unittest. Thank you so much if anyone could help me with this. I just started in python. Any suggestions would help. Thank you. Neglect the indent
class hand(unittest.TestCase):
def __init__(self):
self.cards=cards
self.total = total
self.soft_ace_count = soft_ace_count
Assuming that you have your class in a module named hand.py, you can place your unittest script in the same directory. It could look like this:
import unittest
from hand import Hand
class hand(unittest.TestCase):
def test_init(self):
cards = []
h = Hand(cards, 0, 0)
self.assertEqual(h.total, 0)
self.assertEqual(h.soft_ace_count, 0)
self.assertEqual(len(h.cards), 0)
# def test_blackjack(self):
#....
# def test_score(self):
#....
# def test_OTHERTHINGS(self):
#.....
if __name__ == '__main__':
unittest.main()
if you name your unittestscript for example unittesthand.py, you can run it via "python unittestscript.py". You will get the following result:
> .
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
The unittest component has executed all methods starting with "test" and executed. In the example the "test_init" method. This is NOT the initialization of the test, but the unittest for the initialization of class Hand.
Now change for example the code to "self.assertEqual(h.total, 1)", and you will see that the unittest component reports an error.
Now you can create additional cases for the other methods.You can also create a base test case with code that is always executed before and after the unittests and so on...

How to write a nested switch case in python?

Is that even possible?
What I know so far:
Python hasn't switch case but they have something called dictionary mapping.
def fun1():print("fun1")
def fun2():print("fun2")
def fun3():print("fun3")
def WannaBeSwitch(arg):
switch = {
0: fun1,
1: fun2,
2: fun3
}
return switch.get(arg, "blabla")
if __name__ == "__main__":
argument = 1
call_func = WannaBeSwitch(argument)
call_func()
I am working on the python project in which I needed to implement nested switch.
This answer helped me a lot.
Here is working example based on that answer. The example is how I implemented it in my project. You can make changes to fit it with your needs.
def fun1_1():print("fun1_1")
def fun1_2():print("fun1_2")
def fun1_3():print("fun1_3")
def fun1(sub_case):
sub_switch = {
1: fun1_1,
2: fun1_2,
3: fun1_3
}
sub_switch.get(sub_case, default_case)()
return
def fun2_1():print("fun2_1")
def fun2_2():print("fun2_2")
def fun2_3():print("fun2_3")
def fun2(sub_case):
sub_switch = {
1: fun2_1,
2: fun2_2,
3: fun2_3
}
sub_switch.get(sub_case, default_case)()
return
def fun3_1():print("fun3_1")
def fun3_2():print("fun3_2")
def fun3_3():print("fun3_3")
def fun3(sub_case):
sub_switch = {
1: fun3_1,
2: fun3_2,
3: fun3_3
}
sub_switch.get(sub_case, default_case)()
return
def default_case(): print("Unsupported case!")
main_switch = {
1: fun1,
2: fun2,
3: fun3
}
if __name__ == "__main__":
main_case = 2
sub_case = 3
main_switch.get(main_case)(sub_case)
I do not know what exactly you mean by nested switch case, but if I have gotten it right, there is no problem with using dictionary mapping inside the helpers functions. I mean something like this is possible, using your example as demonstration:
def fun1_1():print("fun1_1")
def fun1_2():print("fun1_2")
def fun1_3():print("fun1_3")
def fun1(arg):
switch = {
0: fun1_1,
1: fun1_2,
2: fun1_3
}
return switch.get(arg, "blabla")
def fun2_1():print("fun2_1")
def fun2_2():print("fun2_2")
def fun2_3():print("fun2_3")
def fun2(arg):
switch = {
0: fun2_1,
1: fun2_2,
2: fun2_3
}
return switch.get(arg, "blabla")
def fun3_1():print("fun3_1")
def fun3_2():print("fun3_2")
def fun3_3():print("fun3_3")
def fun3(arg):
switch = {
0: fun3_1,
1: fun3_2,
2: fun3_3
}
return switch.get(arg, "blabla")
def WannaBeSwitch(arg):
switch = {
0: fun1,
1: fun2,
2: fun3
}
return switch.get(arg, "blabla")
if __name__ == "__main__":
argument1 = 1
argument2 = 1
call_func = WannaBeSwitch(argument1)(argument2)
call_func()
Nevertheless, it does not look very readable... Maybe if you write what exactly do you want to do with it and how do you imagine you would use it, I could give you more helpful answer.

testing a method with two input() in console app

My console app is simply adding two numbers:
def add():
a=int(input('Enter first number '))
b= int(input('Enter second number '))
return a + b
how do I unit test the above method? I tried the following but I can't seem to pass two values to it:
import unittest
from unittest.mock import patch
#patch('builtins.input', return_value='2')
#patch('builtins.input', return_value='3')
def test_add(self, a, b ):
self.assertEqual(result, 5)
While I don't get the prompts asking for numbers during testing, the tests are failing because both a and b are 2.
The side_effect parameter can be used to construct a mock object that returns different values each time it is called. Pass it a list or other iterable containing each of your return values.
You can set this attribute directly,
import unittest
from unittest.mock import patch
def add():
a=int(input('Enter first number '))
b= int(input('Enter second number '))
return a + b
class Tester(unittest.TestCase):
#patch('builtins.input')
def test_add(self, input_mock):
input_mock.side_effect = [2,3]
result = add()
self.assertEqual(result, 5)
if __name__ == '__main__':
unittest.main()
Or specify it in the decorator.
import unittest
from unittest.mock import patch
def add():
a=int(input('Enter first number '))
b= int(input('Enter second number '))
return a + b
class Tester(unittest.TestCase):
#patch('builtins.input', side_effect=[2,3])
def test_add(self, input_mock):
result = add()
self.assertEqual(result, 5)
if __name__ == '__main__':
unittest.main()

Mocking a while statment Python

Im pretty new at mocking in Python. I searched pretty deeply for any post that answered this question, but i failed to do so. I want to mock a function that is called within a while statement. Is there anyway to do this?
def some_function(self, some_param):
some_counter = 0
while self.func_i_want_to_mock(mock_param, mock_param2) is False:
some_counter += 1
return some_counter
I want to mock a function that is called within a while statement
Define a side effect function if you want to play with the parameters
def func_tbm_side_effect(first, second):
return 'whatever'
Now with the testing
import unittest
import mock
import ClassWithSomeFunc
class TestClassWithSomeFunc(unittest.TestCase):
def test_some_function(self):
with mock.patch.object(ClassWithSomeFunc, 'some_function') as mocked_sf:
mocked_sf.side_effect = func_tbm_side_effect
item = ClassWithSomeFunc()
value = item.some_function('parameter')
self.assertEqual(value, 'endless loop')
def some_function(self, some_param):
some_counter = 0
while self.func_i_want_to_mock(mock_param, mock_param) is False:
some_counter += 1
return some_counter
def func_i_want_to_mock(mock_param, mock_param):
if mock_param1 == x and mock_param2 == y:
return True
elif """ ... all cases"""

Resources