summaryrefslogtreecommitdiff
path: root/django_testscenarios/tests.py
blob: f9a1318d7944ded02d4834f150850a59d29f00eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Copyright (C) 2010, 2011, 2015 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#         Neil Williams <neil.williams@linaro.org>
#
# This file is part of django-testscenarios.
#
# django-testscenarios is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation
#
# django-testscenarios is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with django-testscenarios.  If not, see <http://www.gnu.org/licenses/>.

import unittest
import django

from django.db import models, transaction
from django.test import (
    TestCase as DjangoTestCase,
    TransactionTestCase as DjangoTransactionTestCase)

from django_testscenarios.ubertest import (
    TestCase,
    TestCaseWithScenarios,
    TransactionTestCase,
    TransactionTestCaseWithScenarios)


if hasattr(django, 'setup'):
    django.setup()


class TestModel(models.Model):
    """
    Model for testing database configuration/initialization
    """
    field = models.CharField(max_length=10, null=True)
    broken = models.IntegerField(default=1)


class ScenarioParametersAreVisibleChecks(object):

    scenarios = [
        ('scenario_a', {'attr': 'foo'}),
        ('scenario_b', {'attr': 'bar'}),
    ]

    def test_attr_is_set(self):
        self.assertNotEqual(getattr(self, 'attr'), None)


class PlainDatabaseChecks(object):

    def _do_check_for_database_state(self):
        self.assertEqual(TestModel.objects.all().count(), 0)
        obj = TestModel.objects.create()
        self.assertEqual(TestModel.objects.all().count(), 1)
        obj.delete()
        self.assertEqual(TestModel.objects.all().count(), 0)

    def test_database_is_empty_at_start_of_test_first(self):
        self._do_check_for_database_state()

    def test_database_is_empty_at_start_of_test_second(self):
        self._do_check_for_database_state()


class TransactionChecks(object):

    @transaction.atomic
    def _create_object(self):
        self.obj = TestModel.objects.create(field=None)
        self.pk = self.obj.pk

    def _reload_object(self):
        self.obj = TestModel.objects.get(pk=self.pk)

    def test_transaction_handling(self):
        with transaction.atomic():
            self._create_object()
        self._reload_object()
        self.assertEqual(self.obj.field, None)
        self.obj.field = "something"
        self.obj.save()
        try:
            self.obj.broken = 'not an integer'
        except ValueError:
            pass
        try:
            with transaction.atomic():
                self.obj.save()
        except ValueError:
            pass
        self._reload_object()
        self.assertEqual(self.obj.broken, 1)
        self.assertNotEqual(self.obj.field, None)


# Non-transaction tests


class TestsWorkWithPlainDjangoTestCase(DjangoTestCase,
                                       PlainDatabaseChecks):
    """
    Test class that is using:
        * plain database checks
        * django test case
    """


class TestsWorkWithTestToolsTestCase(TestCase,
                                     PlainDatabaseChecks):
    """
    Test class that is using:
        * plain database checks
        * test tools test case
    """
    def __hash__(self):
        return hash(repr(self))


class TestsWorkWithTestScenariosTestCaseAndNoScenarios(TestCaseWithScenarios,
                                                       PlainDatabaseChecks):
    """
    Test class that is using:
        * plain database checks
        * test tools test case
        * test scenarios test case
        * no actual scenarios (short-circuited fast path)
    """
    def __hash__(self):
        return hash(repr(self))


class TestsWorkWithTestScenariosTestCaseAndSomeScenarios(TestCaseWithScenarios,
                                                         ScenarioParametersAreVisibleChecks,
                                                         PlainDatabaseChecks):
    """
    Test class that is using:
        * database transactions
        * test tools test case
        * test scenarios test case
        * two dummy scenarios so that multiple test cases get generated
    """
    def __hash__(self):
        return hash(repr(self))


# Transaction tests


class TransactionsWorkWithPlainDjangoTestCase(DjangoTransactionTestCase,
                                              PlainDatabaseChecks,
                                              TransactionChecks):
    """
    Test class that is using:
        * database transactions
        * django test case (with transaction support)
    """
    def __hash__(self):
        return hash(repr(self))


class TransactionsWorkWithTestToolsTestCase(TransactionTestCase,
                                            PlainDatabaseChecks,
                                            TransactionChecks):
    """
    Test class that is using:
        * database transactions
        * test tools test case (with transaction support)
    """
    def __hash__(self):
        return hash(repr(self))


class TransactionsWorkWithTestScenariosTestCaseAndNoScenarios(TransactionTestCaseWithScenarios,
                                                              PlainDatabaseChecks,
                                                              TransactionChecks):
    """
    Test class that is using:
        * database transactions
        * test tools test case (with transaction support)
        * test scenarios test case (with transaction support)
        * no actual scenarios (short-circuited fast path)
    """
    def __hash__(self):
        return hash(repr(self))


class TransactionsWorkWithTestScenariosTestCaseAndSomeScenarios(TransactionTestCaseWithScenarios,
                                                                ScenarioParametersAreVisibleChecks,
                                                                PlainDatabaseChecks,
                                                                TransactionChecks):
    """
    Test class that is using:
        * database transactions
        * test tools test case (with transaction support)
        * test scenarios test case (with transaction support)
        * two dummy scenarios so that multiple test cases get generated
    """
    def __hash__(self):
        return hash(repr(self))


class TestReorderingNotBroken(DjangoTestCase):
    """
    Test that test suite reordering done inside DjangoTestSuiteRunner
    class (to optimize database setup/tear down code) is not going to
    reorder our improved test classes.
    """

    class Plain(TestCase):
        """" Empty test class inheriting from TestCase """
        def __hash__(self):
            return hash(repr(self))

        def runTest(self, result):
            pass

    class PlainScenarios(TestCaseWithScenarios):
        def __hash__(self):
            return hash(repr(self))

        def runTest(self, result):
            pass

    class Transaction(TransactionTestCase):
        """" Empty test class inheriting from TransactionTestCase """
        def __hash__(self):
            return hash(repr(self))

        def runTest(self, result):
            pass

    class TransactionScenarios(TransactionTestCaseWithScenarios):
        """" Empty test class inheriting from TransactionTestCase """
        def __hash__(self):
            return hash(repr(self))

        def runTest(self, result):
            pass

    def ensure_proper_order(self, initial_order, proper_order):
        """
        Create a TestSuite with test cases in initial_order, reorder
        them using the same logic that Django applies and verify that
        the order is proper_order
        """
        from django.test.runner import reorder_suite

        suite = unittest.TestSuite()
        for cls in initial_order:
            suite.addTest(cls())
        reordered_suite = reorder_suite(suite, (DjangoTestCase,))
        self.assertEqual(list(map(type, reordered_suite._tests)), proper_order)

    def test_transaction_test_case_stays_last(self):
        self.ensure_proper_order(
            [self.Plain, self.Transaction],
            [self.Plain, self.Transaction])

    def test_transaction_test_case_is_moved_to_be_last(self):
        self.ensure_proper_order(
            [self.Transaction, self.Plain],
            [self.Plain, self.Transaction])

    def test_transaction_scenarios_test_case_stays_last(self):
        self.ensure_proper_order(
            [self.Plain, self.TransactionScenarios],
            [self.Plain, self.TransactionScenarios])

    def test_transaction_scenarios_test_case_is_moved_to_be_last(self):
        self.ensure_proper_order(
            [self.TransactionScenarios, self.Plain],
            [self.Plain, self.TransactionScenarios])

    def test_plain_test_case_stays_first(self):
        self.ensure_proper_order(
            [self.Plain, self.Transaction],
            [self.Plain, self.Transaction])

    def test_plain_test_case_is_moved_to_be_first(self):
        self.ensure_proper_order(
            [self.Transaction, self.Plain],
            [self.Plain, self.Transaction])

    def test_plain_test_case_stays_first(self):
        self.ensure_proper_order(
            [self.Plain, self.Transaction],
            [self.Plain, self.Transaction])

    def test_plain_scenarios_test_case_is_moved_to_be_first(self):
        self.ensure_proper_order(
            [self.Transaction, self.PlainScenarios],
            [self.PlainScenarios, self.Transaction])

    def test_plain_scenarios_test_case_stays_first(self):
        self.ensure_proper_order(
            [self.PlainScenarios, self.Transaction],
            [self.PlainScenarios, self.Transaction])