Fixtures

In unit testing, fixtures represent components that are set up before a test, and

cleaned up ater the test is done. It’s usuall a good idea to build a special kind

of component for them, as the are reused in a lot of different places. For example,

if ou need an object which represents the configuration state of our application,

there’s a chance ou ma want it to be initialied before each test, and reset

to its default values when the test is done. Reling on temporar file creation also

requires that the file is created before the test starts, and deleted once the test is

done.

unittest onl provides the setUp and tearDown functions we alread evoked. However,

a mechanism exists to hook into these. The fixtures Pthon module (not part

of the standard librar) provides an eas mechanism for creating fixture classes and

objects, such as the useFixture method.


The fixtures modules provides a few built-in fixtures, like fixtures.Environment

Variable – useful for adding or changing a variable in os.environ that will be reset

upon test exit.



Example . Using fixtures.EnvironmentVariable

import fixtures

import os

class TestEnviron(fixtures.TestWithFixtures):

def test_environ(self):

fixture = self.useFixture(

fixtures.EnvironmentVariable("FOOBAR", "42"))

self.assertEqual(os.environ.get("FOOBAR"), "42")

def test_environ_no_fixture(self):

self.assertEqual(os.environ.get("FOOBAR"), None)



When ou can identif common patterns like these, it’s a good idea to create a fixture

that ou can reuse over all our test cases. This greatl simplifies the logic, and

shows exactl what ou are testing and in what manner.


Note

If you’re wondering why the base class unittest.TestCase isn’t used in the examples

in this section, it’s because fixtures.TestWithFixtures inherits from it.



参考:1、http://www.tuicool.com/articles/mi6Nra

    2、the hacker guide to python