Python : is coverage using skipped test - python

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.

Related

Python mock.patch is not mocking my function?

So I wrote a pretty simple test case and function. I can't seem to figure out the problem. Anyone have an idea? I feel like it should work.
import pandas
import unittest
from unittest import mock
from unittest.mock import MagicMock, Mock
def my_func():
temp = pandas.ExcelFile('temp.xlsx')
return temp.parse()
#mock.patch('pandas.ExcelFile')
def test_func(pd):
pd.parse.return_value = 10
print(pd.parse())
print(my_func())
Output just gives this:
10
<MagicMock name='ExcelFile().parse()' id='140620591125360'>
Provide a completed unit test solution based on #MrBean Bremen's comment.
index_63929989.py:
import pandas
def my_func():
temp = pandas.ExcelFile('temp.xlsx')
return temp.parse()
test_index_63929989.py:
import unittest
from unittest import mock
from index_63929989 import my_func
class TestIndex(unittest.TestCase):
#mock.patch('pandas.ExcelFile')
def test_func(self, mock_pd_excelFile):
mock_pd_excelFile.return_value.parse.return_value = 10
actual = my_func()
mock_pd_excelFile.assert_called_with('temp.xlsx')
self.assertEqual(actual, 10)
if __name__ == '__main__':
unittest.main()
unit test result with coverage report:
coverage run /Users/ldu020/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/63929989/test_index_63929989.py && coverage report -m --include="src/*"
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
---------------------------------------------------------------------------------
src/stackoverflow/63929989/index_63929989.py 4 0 100%
src/stackoverflow/63929989/test_index_63929989.py 11 0 100%
---------------------------------------------------------------------------------
TOTAL 15 0 100%

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/

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

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.

Categories

Resources