Nose supports two new kinds of tests: standalone test functions, and non-TestCase
test classes. It finds these tests by using the same pattern matching that it uses to find test modules. When looking through a module whose name matches the pattern, any functions or classes whose names also match the pattern are assumed to be tests.
We're going to write a few tests that demonstrate Nose's support for test functions and non-TestCase
test classes.
Let's create a new test file in the tests
directory, called nose_specific_tests.py
. Inside the file, put the following code:
import sys from sqlite3 import connect from imp import reload class grouped_tests: def setup(self): self.connection = connect(':memory:') cursor = self.connection.cursor() cursor.execute('create table test (a, b, c)') cursor.execute('''insert into test (a, b, c) values (1, 2, 3)''') self.connection.commit() def teardown(self): self.connection.close() def test_update(self): cursor = self.connection.cursor() cursor.execute('update test set b = 7 where a = 1') def test_select(self): cursor = self.connection.cursor() cursor.execute('select * from test limit 1') assert cursor.fetchone() == (1, 2, 3) def platform_setup(): sys.platform = 'test platform' def platform_teardown(): global sys sys = reload(sys) def standalone_test(): assert sys.platform == 'test platform' standalone_test.setup = platform_setup standalone_test.teardown = platform_teardown
Running Nose now doesn't print out very much, but the fact that the tests were run and didn't fail tells us a lot.
The grouped_tests
class contains a test fixture (the setup
and teardown
methods) and two tests; but it's not a unittest
TestCase
class. Nose recognized it as a test class because its name follows the same pattern that Nose looks for when it checks module names to find test modules. It then looks through the class for a test fixture and any test methods, and runs them appropriately.
Since the class isn't a TestCase
class, the tests don't have access to any of the unittest
assert
methods; Nose considers such a test to pass unless it raises an exception. Python has an assert
statement that raises an exception if its expression is false, which is helpful for just this sort of thing. It's not as nice as assertEqual
, but it does the job in many cases.
We wrote another test in the standalone_test
function. Like grouped_tests
, standalone_test
is recognized as a test by Nose because its name matches the same pattern that Nose uses to search for test modules. Nose runs standalone_test
as a test, and reports a failure if it raises an exception.
We were able to attach a test fixture to standalone_test
by setting its setup
and teardown
attributes to a pair of functions that we defined for that purpose. As usual, the setup
function runs before the test function and the teardown
function runs after the test function.
18.119.142.232