diff --git a/django_db_comments/db_comments.py b/django_db_comments/db_comments.py index 3771224..7391be6 100644 --- a/django_db_comments/db_comments.py +++ b/django_db_comments/db_comments.py @@ -23,6 +23,11 @@ POSTGRES_COMMENT_ON_TABLE_SQL = sql.SQL("COMMENT ON TABLE {} IS %s") +# For TransactionTestCase tests, the post_migrate signal is fired as part of a flush +# operation after each test. We keep track of the apps we've synced the comments for +# in order to avoid syncing db comments after each test. +PROCESSED_APPS = set() + def get_comments_for_model(model): column_comments = {} @@ -91,6 +96,9 @@ def copy_help_texts_to_database( """ Create content types for models in the given app. """ + if app_config in PROCESSED_APPS: + return + PROCESSED_APPS.add(app_config) if not _check_app_config(app_config, using): return diff --git a/tests/test_db_comments.py b/tests/test_db_comments.py index c316690..21c573a 100644 --- a/tests/test_db_comments.py +++ b/tests/test_db_comments.py @@ -13,7 +13,7 @@ from django.apps import apps from django.db import models, DEFAULT_DB_ALIAS -from django.test import TestCase +from django.test import TestCase, TransactionTestCase try: from django.utils.translation import ugettext_lazy as _ @@ -116,6 +116,8 @@ class Meta: }, ) +class TestDbcommentsSignal(TransactionTestCase): + available_apps = ["django_db_comments", "tests"] def test_post_migrate_signal(self): app_config = apps.get_app_config("tests") with patch( @@ -129,12 +131,20 @@ def test_post_migrate_signal(self): "django_db_comments.db_comments.add_table_comments_to_database", return_value=True, ) as mock_table_comments: - copy_help_texts_to_database(app_config) - mock_table_comments.assert_called_once_with( - {"tests_examplemodel": "This Is An Example For Table Comment"}, - "default", - ) - mock_column_comments.assert_called_once_with( - {"tests_examplemodel": {"created_at": "model creation time"}}, - "default", - ) + with patch("django_db_comments.db_comments.PROCESSED_APPS", set()): + copy_help_texts_to_database(app_config) + mock_table_comments.assert_called_once_with( + {"tests_examplemodel": "This Is An Example For Table Comment"}, + "default", + ) + mock_column_comments.assert_called_once_with( + {"tests_examplemodel": {"created_at": "model creation time"}}, + "default", + ) + # make sure they're not called multiple times + mock_table_comments.reset_mock() + mock_column_comments.reset_mock() + + copy_help_texts_to_database(app_config) + mock_table_comments.assert_not_called() + mock_column_comments.assert_not_called()