I want to understand what part of setup is done in the setUp and setUpClass functions, as well as with tearDown and tearDownClass. The difference manifests itself when you have more than one test method in your class. The dots. Observe that setUp and tearDown appear before and after test1 and test2 , whereas setUpClass and tearDownClass appear only once, at the beginning and end of the whole test case.
The main difference as noted in the answer by Benjamin Hodgson is that setUpClass is called only once and that is before all the tests, while setUp is called immediately before each and every test.
NB: The same applies to the equivalent methods in other xUnit test frameworks, not just Python's unittest.
From the unittest documentation :. A class method called before tests in an individual class are run. Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure.
The default implementation does nothing. This part of the question has not been answered yet. As per my comment in response to the answer by Gearon, the setUp method is meant for elements of the fixture that are common to all tests to avoid duplicating that code in each test. I find this is often useful as removing duplication usually improves readability and reduces the maintenance burden. The setUpClass method is for expensive elements that you would rather only have to do once, such as opening a database connection, opening a temporary file on the filesystem, loading a shared library for testing, etc.
For production environments it is recommended that tests be driven by a continuous integration system such as Buildbot , Jenkins or Travis-CI , or AppVeyor. The unittest module provides a rich set of tools for constructing and running tests.
This section demonstrates that a small subset of the tools suffice to meet the needs of most users. A testcase is created by subclassing unittest. The three individual tests are defined with methods whose names start with the letters test.
This naming convention informs the test runner about which methods represent tests. The crux of each test is a call to assertEqual to check for an expected result; assertTrue or assertFalse to verify a condition; or assertRaises to verify that a specific exception gets raised.
These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report. The setUp and tearDown methods allow you to define instructions that will be executed before and after each test method.
They are covered in more detail in the section Organizing test code. The final block shows a simple way to run the tests. When run from the command line, the above script produces an output that looks like this:.
Passing the -v option to your test script will instruct unittest. The above examples show the most commonly used unittest features which are sufficient to meet many everyday testing needs. The remainder of the documentation explores the full feature set from first principles. The unittest module can be used from the command line to run tests from modules, classes or even individual test methods:. You can pass in a list with any combination of module names, and fully qualified class or method names.
This allows you to use the shell filename completion to specify the test module. The file specified must still be importable as a module. When executed without arguments Test Discovery is started:. Changed in version 3. The standard output and standard error streams are buffered during the test run.
Output during a passing test is discarded. Output is echoed normally on test fail or error and is added to the failure messages. Control - C during the test run waits for the current test to end and then reports all the results so far.
A second Control - C raises the normal KeyboardInterrupt exception. See Signal Handling for the functions that provide this functionality. Only run test methods and classes that match the pattern or substring. This option may be used multiple times, in which case all test cases that match any of the given patterns are included.
Patterns are matched against the fully qualified test method name as imported by the test loader. New in version 3. The command line can also be used for test discovery, for running all of the tests in a project or just a subset. Unittest supports simple test discovery.
In order to be compatible with test discovery, all of the test files must be modules or packages including namespace packages importable from the top-level directory of the project this means that their filenames must be valid identifiers.
Test discovery is implemented in TestLoader. The basic command-line usage is:. As a shortcut, python -m unittest is the equivalent of python -m unittest discover. If you want to pass arguments to test discovery the discover sub-command must be used explicitly. The discover sub-command has the following options:. Directory to start discovery. The -s , -p , and -t options can be passed in as positional arguments in that order. The following two command lines are equivalent:.
As well as being a path it is possible to pass a package name, for example myproject. The package name you supply will then be imported and its location on the filesystem will be used as the start directory. Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify it turns the paths into package names to import.
If you have a package installed globally and attempt test discovery on a different copy of the package then the import could happen from the wrong place. If this happens test discovery will warn you and exit. If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning. Note that you need to specify the top level directory too e.
The basic building blocks of unit testing are test cases — single scenarios that must be set up and checked for correctness. In unittest , test cases are represented by unittest. TestCase instances. The testing code of a TestCase instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases. The simplest TestCase subclass will simply implement a test method i.
If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors. Tests can be numerous, and their set-up can be repetitive.
Luckily, we can factor out set-up code by implementing a method called setUp , which the testing framework will automatically call for every single test we run:. The order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings. If the setUp method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed.
Similarly, we can provide a tearDown method that tidies up after the test method has been run:. If setUp succeeded, tearDown will be run whether the test method succeeded or not.
Such a working environment for the testing code is called a test fixture. A new TestCase instance is created as a unique test fixture used to execute each individual test method. It is recommended that you use TestCase implementations to group tests together according to the features they test. In most cases, calling unittest. You can place the definitions of test cases and test suites in the same modules as the code they are to test such as widget.
Some users will find that they have existing test code that they would like to run from unittest , without converting every old test function to a TestCase subclass. For this reason, unittest provides a FunctionTestCase class. This subclass of TestCase can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.
Even though FunctionTestCase can be used to quickly convert an existing test base over to a unittest -based system, this approach is not recommended. Taking the time to set up proper TestCase subclasses will make future test refactorings infinitely easier. In some cases, the existing tests may have been written using the doctest module.
If so, doctest provides a DocTestSuite class that can automatically build unittest. TestSuite instances from the existing doctest -based tests. Unittest supports skipping individual test methods and even whole classes of tests.
Skipping a test is simply a matter of using the skip decorator or one of its conditional variants, calling TestCase. This is useful when a resource that needs to be set up is not available.
Expected failures use the expectedFailure decorator. This decorator skips the test unless the passed object has a certain attribute:. Unconditionally skip the decorated test. Mark the test as an expected failure or error. If the test fails or errors in the test function itself rather than in one of the test fixture methods then it will be considered a success.
If the test passes, it will be considered a failure. Usually you can use TestCase. Skipped tests will not have setUp or tearDown run around them. Skipped classes will not have setUpClass or tearDownClass run.
Skipped modules will not have setUpModule or tearDownModule run. When there are very small differences among your tests, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the subTest context manager. This section describes in depth the API of unittest. Instances of the TestCase class represent the logical test units in the unittest universe.
This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. This class implements the interface needed by the test runner to allow it to drive the tests, and methods that the test code can use to check for and report various kinds of failure. Each instance of TestCase will run a single base method: the method named methodName. In most uses of TestCase , you will neither change the methodName nor reimplement the default runTest method.
This makes it easier to experiment with TestCase from the interactive interpreter. TestCase instances provide three groups of methods: one group used to run the test, another used by the test implementation to check conditions and report failures, and some inquiry methods allowing information about the test itself to be gathered. Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest , any exception raised by this method will be considered an error rather than a test failure.
The default implementation does nothing. Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state.
Any exception, other than AssertionError or SkipTest , raised by this method will be considered an additional error rather than a test failure thus increasing the total number of reported errors. This method will only be called if the setUp succeeds, regardless of the outcome of the test method. A class method called before tests in an individual class are run. See Class and Module Fixtures for more details.
A class method called after tests in an individual class have run. Run the test, collecting the result into the TestResult object passed as result. If result is omitted or None , a temporary result object is created by calling the defaultTestResult method and used.
The same effect may be had by simply calling the TestCase instance. Collectives on Stack Overflow. Learn more. Pyunit setUpClass not running Ask Question. Asked 10 years, 10 months ago.
Active 10 years, 10 months ago. Viewed 2k times. Improve this question. Mike Mike Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object. This class is used to compile information about the tests that have been successful and the tests that have met failure. A TestResult object stores the results of a set of tests.
A TestResult instance is returned by the TestRunner. A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test which raised an unexpected exception. Each tuple represents a test where a failure was explicitly signalled using the TestCase. A list containing 2-tuples of TestCase instances and strings holding the reason for skipping the test. If set to true, sys. Previous Page.
Next Page.
0コメント