Skip to content

Commit 6c71fd3

Browse files
committed
added a unit test for a migration with a foreign key with references='self'
1 parent d3b8276 commit 6c71fd3

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

tests/apps/migrations/auto/test_migration_manager.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from piccolo.apps.migrations.auto import MigrationManager
66
from piccolo.apps.migrations.commands.base import BaseMigrationManager
77
from piccolo.columns import Varchar
8+
from piccolo.columns.base import OnDelete, OnUpdate
89

910
from tests.example_app.tables import Manager
1011
from tests.base import DBTestCase
@@ -145,6 +146,51 @@ def test_add_column(self):
145146
response = self.run_sync("SELECT * FROM manager;")
146147
self.assertEqual(response, [{"id": 1, "name": "Dave"}])
147148

149+
@postgres_only
150+
def test_add_foreign_key_self_column(self):
151+
"""
152+
Test adding a ForeignKey column to a MigrationManager, with a
153+
references argument of 'self'.
154+
"""
155+
manager = MigrationManager()
156+
manager.add_column(
157+
table_class_name="Manager",
158+
tablename="manager",
159+
column_name="advisor",
160+
column_class_name="ForeignKey",
161+
params={
162+
"references": "self",
163+
"on_delete": OnDelete.cascade,
164+
"on_update": OnUpdate.cascade,
165+
"default": None,
166+
"null": True,
167+
"primary": False,
168+
"key": False,
169+
"unique": False,
170+
"index": False,
171+
},
172+
)
173+
asyncio.run(manager.run())
174+
175+
self.run_sync("INSERT INTO manager VALUES (default, 'Alice', null);")
176+
self.run_sync("INSERT INTO manager VALUES (default, 'Dave', 1);")
177+
178+
response = self.run_sync("SELECT * FROM manager;")
179+
self.assertEqual(
180+
response,
181+
[
182+
{"id": 1, "name": "Alice", "advisor": None},
183+
{"id": 2, "name": "Dave", "advisor": 1},
184+
],
185+
)
186+
187+
# Reverse
188+
asyncio.run(manager.run_backwards())
189+
response = self.run_sync("SELECT * FROM manager;")
190+
self.assertEqual(
191+
response, [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Dave"}],
192+
)
193+
148194
@postgres_only
149195
def test_add_non_nullable_column(self):
150196
"""

0 commit comments

Comments
 (0)