AI Briefing
KO

8Percent's Guide to Writing Python Django Test Cases

·2017.05.31 00:00

Key point

8Percent laid out standards for class names, function names, factories, timezone, and freezegun in Python Django testing.

Details

8Percent has put together an internal guide to follow when writing Test cases for Python Django code. The focus is on practical rules that improve both the readability and execution speed of tests.

For class names, when generally inheriting from TestCase, the suffix TestCase is appended to the end of the name. Since test function names only need to start with test_ to work, instead of writing a comment, the team writes a descriptive suffix in Korean after test_ to reveal intent.

  • Example: test_page_url_default
  • Example: test_page_url_without_querystring_appends_question_mark
  • Example: test_page_url_with_querystring_appends_ampersand

Instead of fixtures, factory_boy is preferred whenever possible. Signals also run when a model is created, but unless you're specifically testing the signal itself, it's better to turn them off with factory.django.mute_signals.

Test data should distinguish between setUpTestData and setUp. Objects that are only used as read-only should be created once in setUpTestData to improve speed, and setUp should only be used when an object needs to be created for every test. Where possible, it's more efficient to avoid unnecessarily creating objects every time in setUp.

When method mocking is needed, use unittest.mock.patch(). Use a decorator for individual tests, and when a mock needs to be shared across multiple tests, use start() and stopall().

  • Start with mock.patch(...).start() in setUp
  • Clean up with mock.patch.stopall() in tearDown

For handling time, the guide emphasizes timezone and freezegun. If a naive datetime created with datetime.now() or strptime() needs to be put into a Django DateTimeField, it must be converted to an aware datetime using django.utils.timezone.make_aware(). When you need to check a specific point in time, it's good practice to freeze time with freezegun and narrow its scope by applying it via a decorator or context manager.

To freeze time across an entire specific test case, you can use start() and stop(), but you must always release it with stop() so it doesn't affect other tests. Overall, this guide lays out how to write Django tests clearly, run them quickly, and handle time dependencies safely.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.