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


Author: 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 compatibleunittest , and is known as a better use of the testing framework.

Then noseaddition to unittestall the features, but also has what advantage?

1.1 write use cases

Example of the preparation manner except that in the preparation of inherited unittest.TestCase test class, but can also be written as not inherit test class . For example, written in the form will be nosetreated as a test class:

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 class does not inherit test unittest.TestCase, you will not be able to use all types of its built-in assertXXXmethod, which led unable to obtain more detailed information when an error occurs context use cases.

In addition, nosealso supports the definition of a function 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

unittestThe discovery supports the use cases and implementation capacity, noseare supported.
noseAutomatic support (recursively) found with Example:

  • The default found in the current directory that contains all testtest cases, but does not include _the beginning of the use case
    • Use noseteststhe command
  • By -wdirectory parameter specifies autodiscovered -mparameter specifies the file cases, a directory function, using the class name pattern (regular match)
    • nosetests -w project_directory "test_.+"

nose Also support the implementation of the specified use cases:

  • Specifies the test module
    • nosetests test.module
  • Specify the test class
    • nosetests a.test:TestCase
  • Specify test methods
    • nosetests another.test:TestCase.test_method
  • Specifies the test file path
    • nosetests /path/to/test/file.py
  • Specifying the test class file path + test or test function (which is unittestnot supported)
    • 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)

noseIn addition to supporting unittestsupports 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 decoration test function, noseperforms the pre-defined function and cleanup performed before and after each test.

1.4 subtest / test generator

noseIn addition to supporting unittestthe TestCase.subTest, also supports a more powerful way of sub-write tests, that is 测试生成器(Test generators), through the yieldimplementation.

In the following example, we define a test_evenstest 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 the unittest.TestCase.subTestmultiple sub-test can only be performed once the pre-test and clean up, nosethe 测试生成器supports each sub-test perform a 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

noseCompared to unittestone of the biggest advantages 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
  • The collect : use cases quickly gather
  • Cover : Statistical code coverage
  • Debug : Debug when patients fail to enter the pdb with
  • Of Deprecated : Deprecated cases labeled with
  • Doctests : Running Documents Use Case
  • The Detail Failure : Assertion failed to provide contextual information
  • An 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
  • The xUnit : Output format test results xunit

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

Thanks to nosea wealth of plug-in ecology, when nosetime itself is not able to fully meet the needs of our test, you can install plug-ins, and nosetestsspecify certain parameters for the plug-in provides a command line can be very easy to use plug-ins.
Compared to unittest, we 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 compatible 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:

  • Find and load test
    • nose Self-fulfilling function module loading, loading with inert way testing module, loading an execution a.
    • nose2By means of the built- Import () introduced into the module, and is first of all loaded, then execution Example
    • nose2Does not support noseall the supported structure test items, such as file structures as in the embodiment nose2in it are not supported:
.
`-- tests
    |-- more_tests
    |   `-- test.py
    `-- test.py
  • Pre-testing and cleanup function level
    • nose Support methods, classes, modules, and package-level testing and pre-cleanup function
    • nose2 Pre-package-level testing and cleanup function is not supported
  • Subtest
    • nose2In addition to supporting the test generator used to achieve sub-test, but also supports the use of parametric test (Parameterized tests) to achieve subtest
    • nose2In addition, like nosethe same function and test support in the test classes (not inherited unittest.TestCase) and supports parametric tests and test generator, but also to support the succession unittest.TestCaseusing the test class
  • Configuration of
    • nose All plug-in the desired configuration configured via command line arguments
    • nose2 It is controlled by configuration files, command line parameters to minimize people read more comfortable

More detailed comparison of official documents .

III Summary

noseAnd nose2in to be accommodating unitteston enough to see their target, that is to attract those using the original unittestuser to use them. They really did it!

noseAnd nose2make 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 ~

Guess you like

Origin www.cnblogs.com/xueweihan/p/11529101.html