Categories
Uncategorized

Talk Python unit testing framework (b): nose and its successor nose2


作者:HelloGitHub-Prodesire

HelloGitHub of “explain open source projects” series, Project address: https: //github.com/HelloGitHub-Team/Article

A, nose

nose is a third-party unit testing framework, it is fully compatible with the unittest, and claims to be a better use of the testing framework.

Then the nose in addition to all the features of unittest, but also has what advantage?

1.1 write use cases

Example of the preparation manner except that in the preparation of unittest.TestCase test class inheritance, but also can not write into the test class inheritance. For example, written in the form will be considered a test class nose:

from nose.tools import raises

class TestStringMethods:

    def test_upper(self):
        assert 'foo'.upper() == 'FOO'

    def test_isupper(self):
        assert 'FOO'.isupper()
        assert not 'Foo'.isupper()

    @raises(TypeError)
    def test_split(self):
        s = 'hello world'
        assert s.split() == ['hello', 'world']
        # check that s.split fails when the separator is not a string
        s.split(2)

Of course, the test class does not inherit unittest.TestCase, will not be able to use all kinds of methods assertXXX its built-in, which led to errors when patients can not be used to obtain more detailed contextual information.

In addition, nose-defined functions are also supported as a test, which gives many simple test scenarios bring great convenience:

def test_upper():
    assert 'foo'.upper() == 'FOO'

And performing discovery with Example 1.2

unittest supported use cases found and ability to execute, nose support.
    support the use of an automatic nose (recursively) found:

  • 默认发现当前目录下所有包含 test 的测试用例,但不包括以 _ 开头的用例

      Use nosetests command

  • 通过 -w 参数指定要自动发现的目录, -m 参数指定用例文件、目录、函数、类的名称模式(正则匹配)
    • nosetests -w project_directory "test_.+"

nose also support the implementation of the specified use cases:

  • 指定测试模块
    • nosetests test.module
  • 指定测试类
    • nosetests a.test:TestCase
  • 指定测试方法
    • nosetests another.test:TestCase.test_method
  • 指定测试文件路径
    • nosetests /path/to/test/file.py
  • 指定测试文件路径+测试类或测试函数(这是 unittest 所不支持的)
    • nosetests /path/to/test/file.py:TestCase
    • nosetests /path/to/test/file.py:TestCase.test_method
    • nosetests /path/to/test/file.py:test_function

1.3 test fixture (Fixtures)

In addition to supporting nose unittest supports pre-defined test and clean way, also supports a simpler definition of ways:

def setup_func():
    "set up test fixtures"

def teardown_func():
    "tear down test fixtures"

@with_setup(setup_func, teardown_func)
def test():
    "test ..."

Simply defined functions used to represent the front and two cleaning methods by nose.tools.with_setup decorator decorative function test, the nose will be performed before and after the pre-test and cleanup functions are performed are defined.

1.4 subtest / test generator

In addition to supporting unittest nose in TestCase.subTest, also supports a more powerful way of sub-write tests, that is, the test generator (Test generators), by the yield achieved.

In the following example, the definition of a test_evens test function, which generates five subtests check_even:

def test_evens():
    for i in range(0, 5):
        yield check_even, i, i*3

def check_even(n, nn):
    assert n % 2 == 0 or nn % 2 == 0

In addition, compared to unittest.TestCase.subTest multiple sub-test can only be performed once the pre-test and clean up, nose test generator can support each sub-test is performed once the pre-test and clean up, such as:

def test_generator():
    # ...
    yield func, arg, arg # ...

@with_setup(setup_func, teardown_func)
def func(arg):
    assert something_about(arg)

1.5 plug-in system

nose compared to a unittest biggest advantage is the plug-in system, comes with a lot of useful plug-ins, there are a wealth of third-party plug-ins. So you can do more things.

Which comes with plug-ins are as follows:

    AllModules: Example collected by all modules

    Attrib: tagging embodiment for use, and run with the embodiment containing the specified tag

    Capture: Capture standard output example of

    Collect: quickly gather use cases

    Cover: Statistical code coverage

    Debug: Debug when patients fail to enter the pdb with

    Deprecated: Deprecated cases labeled with

    Doctests: Running Documents Use Case

    Failure Detail: Assertion failed to provide contextual information

    Isolate: protective cases to avoid the influence of some of the side effects

    Logcapture: capture logging output

    Multiprocess: Parallel execution Example

    Prof: hot analyzer for analysis using

    Skip: Skip cases labeled with

    Testid: adding the test ID for each use case name of the output

    Xunit: Output format test results xunit

The third-party libraries are varied, such as nose-htmloutput used to generate test reports in HTML format, etc., is no longer listed here.

Thanks nose rich plug ecology, when the nose itself is not able to fully meet the needs of our test, you can install plug-ins, and line specifies specific parameters provided by the plug-in nosetests command can be very easy to use plug-ins.
    Compared to unittest, you can save a lot of their effort to develop additional test logic.

Two, nose2

nose2 is nose successor.
    Their idea is to make writing and running test cases easier.

They have many similarities, such as are compatible with unittest, supports function as a test case in support of child test, with plug-in system. But there are many different points, the following are some key differences:

  • 发现和载入测试

      Self loading nose to achieve the function module, an inert test mode loading module loads an execution a.

      nose2 built by the import () introduced into the module, and is first of all loaded, then execution Example

      nose2 not support all test items supported nose structure, such as a configuration file with the embodiment is not supported on the nose2:

.
`-- tests
    |-- more_tests
    |   `-- test.py
    `-- test.py
  • 测试前置和清理函数级别

      nose support methods, classes, modules, and package-level testing and pre-cleanup function

      nose2 package level testing and pre-cleanup function is not supported

  • 子测试

      In addition to supporting nose2 test generator used to achieve sub-test, but also supports the use of parametric test (Parameterized tests) to achieve subtest

      In addition to the same support as nose2 nose (not inherited in unittest.TestCase) supports parametric testing in the test generator and test functions and test classes, but also support the use of inheritance in test class unittest.TestCase

  • 配置化

      nose plug all the desired configuration configured via command line arguments

      nose2 is controlled by configuration files, command line parameters to minimize people read more comfortable

More detailed comparison of official documents.

III Summary

nose and nose2 do in the unittest compatible enough to see their target, that is to attract those users who use the original unittest to use them. They really did it!

nose and nose2 make improvements in the preparation of use cases, test fixtures, test the child has to make daily use case preparation easier and more flexible. While the introduction of plug-in system, will further enhance the capacity of the unit test framework a big step, which makes implementation and share a lot of higher-order functions on the basis of test functions as possible. No wonder many developers have a soft spot for them.


“Explain open source projects Series” – to let people interested in open source projects are no longer afraid, let sponsors open source projects are no longer alone. Follow our articles, you’ll discover the fun of programming, the use of open source projects and found to be involved so simple. Welcome messages to contact us, join us, so that more people fall in love with open source, open source contribution ~

Leave a Reply