TextTestRunner runs 2 tests (test_methods when one is called) in pyunit - python

I am just trying to understand the behavior of unittest's subclasses and methods. In the following code, I want to just run test_add method and not test_sub. Can someone please explain to me what I am doing wrong since the output proves that both the methods are being executed:
import unittest
def add(a,b):
x=a+b
return x
def sub(x,y):
z=x-y
return z
class addnum():
def calladd(self, a, b):
sum1 = add(a, b)
return sum1
def callsub(self,x,y):
diff = sub(x , y)
print "subtraction succ"
return diff
class test(addnum, unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
def test_add(self):
a1=addnum()
if a1.calladd(1, 2) ==3:
print "add successful"
assert addnum().calladd(1,2) == 3
def test_sub(self):
assert addnum().callsub(5, 3) == 2
print "abc"
#suite = unittest.TestSuite()
#suite.addTest(test('test_add'))
runner = unittest.TextTestRunner(verbosity=2)
runner.run(test(methodName='test_add'))
The output is as follows:
Finding files... done.
Importing test modules ... add successful
done.
add successful
subtraction succ
abc
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
test_add (trial2.test) ... ok
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Please help. I admit my knowledge is pretty limited at this point.

First of all, you should not place those lines at the end of your module alone. Otherwise, every time you import the module, this test will be run. You should wrap them like this:
if __name__ == "__main__":
#suite = unittest.TestSuite()
#suite.addTest(test('test_add'))
runner = unittest.TextTestRunner(verbosity=2)
runner.run(test(methodName='test_add'))
In this way, your code will be run only when the .py module is called alone and not imported. Once like that seems to work just fine and only runs the requested test.
test_add (__main__.test) ... ok
add successful
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Always wrap it like that so it does not matter if you forget to remove your test.

Related

Python : is coverage using skipped test

Here is a test :
#skip("my test is skipped")
def test_coverage():
my_function()
My question is simple :
If i run my coverage, will my_function will be covered or not (considering my test is skipped) ?
Thanks !
Skipped tests are not executed. Code that is not executed is not covered, by definition.
Demo; given a coverage_demo module:
def foo():
var = "This function has is covered"
def bar():
var = "This function is not"
and a coverage_demo_tests.py file:
from unittest import TestCase, skip
import coverage_demo
class DemoTests(TestCase):
def test_foo(self):
coverage_demo.foo()
#skip("No bar for us today")
def test_bar(self):
import coverage_demo
coverage_demo.bar()
if __name__ == '__main__':
import unittest
unittest.main()
running this under coverage shows that line 5 in coverage_demo is not executed:
$ coverage run coverage_demo_tests.py
s.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK (skipped=1)
$ coverage report --include=coverage_demo\.py -m
Name Stmts Miss Cover Missing
------------------------------------------------
coverage_demo.py 4 1 75% 5
The def statements at the top level are always executed, but line 5 is the only line in the bar() function.

Setup and teardown functions executed once for all nosetests tests

How to execute setup and teardown functions once for all nosetests tests?
def common_setup():
#time consuming code
pass
def common_teardown():
#tidy up
pass
def test_1():
pass
def test_2():
pass
#desired behavior
common_setup()
test_1()
test_2()
common_teardown()
Note that there exists a similar question with an answer that is not working with python 2.7.9-1, python-unittest2 0.5.1-1 and python-nose 1.3.6-1 after replacing the dots with pass and adding the line import unittest.
Unfortunately my reputation is too low to comment on that.
You can have a module level setup function. According to nose documentation:
Test modules offer module-level setup and teardown; define the method
setup, setup_module, setUp or setUpModule for setup, teardown,
teardown_module, or tearDownModule for teardown.
So, more specifically, for your case:
def setup_module():
print "common_setup"
def teardown_module():
print "common_teardown"
def test_1():
print "test_1"
def test_2():
print "test_2"
Running test gives you:
$ nosetests common_setup_test.py -s -v
common_setup
common_setup_test.test_1 ... test_1
ok
common_setup_test.test_2 ... test_2
ok
common_teardown
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
It does not matter which name you choose, so both setup and setup_module would work the same, but setup_module has more clarity to it.

Python Unit-Testing: In Nose is there a way to skip a test case from nose.run()?

I am writing a set of test cases say Test1, Test2 in a test module.
Is there a way to skip Test1 or selectively execute only Test2 in that module using the command nose.main()?
My module contains,
test_module.py,
class Test1:
setUp(self):
print('setup')
tearDown(self):
print('teardown')
test(self):
print('test1')
class Test2:
setUp(self):
print('setup')
tearDown(self):
print('teardown')
test(self):
print('test2')
I run it from a different python file using,
if __name__ == '__main__':
nose.main('test_module')
The notion of skipping test and not running a test are different in the context of nose: skipped tests will be reported as skipped at the end of the test result. If you want to skip the test you would have to monkey patch your test module with decorators or do some other dark magic.
But if you want to just not run a test, you can do it the same way you would do it from the command line: using --exclude option. It takes a regular expression of the test you do not want to run. Something like this:
import sys
import nose
def test_number_one():
pass
def test_number_two():
pass
if __name__ == '__main__':
module_name = sys.modules[__name__].__file__
nose.main(argv=[sys.argv[0],
module_name,
'--exclude=two',
'-v'
])
Running the test will give you:
$ python stackoverflow.py
stackoverflow.test_number_one ... ok
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK

Print a different long description in nose tests along with test name python

I am using the command:
nosetests test.py
When this is run only the first line of the description gets printed.
I want the whole description along with the test name. How do i do that?
test.py file
import unittests
class TestClass(unittest.TestCase):
def test_1(self):
"""this is a long description //
continues on second line which does not get printed """
some code;
self.assertTrue(True)
def test_2(self):
"""this is another or different long description //
continues on second line which does not get printed """
some code;
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
Unittest is documented as only showing the first line of the test method's docstring. But you could override the default implementation of shortDescription method to customise that behaviour:
import unittest
class TestClass(unittest.TestCase):
def shortDescription(self):
return self._testMethodDoc
def test_1(self):
"""this is a long description //
continues on second line """
self.assertTrue(True)
def test_2(self):
"""this is another or different long description //
continues on second line which also gets printed :) """
self.assertTrue(True)
if __name__ == '__main__':
unittest.main(verbosity=2)
Demo:
$ nosetests -v example.py
this is a long description //
continues on second line ... ok
this is another or different long description //
continues on second line which also gets printed :) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Someone wrote a nose plugin to fix this exact annoyance, maybe you'd be interested to use that. Here it is: https://bitbucket.org/natw/nose-description-fixer-plugin/

Python nose setup/teardown class fixture method not executed for test generators

In a hobby project I intend to use nose for testing, I want to put all tests for specific classes into classes since these tests share setup and other functionality. But I can't seem to get nose to execute the setup methods inside the classes.
Here is an example class that is tested:
class mwe():
def __init__(self):
self.example = ""
def setExample(self, ex):
self.example = ex
The tests work, when I don't use classes:
from nose.tools import ok_
import mwe
exampleList = []
def setUp():
print("setup")
exampleList.append("1")
exampleList.append("2")
exampleList.append("3")
def test_Example():
print("test")
for ex in exampleList:
t = mwe.mwe()
t.setExample(ex)
yield check, t, ex
def check(e, ex):
ok_(e.example == ex)
The output is as expected:
setup
test
...
----------------------------------------------------------------------
Ran 3 tests in 0.004s
OK
When a test class is used, the setup method is not executed and therefore no tests are executed.
from nose.tools import ok_
import mwe
class TestexampleClass(object):
def __init__(self):
print("__init__")
self.exampleList = []
def setup(self):
print("setup class")
self.exampleList.append("1")
self.exampleList.append("2")
self.exampleList.append("3")
def test_ExampleClass(self):
print("test class")
for ex in self.exampleList:
t = mwe.mwe()
t.setExample(ex)
yield self.check, t, ex
def check(self, we, ex):
print("check class")
ok_(we.example == ex)
I'm fairly new to python and a newbie with nose, my question is, why is setup not executed? Where is the error in my code?
__init__
test class
----------------------------------------------------------------------
Ran 0 tests in 0.002s
OK
I will be glad for any feedback.
When I use the code from this Question on SO the setup method is executed, as I would expect it.
SOLUTION: After a lot of desperation I found the following:
Nose executes the the class level setup method before the execution of the yielded function, not when the test_* methods are called, as I expected and as is the case for other test_* methods. This obviously goes against the nose documentation:
Setup and teardown functions may be used with test generators. However, please note that setup and teardown attributes attached to the generator function will execute only once. To execute fixtures for each yielded test, attach the setup and teardown attributes to the function that is yielded, or yield a callable object instance with setup and teardown attributes.
Looking at the bug reports, I found the bug report on github.
A possible workaround is to use class level fixtures:
#classmethod
def setup_class(cls):
#do stuff
pass
Your test class needs to extend TestCase and the setup method needs to be called setUp
from unittest import TestCase
class TestUtils(TestCase):
def setUp(self):
self.x = 1
def test_something(self):
self.assertEqual(1, self.x)
which outputs
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

Categories

Resources