Skip to content

Commit b76fb7f

Browse files
committed
✅(backend) fix migration test using model factory
Migration tests should not import and use factories or models directly from the code because they would not be in sync with the database in the state that each state needs to test it. Instead the migrator object passed as argument allows us to retrieve a minimal version of the models in sync with the state of the database that we are testing. What we get is a minimal model and we need to simulate all the methods that we could have on the real model and that are needed for testing.
1 parent bf17eea commit b76fb7f

File tree

2 files changed

+47
-35
lines changed

2 files changed

+47
-35
lines changed

src/backend/core/tests/migrations/test_0018_update_blank_title.py

Lines changed: 0 additions & 35 deletions
This file was deleted.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import pytest
2+
3+
from core import models
4+
5+
6+
@pytest.mark.django_db
7+
def test_update_blank_title_migration(migrator):
8+
"""
9+
Test that the migration fixes the titles of documents that are
10+
"Untitled document", "Unbenanntes Dokument" or "Document sans titre"
11+
"""
12+
old_state = migrator.apply_initial_migration(
13+
("core", "0017_add_fields_for_soft_delete")
14+
)
15+
OldDocument = old_state.apps.get_model("core", "Document")
16+
17+
old_english_doc = OldDocument.objects.create(
18+
title="Untitled document", depth=1, path="0000001"
19+
)
20+
old_german_doc = OldDocument.objects.create(
21+
title="Unbenanntes Dokument", depth=1, path="0000002"
22+
)
23+
old_french_doc = OldDocument.objects.create(
24+
title="Document sans titre", depth=1, path="0000003"
25+
)
26+
old_other_doc = OldDocument.objects.create(
27+
title="My document", depth=1, path="0000004"
28+
)
29+
30+
assert old_english_doc.title == "Untitled document"
31+
assert old_german_doc.title == "Unbenanntes Dokument"
32+
assert old_french_doc.title == "Document sans titre"
33+
assert old_other_doc.title == "My document"
34+
35+
# Apply the migration
36+
new_state = migrator.apply_tested_migration(("core", "0018_update_blank_title"))
37+
NewDocument = new_state.apps.get_model("core", "Document")
38+
39+
new_english_doc = NewDocument.objects.get(pk=old_english_doc.pk)
40+
new_german_doc = NewDocument.objects.get(pk=old_german_doc.pk)
41+
new_french_doc = NewDocument.objects.get(pk=old_french_doc.pk)
42+
new_other_doc = NewDocument.objects.get(pk=old_other_doc.pk)
43+
44+
assert new_english_doc.title == None
45+
assert new_german_doc.title == None
46+
assert new_french_doc.title == None
47+
assert new_other_doc.title == "My document"

0 commit comments

Comments
 (0)