GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.python-guide.org — Testing Your Code — The Hitchhiker's Guide to Python Testing Your Code¶
Testing your code is very important. Getting used to writing testing code and running this code in parallel is now considered a good habit. Used wisely, this method helps to define your code’s intent more precisely and have a more decoupled architecture. Some general rules of testing:
The Basics¶unittest¶
Creating test cases is accomplished by subclassing import unittest def fun(x): return x + 1 class MyTest(unittest.TestCase): def test(self): self.assertEqual(fun(3), 4) As of Python 2.7 unittest also includes its own test discovery mechanisms. Doctest¶The Doctests have a different use case than proper unit tests: they are usually less detailed and don’t catch special cases or obscure regression bugs. They are useful as an expressive documentation of the main use cases of a module and its components. However, doctests should run automatically each time the full test suite runs. A simple doctest in a function: def square(x): """Return the square of x. >>> square(2) 4 >>> square(-2) 4 """ return x * x if __name__ == '__main__': import doctest doctest.testmod() When running this module from the command line as in Tools¶py.test¶py.test is a no-boilerplate alternative to Python’s standard unittest module. $ pip install pytest
Despite being a fully-featured and extensible test tool, it boasts a simple syntax. Creating a test suite is as easy as writing a module with a couple of functions: # content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5 and then running the py.test command: $ py.test =========================== test session starts ============================ platform darwin -- Python 2.7.1 -- pytest-2.2.1 collecting ... collected 1 items test_sample.py F ================================= FAILURES ================================= _______________________________ test_answer ________________________________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:5: AssertionError ========================= 1 failed in 0.02 seconds ========================= is far less work than would be required for the equivalent functionality with the unittest module! Hypothesis¶Hypothesis is a library which lets you write tests that are parameterized by a source of examples. It then generates simple and comprehensible examples that make your tests fail, letting you find more bugs with less work. $ pip install hypothesis
For example, testing lists of floats will try many examples, but report the minimal example of each bug (distinguished exception type and location): @given(lists(floats(allow_nan=False, allow_infinity=False), min_size=1)) def test_mean(xs): mean = sum(xs) / len(xs) assert min(xs) <= mean(xs) <= max(xs) Falsifying example: test_mean(
xs=[1.7976321109618856e+308, 6.102390043022755e+303]
)
Hypothesis is practical as well as very powerful and will often find bugs that escaped all other forms of testing. It integrates well with py.test, and has a strong focus on usability in both simple and advanced scenarios. tox¶tox is a tool for automating test environment management and testing against multiple interpreter configurations. $ pip install tox
tox allows you to configure complicated multi-parameter test matrices via a simple INI-style configuration file. mock¶
For older versions of Python: $ pip install mock
It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. For example, you can monkey-patch a method: from mock import MagicMock thing = ProductionClass() thing.method = MagicMock(return_value=3) thing.method(3, 4, 5, key='value') thing.method.assert_called_with(3, 4, 5, key='value') To mock classes or objects in a module under test, use the def mock_search(self): class MockSearchQuerySet(SearchQuerySet): def __iter__(self): return iter(["foo", "bar", "baz"]) return MockSearchQuerySet() # SearchForm here refers to the imported class reference in myapp, # not where the SearchForm class itself is imported from @mock.patch('myapp.SearchForm.search', mock_search) def test_new_watchlist_activities(self): # get_search_results runs a search and iterates over the result self.assertEqual(len(myapp.get_search_results(q="fish")), 3) Mock has many other ways with which you can configure and control its behaviour. ©2011-2026 Kenneth Reitz & Real Python. CC BY-NC-SA 3.0 |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |