Updated comp.py
- run the actual code only from
if __name__ == "__main__" block. This allows safe importing of the module and also running the code, when called as script
- separate argument parsing into
main function
- keep the tested
afunc as independent from the rest as possible, so expect all needed input to be passed via arguments, not via sys.argv or other global state. This makes your function much more testable
Here comes the code:
from argparse import ArgumentParser
def main():
parser = ArgumentParser()
parser.add_argument("-n", dest="deg", default=100,type=int, help="setup value of deg")
parser.add_argument("-k", dest="k", default=25, type=float, help="setup value of k")
parser.add_argument("-l", dest="l", default=0, type=int, help="setup value of l")
args = parser.parse_args()
def afunc(x):
return 2 * x
if __name__ == "__main__":
main()
Updated veryfi.py => test_it.py
- call the file
test_(something).py. Nose will then discover the file automatically.
- define clear focus of your test, in this case ignore the argument parsing and test only the
afunc
- (recommended) split to smaller test cases - your test run report will tell you much better, what really went wrong.
- (nose feature) use test generator as shown with
test_with_gen.
- possibly move the test(s) into
tests subdirectory. Just a habit. And it allows to target nose to tests with better precision.
Here is updated test_it.py:
import unittest
from comp import afunc
class TestFuncs(unittest.TestCase):
def test_afunc(self):
self.assertEqual(afunc(0), 0)
self.assertEqual(afunc(1), 2)
self.assertEqual(afunc(2), 4)
self.assertEqual(afunc(3.2), 6.4)
def test_case_0():
assert afunc(0) == 0
def test_case_1():
assert afunc(1) == 2
def test_with_gen():
plan = [(0, 0), (1, 2), (2, 4), (3.2, 6.4)]
for arg, expected in plan:
yield check_afunc, arg, expected
def check_afunc(arg, expected):
assert afunc(arg) == expected
Run the test:
$ nosetests -v
test_afunc (test_it.TestFuncs) ... ok
test_it.test_case_0 ... ok
test_it.test_case_1 ... ok
test_it.test_with_gen(0, 0) ... ok
test_it.test_with_gen(1, 2) ... ok
test_it.test_with_gen(2, 4) ... ok
test_it.test_with_gen(3.2, 6.4) ... ok
----------------------------------------------------------------------
Ran 7 tests in 0.005s
OK
noseexactly? What is name of the file you want to test and what is complete content? (or content as short as possible, but still showing the problem). What do you expectnoseto do?nosetestsexecutable thinksverifyis an argument rather than a file. Perhaps you could give it the full path to yourverify.pyfile or run nosetests from a more suitable location?nosetestsis passing argumentverifyand it shall beverify.py