python - How do I write tests correctly using unittest? -


i trying figure out how write unit tests functions have written in python - here's code written below:

def num_buses(n):     import math     """ (int) -> int      precondition: n >= 0      return minimum number of buses required transport n people.     each bus can hold 50 people.      >>> num_buses(75)     2     """     bus = int()     if(n>=0):         bus = int(math.ceil(n/50.0))     return bus 

i attempting write test code giving me fail results - here's code started with:

import a1 import unittest   class testnumbuses(unittest.testcase):     """ test class function a1.num_buses. """     def test_numbuses_1(self):         actual = num_buses(75)         expected = 2         self.assertequal(actual, expected)      # add test methods a1.num_buses here.   if __name__ == '__main__':     unittest.main(exit=false) 

when run module pressing f5 - -

e ====================================================================== error: test_numbuses_1 (__main__.testnumbuses) ---------------------------------------------------------------------- traceback (most recent call last):   file "c:\1-blog-cacher\testnumbuses.py", line 8, in test_numbuses_1     actual = num_buses(75) nameerror: global name 'num_buses' not defined  ---------------------------------------------------------------------- ran 1 test in 0.050s  failed (errors=1) 

so test failed - although should pass since number of passengers 75 , each bus can hold maximum of 50 people - more result in rounding of figures.

can see how can test cases work , writing test code went wrong?

in unittest file have import num_buses.

this fixes immediate problem, if have defined num_buses in a1 have a1.num_buses otherwise python think num_buses global function.

import a1 import unittest import num_buses  class testnumbuses(unittest.testcase):     """ test class function a1.num_buses. """     def test_numbuses_1(self):         actual = num_buses(75) #a1.num_buses(75) <-         expected = 2         self.assertequal(actual, expected)      # add test methods a1.num_buses here.   if __name__ == '__main__':     unittest.main(exit=false) 

check out: cyber-dojo test - press resume , in test_untitled.py press test button.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -