Why doesn't python execute anything after 'unittest.main()' gets executed? - python

So let's say I have the following:
import unittest
class MyTests(unittest.TestCase):
def test001(self):
print 'This is test001'
def test002(self):
print 'This is test002'
if __name__ == '__main__':
unittest.main()
print 'Done'
And the output is:
>> This is test001
>> This is test002
>> ----------------------------------------------------------------------
>> Ran 2 tests in 0.001s
>> OK
And I was wondering why doesn't get to print 'Done' (or anything that comes after)?

Pass exit=False to the unittest.main() call (documentation):
unittest.main(exit=False)
Here's what I'm getting on the console:
$ python test.py
This is test001
.This is test002
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Done
FYI, under the hood unittest's TestProgram.runTests() calls sys.exit() if the value of exit is True (which is by default):
def runTests(self):
...
if self.exit:
sys.exit(not self.result.wasSuccessful())

Related

Unnitest printing extra information

I have the following unit test, which tests if a function returns true or not.
import unittest
from connection import *
class TestConnection(unittest.TestCase):
def test_connection_ok(self):
assertTrue(testConnection())
if __name__ == '__main__':
unittest.main()
It prints
<function testConnectionat 0x7fa5c0845790>
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Why does it print <function testConnectionat 0x7fa5c0845790>? Printing the result of testConnection() does not print <function testConnectionat 0x7fa5c0845790>, unless it's called on the unit test.

Run unittest.main() from a python invoke task

I am trying to run some unittest tests via a Python Invoke library, but my poor knowledge of Python prevents me from doing so.
This is the sample code I have:
my_tests.py
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
def main():
unittest.main()
if __name__ == '__main__':
main()
tasks.py
from invoke import task
#task
def tests(ctx):
main()
#task
def other_task(ctx):
print("This is fine")
def main():
import my_tests
import unittest
unittest.main(module='my_tests')
if __name__ == '__main__':
main()
And this is what I get:
C:\ittle_projects\invoke_unittest>python my_tests.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.002s
OK
C:\ittle_projects\invoke_unittest>python tasks.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
C:\ittle_projects\invoke_unittest>inv tests
E
======================================================================
ERROR: tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module 'my_tests' has no attribute 'tests'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
The tests run fine from my_tests.py and from tasks.py, but when I use invoke stuff breaks.
How can I make it work or where should I look next?
The issue you are running into is that unittest.main() uses the command line arguments your program is called with to determine which tests to run. Since your program is being executed as inv tests, the first argument to your program is tests, so unittest is attempting to run tests for a module name tests which does not exist.
You can get around this by popping the last argument (tests) from the system arguments list:
import sys
from invoke import task
#task
def tests(ctx):
# Pop "tests" off the end of the system arguments
sys.argv.pop()
main()
#task
def other_task(ctx):
print("This is fine")
def main():
import my_tests
import unittest
unittest.main(module='my_tests')
if __name__ == '__main__':
main()

Unittest not testing (python)

This is my code:
import unittest
from sallad.Puppgift import Kundenssallad
class Test_kundenssallad(unittest.TestCase):
def test_av_objekt(self):
namn = "Grekisksallad"
slutpris = 60
tillval = "gurka"
kundenssallad = Kundenssallad(namn, slutpris, tillval)
self.assertIsInstance(kundenssallad, Kundenssallad)
self.assertEqual(kundenssallad.slutpris, 60)
self.assertEqual(kundenssallad.tillval, "gurka")
if __name__ == "__main__":
unittest.main()
Upon running this code in PyCharm, I get:
Testing started at 11:32 ...
Process finished with exit code 0
I expected the program to print something like:
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
Why do the tests not seem to execute?
You have not told unittest what test suite to run.
pycharm not matching the if name == "main" ?
Try add some debug and print name.
Run it something like this:
if __name__ == "__main__":
unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(Test_kundenssallad)
unittest.TextTestRunner(verbosity=2).run(suite)

How to exit the script in a unittest test case

Here is a sample script that checks for a precondition in the very first test case and my intention is to abort the script if the precondition is not met.
#!/usr/bin/python
import unittest
import sys
class TestMyScript(unittest.TestCase):
def test_000_prerequisite(self):
a = 0
if not a:
sys.exit()
return
def test_001_test1(self):
print "Inside test 1"
return
def test_002_test2(self):
print "Inside test 2"
return
if __name__ == "__main__":
unittest.main()
However, the sys.exit() only exits from the individual test case of the suite. It doesn't exit the whole script.
I understand that unittest treats each test case individually which is why any exceptions caused by any testcase are handled by the test runner and it proceeds to the next test case.
But I want the script to kill itself. How do I do that?
Here is the output of my script:
./temp.py
EInside test 1
.Inside test 2
.
======================================================================
ERROR: test_000_prerequisite (__main__.TestMyScript)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./temp.py", line 9, in test_000_prerequisite
sys.exit()
SystemExit
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (errors=1)
My guess is that I have to mess around with TestRunner and kill the script if a test case returns some signal. But I am not sure how to really achieve it.
Here is the answer:
Stop testsuite if a testcase find an error
Here is the change I need to make when calling unittest.main(). The failfast keyword argument stops the script after the first failure.
if __name__ == "__main__":
unittest.main(failfast=True)
p.s. failfast keyword argument is only available for python 2.7+
p.p.s. you can also use failfast on unittest.TextTestRunner()

Increasing logging verbosity of class being unit-tested in Python

I have a Python class that uses the logging module to provide some debug output:
File someclass.py:
import logging
class SomeClass:
def do_stuff(self):
# do some things
logging.debug("I just did some stuff")
# do some more stuff
return True
I do unit testing on this class with the unittest module
File test_someclass.py
import unittest
from someclass import SomeClass
class SomeClassTests(unittest.TestCase):
def test_do_stuff(self):
obj = SomeClass()
self.assertFalse(obj.do_stuff())
def main():
unittest.main()
if __name__ == '__main__':
main()
What I want to do is show the debug messages while I am running the unit tests. I tried to set the verbosity to debug from the unit test module:
import logging
# ....
def main():
unittest.main()
logging.basicConfig(level=logging.DEBUG)
This didn't work. What would be the way to achieve this? Even better would be enabling DEBUG verbosity for only one test.
UPDATE:
Apparently it works when running it from the Python shell, but not in PyDev (it probably uses a different test runner).
If you want to output debug messages on failures only, using nose test runner would be the easiest way to go since nose captures stdout and print it out on failures. It works out of the box:
$ nosetests test.py
F
======================================================================
FAIL: test_stuff (test.SomeClass)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/../../test.py", line 7, in test_stuff
self.assertFalse(True)
AssertionError: True is not false
-------------------- >> begin captured stdout << ---------------------
I just did some stuff
--------------------- >> end captured stdout << ----------------------
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
where test.py contains:
from unittest import TestCase
class SomeClass(TestCase):
def test_stuff(self):
print "I just did some stuff"
self.assertFalse(True)
call unittest.main() from your main().
def main():
logging.basicConfig(level=logging.DEBUG)
unittest.main()
My output shows:
DEBUG:root:I just did some stuff
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
The basic example on unittests docs at: https://docs.python.org/2/library/unittest.html shows the simple way of calling and running a unit test from main.

Categories

Resources