1
# Copyright 2009 Canonical Ltd. This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
4
"""Tests for fixture support."""
10
from zope.interface import implements
12
from lp.testing import TestCase
13
from lp.testing.fixture import (
26
def __init__(self, log):
30
self.log.append('setUp')
33
self.log.append('tearDown')
36
class TestFixture(TestCase):
38
def test_run_with_fixture(self):
39
# run_with_fixture runs the setUp method of the fixture, the passed
40
# function and then the tearDown method of the fixture.
42
fixture = LoggingFixture(log)
43
run_with_fixture(fixture, log.append, 'hello')
44
self.assertEqual(['setUp', 'hello', 'tearDown'], log)
46
def test_run_tearDown_even_with_exception(self):
47
# run_with_fixture runs the setUp method of the fixture, the passed
48
# function and then the tearDown method of the fixture even if the
49
# function raises an exception.
51
fixture = LoggingFixture(log)
53
ZeroDivisionError, run_with_fixture, fixture, lambda: 1/0)
54
self.assertEqual(['setUp', 'tearDown'], log)
56
def test_with_fixture(self):
57
# with_fixture decorates a function so that it gets passed the fixture
58
# and the fixture is set up and torn down around the function.
60
fixture = LoggingFixture(log)
61
@with_fixture(fixture)
62
def function(fixture, **kwargs):
66
result = function(foo='bar')
67
self.assertEqual('oi', result)
68
self.assertEqual(['setUp', fixture, {'foo': 'bar'}, 'tearDown'], log)
71
class TestFixtureWithCleanup(TestCase):
72
"""Tests for `FixtureWithCleanup`."""
74
def test_cleanup_called_during_teardown(self):
76
fixture = FixtureWithCleanup()
78
fixture.addCleanup(log.append, 'foo')
79
self.assertEqual([], log)
81
self.assertEqual(['foo'], log)
83
def test_cleanup_called_in_reverse_order(self):
85
fixture = FixtureWithCleanup()
87
fixture.addCleanup(log.append, 'foo')
88
fixture.addCleanup(log.append, 'bar')
90
self.assertEqual(['bar', 'foo'], log)
92
def test_cleanup_run_even_in_failure(self):
94
fixture = FixtureWithCleanup()
96
fixture.addCleanup(log.append, 'foo')
97
fixture.addCleanup(lambda: 1/0)
98
self.assertRaises(ZeroDivisionError, fixture.tearDown)
99
self.assertEqual(['foo'], log)
102
class TestFixtures(TestCase):
103
"""Tests the `Fixtures` class, which groups multiple `IFixture`s."""
105
class LoggingFixture:
107
def __init__(self, log):
111
self._log.append((self, 'setUp'))
114
self._log.append((self, 'tearDown'))
116
def test_with_single_fixture(self):
118
a = self.LoggingFixture(log)
119
fixtures = Fixtures([a])
122
self.assertEqual([(a, 'setUp'), (a, 'tearDown')], log)
124
def test_with_multiple_fixtures(self):
126
a = self.LoggingFixture(log)
127
b = self.LoggingFixture(log)
128
fixtures = Fixtures([a, b])
132
[(a, 'setUp'), (b, 'setUp'), (b, 'tearDown'), (a, 'tearDown')],
137
return unittest.TestLoader().loadTestsFromName(__name__)