Skip to content

Teardown should always occur #917

Closed
Closed
@ghostsquad

Description

@ghostsquad

teardown should always occur even if setup fails.

http://pythontesting.net/framework/unittest/unittest-wrong-teardown/

consider the following

class TestStuff:
    def setup(self):
        print "setup class:TestStuff"
        raise Exception

    def teardown(self):
        print "teardown class:TestStuff"

    def test_foo(self):
        print 'test_foo'

teardown never occurs.

The real-world scenario would be similar to this:
http://effbot.org/zone/python-with-statement.htm

with open("x.txt") as f:
   with open("y.txt") as f2:
       data1 = f.read()
       data2 = f2.read()

This is the correct usage if multiple resources need to be used simultaneously and cleaned up after.

Here's a real world testing scenario:

class TestStuff:
    f = None
    f2 = None

    def setup(self):
        self.f = open("x.txt")
        self.f2 = open("y.txt")

    def teardown(self):
       if self.f is not None:
           self.f.Close()
       if self.f2 is not None:
           self.f2.Close()

    def test_foo(self):
        # do something with f & f2

if x.txt exists, but y.txt does not exist, we have no chance to close self.f.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions