nigel222
nigel222

Reputation: 8192

Django Testing: Error handling in setUpTestData

I want to write a test for a data-loading command, which creates a large number (thousands) of objects variously related by foreign keys. There are two ways I might structure it

  1. Invoke the management commands in setUpTestData, and then write data consistency tests as ordinary tests
  2. Write one large test method to run the management commands, and then subtests to check the data consistency

subtests are a Python unittest feature which the Django test runner inherits:

    with self.subTest("Subtest Foo"):
        self.assertFalse( True)           # FAIL message includes [Subtest Foo]
    with self.subTest("Subtest Bar"):
        self.assertFalse( True)           # and failure doesn't stop the next subtest from running

Is there any particular reason to prefer one over the other? Does setUpTestData wrap the entire class in a DB transaction, so the tests DB is left unchanged should it fail here rather than inside one or more of the tests?

Incidentally, I've never seen any reference to how to write a test that will never run unless the ./manage.py test ... command explicitly asks for it. So this might be useful to somebody:

from unittest import skipIf
import sys

@skipIf( not 'test123' in sys.argv, "Runs only with --tag test123")
@tag('test123')
class Test03( TestCase):
    ...

will run Test03 if and only if invoked with ./manage.py test ... --tag test123

Upvotes: 0

Views: 34

Answers (0)

Related Questions