def setUp(self): super(TestingFullCycle, self).setUpClass() self.tests = ContextSuite(tests=[ case.Test(T('runTest')), case.Test(T('runBadTest')), case.Test(T('runFailingTest')) ])
def test_runner_collect_tests(self): test = ContextSuite(tests=[ self.loader.makeTest(T_fixt), self.loader.makeTest(T), case.Test(TC('runTest')) ]) kw = dict(tasks_queue=[], tasks_list=[], to_teardown=[], result=None) self.runner.collect_tasks(test, **kw) # Tasks Queue should_be_tasks = ['T_fixt', 'T.test_a', 'T.test_b', 'TC.runTest'] tasks = [addr.split(':')[-1] for addr, args in kw['tasks_queue']] self.assertEqual(tasks, should_be_tasks) # Tasks List should_be_tasks = [ 'T_fixt', 'T.test_a()', # args is a tuple. appended as string to base addr 'T.test_b()', # args is a tuple. appended as string to base addr 'TC.runTest' ] tasks = [addr.split(':')[-1] for addr in kw['tasks_list']] self.assertEqual(tasks, should_be_tasks)
def test_context_fixtures_setup_fails(self): class P: was_setup = False was_torndown = False def setup(self): self.was_setup = True assert False, "Setup failed" def teardown(self): self.was_torndown = True context = P() suite = ContextSuite( [self.TC('test_one'), self.TC('test_two')], context=context) res = unittest.TestResult() suite(res) assert not res.failures, res.failures assert res.errors, res.errors assert context.was_setup assert not context.was_torndown assert res.testsRun == 0, \ "Expected to run no tests but ran %s" % res.testsRun
def test_next_batch_with_classes(self): r = multiprocess.MultiProcessTestRunner() l = TestLoader() tests = list( r.nextBatch(ContextSuite( tests=[l.makeTest(T_fixt), l.makeTest(T)]))) print tests self.assertEqual(len(tests), 3)
def test_nested_context_suites(self): """Nested suites don't re-wrap""" suite = ContextSuite([self.TC('test_one'), self.TC('test_two')]) suite2 = ContextSuite(suite) suite3 = ContextSuite([suite2]) # suite3 is [suite2] tests = [t for t in suite3] assert isinstance(tests[0], ContextSuite) # suite2 is [suite] tests = [t for t in tests[0]] assert isinstance(tests[0], ContextSuite) # suite is full of wrapped tests tests = [t for t in tests[0]] cases = filter(lambda t: isinstance(t, case.Test), tests) assert cases assert len(cases) == len(tests)
def test_next_batch_with_classes(self): tests = list( self.runner.get_test_batch( ContextSuite(tests=[ self.loader.makeTest(T_fixt), self.loader.makeTest(T) ]))) print tests self.assertEqual(len(tests), 3)
def _put_transaction_test_cases_last(self, test): """Reorder tests in the suite so TransactionTestCase-based tests come last. Django has a weird design decision wherein TransactionTestCase doesn't clean up after itself. Instead, it resets the DB to a clean state only at the *beginning* of each test: https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs# django. test.TransactionTestCase. Thus, Django reorders tests so TransactionTestCases all come last. Here we do the same. "I think it's historical. We used to have doctests also, adding cleanup after each unit test wouldn't necessarily clean up after doctests, so you'd have to clean on entry to a test anyway." was once uttered on #django-dev. """ def filthiness(test): """Return a comparand based on whether a test is guessed to clean up after itself. Django's TransactionTestCase doesn't clean up the DB on teardown, but it's hard to guess whether subclasses (other than TestCase) do. We will assume they don't, unless they have a ``cleans_up_after_itself`` attr set to True. This is reasonable because the odd behavior of TransactionTestCase is documented, so subclasses should by default be assumed to preserve it. Thus, things will get these comparands (and run in this order): * 1: TestCase subclasses. These clean up after themselves. * 1: TransactionTestCase subclasses with cleans_up_after_itself=True. These include FastFixtureTestCases. If you're using the FixtureBundlingPlugin, it will pull the FFTCs out, reorder them, and run them first of all. * 2: TransactionTestCase subclasses. These leave a mess. * 2: Anything else (including doctests, I hope). These don't care about the mess you left, because they don't hit the DB or, if they do, are responsible for ensuring that it's clean (as per https://docs.djangoproject.com/en/dev/topics/testing/?from= olddocs#writing-doctests) """ test_class = test.context if (is_subclass_at_all(test_class, TestCase) or (is_subclass_at_all(test_class, TransactionTestCase) and getattr(test_class, 'cleans_up_after_itself', False))): return 1 return 2 flattened = [] process_tests(test, flattened.append) flattened.sort(key=filthiness) return ContextSuite(flattened)
def test_get_name_from_context_suite(self): """When the test is actually a ContextSuite, get the name from context. setUpClass/tearDownClass provides a ContextSuite object to the plugin if they raise an exception. The test case is not available so its name must be pulled from a different location. """ plugin = self._make_one() context = mock.Mock(__name__='FakeContext') test = ContextSuite(context=context) name = plugin._cls_name(test) self.assertEqual(name, 'FakeContext')
def test_result_proxy_used(self): class TC(unittest.TestCase): def runTest(self): raise Exception("error") ResultProxy.called[:] = [] res = unittest.TestResult() config = Config() suite = ContextSuite([TC()], resultProxy=ResultProxyFactory()) suite(res) calls = [c[0] for c in ResultProxy.called] self.assertEqual(calls, ['beforeTest', 'startTest', 'addError', 'stopTest', 'afterTest'])
def suite_sorted_by_fixtures(suite): """Flatten and sort a tree of Suites by the ``fixtures`` members of their contexts. Add ``_fb_should_setup_fixtures`` and ``_fb_should_teardown_fixtures`` attrs to each test class to advise it whether to set up or tear down (respectively) the fixtures. Return a Suite. """ bucketer = Bucketer() process_tests(suite, bucketer.add) # Lay the bundles of common-fixture-having test classes end to end # in a single list so we can make a test suite out of them: flattened = [] for ((fixtures, is_exempt), fixture_bundle) in bucketer.buckets.items(): # Advise first and last test classes in each bundle to set up # and tear down fixtures and the rest not to: if fixtures and not is_exempt: # Ones with fixtures are sure to be classes, which means # they're sure to be ContextSuites with contexts. # First class with this set of fixtures sets up: first = fixture_bundle[0].context first._fb_should_setup_fixtures = True # Set all classes' 1..n should_setup to False: for cls in fixture_bundle[1:]: cls.context._fb_should_setup_fixtures = False # Last class tears down: last = fixture_bundle[-1].context last._fb_should_teardown_fixtures = True # Set all classes' 0..(n-1) should_teardown to False: for cls in fixture_bundle[:-1]: cls.context._fb_should_teardown_fixtures = False flattened.extend(fixture_bundle) flattened.extend(bucketer.remainder) return ContextSuite(flattened)
def test_context_fixtures_called(self): class P: was_setup = False was_torndown = False def setup(self): self.was_setup = True def teardown(self): self.was_torndown = True context = P() suite = ContextSuite( [self.TC('test_one'), self.TC('test_two')], context=context) res = unittest.TestResult() suite(res) assert not res.errors, res.errors assert not res.failures, res.failures assert context.was_setup assert context.was_torndown
def test_context_fixtures_no_tests_no_setup(self): class P: was_setup = False was_torndown = False def setup(self): self.was_setup = True def teardown(self): self.was_torndown = True context = P() suite = ContextSuite([], context=context) res = unittest.TestResult() suite(res) assert not res.failures, res.failures assert not res.errors, res.errors assert not context.was_setup assert not context.was_torndown assert res.testsRun == 0, \ "Expected to run no tests but ran %s" % res.testsRun
def test_tests_are_wrapped(self): """Tests in a context suite are wrapped""" suite = ContextSuite([self.TC('test_one'), self.TC('test_two')]) for test in suite: assert isinstance(test.test, self.TC)
def to_context_suite(self): tests = [] for _, child in sorted(self.children.items()): tests.append(child.to_context_suite()) tests.extend(self.tests) return ContextSuite(tests, self.context)