[TIP] setUp and tearDown behavior

Robert Collins robertc at robertcollins.net
Mon Jan 18 19:13:37 PST 2010


On Mon, 2010-01-18 at 21:37 -0500, Alfredo Deza wrote:
> I am building some tests for a Python installer that copies some files
> and changes some permissions.
> 
> Nothing weird there.
> 
> However, in the test class I am starting with a setUp that basically
> calls the installer (so the tests can see if everything is where it
> should be), this is followed by a few assertions and finally a
> tearDown is called where everything gets uninstalled.
> 
> When running the tests with nosetests, I see that setUp and tearDown
> are called for *every* method in my test class (e.g. installs => runs
> test method => uninstalls ....)

Thats expected. setUp sets up the environment for a single test.

> Isn't setUp supposed to be run once at the beginning of the class? or
> is this expected?
> 
> In case this is expected, is there a way to do it just once for all
> the methods?

I think nose has a per-class approach, or you can use testresources -
something like

class InstalledPackage(TestResource):

    def make(self, dependency_resources):
        # do the setup
        install_root = 'xxx'
        return install_root

    def clean(self, resource):
        shutil.rmtree(resource)

class MyTest(ResourcedTestCase):
    resources = [('installed_root', InstalledPackage())]

    def test_foo(self):
        self.assertEqual('foo',
            file(self.install_root + '/foo.txt', 'rb').read())


Cheers,
Rob
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20100119/f2a81f6f/attachment.pgp>


More information about the testing-in-python mailing list