/
test_commands.py
1955 lines (1765 loc) · 89.5 KB
/
test_commands.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import importlib
import io
import os
import sys
from unittest import mock
from django.apps import apps
from django.core.management import CommandError, call_command
from django.db import (
ConnectionHandler, DatabaseError, OperationalError, connection,
connections, models,
)
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.utils import truncate_name
from django.db.migrations.exceptions import InconsistentMigrationHistory
from django.db.migrations.recorder import MigrationRecorder
from django.test import TestCase, override_settings, skipUnlessDBFeature
from .models import UnicodeModel, UnserializableModel
from .routers import TestRouter
from .test_base import MigrationTestBase
class MigrateTests(MigrationTestBase):
"""
Tests running the migrate command.
"""
databases = {'default', 'other'}
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_migrate(self):
"""
Tests basic usage of the migrate command.
"""
# No tables are created
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
# Run the migrations to 0001 only
stdout = io.StringIO()
call_command('migrate', 'migrations', '0001', verbosity=2, stdout=stdout, no_color=True)
stdout = stdout.getvalue()
self.assertIn('Target specific migration: 0001_initial, from migrations', stdout)
self.assertIn('Applying migrations.0001_initial... OK', stdout)
self.assertIn('Running pre-migrate handlers for application migrations', stdout)
self.assertIn('Running post-migrate handlers for application migrations', stdout)
# The correct tables exist
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
# Run migrations all the way
call_command("migrate", verbosity=0)
# The correct tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
# Unmigrate everything
stdout = io.StringIO()
call_command('migrate', 'migrations', 'zero', verbosity=2, stdout=stdout, no_color=True)
stdout = stdout.getvalue()
self.assertIn('Unapply all migrations: migrations', stdout)
self.assertIn('Unapplying migrations.0002_second... OK', stdout)
self.assertIn('Running pre-migrate handlers for application migrations', stdout)
self.assertIn('Running post-migrate handlers for application migrations', stdout)
# Tables are gone
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
@override_settings(INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'migrations.migrations_test_apps.migrated_app',
])
def test_migrate_with_system_checks(self):
out = io.StringIO()
call_command('migrate', skip_checks=False, no_color=True, stdout=out)
self.assertIn('Apply all migrations: migrated_app', out.getvalue())
@override_settings(INSTALLED_APPS=['migrations', 'migrations.migrations_test_apps.unmigrated_app_syncdb'])
def test_app_without_migrations(self):
msg = "App 'unmigrated_app_syncdb' does not have migrations."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='unmigrated_app_syncdb')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_clashing_prefix'})
def test_ambiguous_prefix(self):
msg = (
"More than one migration matches 'a' in app 'migrations'. Please "
"be more specific."
)
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='migrations', migration_name='a')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_unknown_prefix(self):
msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='migrations', migration_name='nonexistent')
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"})
def test_migrate_initial_false(self):
"""
`Migration.initial = False` skips fake-initial detection.
"""
# Make sure no tables are created
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
# Run the migrations to 0001 only
call_command("migrate", "migrations", "0001", verbosity=0)
# Fake rollback
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
# Make sure fake-initial detection does not run
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0)
call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
# Real rollback
call_command("migrate", "migrations", "zero", verbosity=0)
# Make sure it's all gone
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
@override_settings(
MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
DATABASE_ROUTERS=['migrations.routers.TestRouter'],
)
def test_migrate_fake_initial(self):
"""
--fake-initial only works if all tables created in the initial
migration of an app exists. Database routers must be obeyed when doing
that check.
"""
# Make sure no tables are created
for db in self.databases:
self.assertTableNotExists("migrations_author", using=db)
self.assertTableNotExists("migrations_tribble", using=db)
# Run the migrations to 0001 only
call_command("migrate", "migrations", "0001", verbosity=0)
call_command("migrate", "migrations", "0001", verbosity=0, database="other")
# Make sure the right tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
# Also check the "other" database
self.assertTableNotExists("migrations_author", using="other")
self.assertTableExists("migrations_tribble", using="other")
# Fake a roll-back
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
# Make sure the tables still exist
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble", using="other")
# Try to run initial migration
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", "0001", verbosity=0)
# Run initial migration with an explicit --fake-initial
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other")
self.assertIn(
"migrations.0001_initial... faked",
out.getvalue().lower()
)
try:
# Run migrations all the way.
call_command('migrate', verbosity=0)
call_command('migrate', verbosity=0, database="other")
self.assertTableExists('migrations_author')
self.assertTableNotExists('migrations_tribble')
self.assertTableExists('migrations_book')
self.assertTableNotExists('migrations_author', using='other')
self.assertTableNotExists('migrations_tribble', using='other')
self.assertTableNotExists('migrations_book', using='other')
# Fake a roll-back.
call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0, database='other')
self.assertTableExists('migrations_author')
self.assertTableNotExists('migrations_tribble')
self.assertTableExists('migrations_book')
# Run initial migration.
with self.assertRaises(DatabaseError):
call_command('migrate', 'migrations', verbosity=0)
# Run initial migration with an explicit --fake-initial.
with self.assertRaises(DatabaseError):
# Fails because "migrations_tribble" does not exist but needs
# to in order to make --fake-initial work.
call_command('migrate', 'migrations', fake_initial=True, verbosity=0)
# Fake an apply.
call_command('migrate', 'migrations', fake=True, verbosity=0)
call_command('migrate', 'migrations', fake=True, verbosity=0, database='other')
finally:
# Unmigrate everything.
call_command('migrate', 'migrations', 'zero', verbosity=0)
call_command('migrate', 'migrations', 'zero', verbosity=0, database='other')
# Make sure it's all gone
for db in self.databases:
self.assertTableNotExists("migrations_author", using=db)
self.assertTableNotExists("migrations_tribble", using=db)
self.assertTableNotExists("migrations_book", using=db)
@skipUnlessDBFeature('ignores_table_name_case')
def test_migrate_fake_initial_case_insensitive(self):
with override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_fake_initial_case_insensitive.initial',
}):
call_command('migrate', 'migrations', '0001', verbosity=0)
call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
with override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_fake_initial_case_insensitive.fake_initial',
}):
out = io.StringIO()
call_command(
'migrate',
'migrations',
'0001',
fake_initial=True,
stdout=out,
verbosity=1,
no_color=True,
)
self.assertIn(
'migrations.0001_initial... faked',
out.getvalue().lower(),
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_fake_split_initial"})
def test_migrate_fake_split_initial(self):
"""
Split initial migrations can be faked with --fake-initial.
"""
try:
call_command('migrate', 'migrations', '0002', verbosity=0)
call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command('migrate', 'migrations', '0002', fake_initial=True, stdout=out, verbosity=1)
value = out.getvalue().lower()
self.assertIn('migrations.0001_initial... faked', value)
self.assertIn('migrations.0002_second... faked', value)
finally:
# Fake an apply.
call_command('migrate', 'migrations', fake=True, verbosity=0)
# Unmigrate everything.
call_command('migrate', 'migrations', 'zero', verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"})
def test_migrate_conflict_exit(self):
"""
migrate exits if it detects a conflict.
"""
msg = (
"Conflicting migrations detected; multiple leaf nodes in the "
"migration graph: (0002_conflicting_second, 0002_second in "
"migrations).\n"
"To fix them run 'python manage.py makemigrations --merge'"
)
with self.assertRaisesMessage(CommandError, msg):
call_command("migrate", "migrations")
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations',
})
def test_migrate_check(self):
with self.assertRaises(SystemExit):
call_command('migrate', 'migrations', '0001', check_unapplied=True)
self.assertTableNotExists('migrations_author')
self.assertTableNotExists('migrations_tribble')
self.assertTableNotExists('migrations_book')
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations_plan',
})
def test_migrate_check_plan(self):
out = io.StringIO()
with self.assertRaises(SystemExit):
call_command(
'migrate',
'migrations',
'0001',
check_unapplied=True,
plan=True,
stdout=out,
no_color=True,
)
self.assertEqual(
'Planned operations:\n'
'migrations.0001_initial\n'
' Create model Salamander\n'
' Raw Python operation -> Grow salamander tail.\n',
out.getvalue(),
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_showmigrations_list(self):
"""
showmigrations --list displays migrations and whether or not they're
applied.
"""
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: True):
call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
self.assertEqual(
'\x1b[1mmigrations\n\x1b[0m'
' [ ] 0001_initial\n'
' [ ] 0002_second\n',
out.getvalue().lower()
)
call_command("migrate", "migrations", "0001", verbosity=0)
out = io.StringIO()
# Giving the explicit app_label tests for selective `show_list` in the command
call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_initial\n'
' [ ] 0002_second\n',
out.getvalue().lower()
)
out = io.StringIO()
# Applied datetimes are displayed at verbosity 2+.
call_command('showmigrations', 'migrations', stdout=out, verbosity=2, no_color=True)
migration1 = MigrationRecorder(connection).migration_qs.get(app='migrations', name='0001_initial')
self.assertEqual(
'migrations\n'
' [x] 0001_initial (applied at %s)\n'
' [ ] 0002_second\n' % migration1.applied.strftime('%Y-%m-%d %H:%M:%S'),
out.getvalue().lower()
)
# Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_showmigrations_list_squashed(self):
out = io.StringIO()
call_command('showmigrations', format='list', stdout=out, verbosity=2, no_color=True)
self.assertEqual(
'migrations\n'
' [ ] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower(),
)
out = io.StringIO()
call_command(
'migrate',
'migrations',
'0001_squashed_0002',
stdout=out,
verbosity=2,
no_color=True,
)
try:
self.assertIn(
'operations to perform:\n'
' target specific migration: 0001_squashed_0002, from migrations\n'
'running pre-migrate handlers for application migrations\n'
'running migrations:\n'
' applying migrations.0001_squashed_0002... ok (',
out.getvalue().lower(),
)
out = io.StringIO()
call_command('showmigrations', format='list', stdout=out, verbosity=2, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower(),
)
finally:
# Unmigrate everything.
call_command('migrate', 'migrations', 'zero', verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
def test_showmigrations_plan(self):
"""
Tests --plan output of showmigrations command
"""
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third\n"
"[ ] migrations.0002_second\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third ... (migrations.0001_initial)\n"
"[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "0003", verbosity=0)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third\n"
"[ ] migrations.0002_second\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third ... (migrations.0001_initial)\n"
"[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
out.getvalue().lower()
)
# Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_plan'})
def test_migrate_plan(self):
"""Tests migrate --plan output."""
out = io.StringIO()
# Show the plan up to the third migration.
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0001_initial\n'
' Create model Salamander\n'
' Raw Python operation -> Grow salamander tail.\n'
'migrations.0002_second\n'
' Create model Book\n'
" Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
'migrations.0003_third\n'
' Create model Author\n'
" Raw SQL operation -> ['SELECT * FROM migrations_author']\n",
out.getvalue()
)
try:
# Migrate to the third migration.
call_command('migrate', 'migrations', '0003', verbosity=0)
out = io.StringIO()
# Show the plan for when there is nothing to apply.
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
' No planned migration operations.\n',
out.getvalue()
)
out = io.StringIO()
# Show the plan for reverse migration back to 0001.
call_command('migrate', 'migrations', '0001', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0003_third\n'
' Undo Create model Author\n'
" Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
'migrations.0002_second\n'
' Undo Create model Book\n'
" Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n",
out.getvalue()
)
out = io.StringIO()
# Show the migration plan to fourth, with truncated details.
call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0004_fourth\n'
' Raw SQL operation -> SELECT * FROM migrations_author WHE…\n',
out.getvalue()
)
# Show the plan when an operation is irreversible.
# Migrate to the fourth migration.
call_command('migrate', 'migrations', '0004', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0004_fourth\n'
' Raw SQL operation -> IRREVERSIBLE\n',
out.getvalue()
)
out = io.StringIO()
call_command('migrate', 'migrations', '0005', plan=True, stdout=out, no_color=True)
# Operation is marked as irreversible only in the revert plan.
self.assertEqual(
'Planned operations:\n'
'migrations.0005_fifth\n'
' Raw Python operation\n'
' Raw Python operation\n'
' Raw Python operation -> Feed salamander.\n',
out.getvalue()
)
call_command('migrate', 'migrations', '0005', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0005_fifth\n'
' Raw Python operation -> IRREVERSIBLE\n'
' Raw Python operation -> IRREVERSIBLE\n'
' Raw Python operation\n',
out.getvalue()
)
finally:
# Cleanup by unmigrating everything: fake the irreversible, then
# migrate all to zero.
call_command('migrate', 'migrations', '0003', fake=True, verbosity=0)
call_command('migrate', 'migrations', 'zero', verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_empty'})
def test_showmigrations_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', stdout=out, no_color=True)
self.assertEqual('migrations\n (no migrations)\n', out.getvalue().lower())
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
def test_showmigrations_unmigrated_app(self):
out = io.StringIO()
call_command('showmigrations', 'unmigrated_app', stdout=out, no_color=True)
try:
self.assertEqual('unmigrated_app\n (no migrations)\n', out.getvalue().lower())
finally:
# unmigrated_app.SillyModel has a foreign key to
# 'migrations.Tribble', but that model is only defined in a
# migration, so the global app registry never sees it and the
# reference is left dangling. Remove it to avoid problems in
# subsequent tests.
apps._pending_operations.pop(('migrations', 'tribble'), None)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"})
def test_showmigrations_plan_no_migrations(self):
"""
Tests --plan output of showmigrations command without migrations
"""
out = io.StringIO()
call_command('showmigrations', format='plan', stdout=out, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue().lower())
out = io.StringIO()
call_command('showmigrations', format='plan', stdout=out, verbosity=2, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue().lower())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
def test_showmigrations_plan_squashed(self):
"""
Tests --plan output of showmigrations command with squashed migrations.
"""
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[ ] migrations.1_auto\n"
"[ ] migrations.2_auto\n"
"[ ] migrations.3_squashed_5\n"
"[ ] migrations.6_auto\n"
"[ ] migrations.7_auto\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[ ] migrations.1_auto\n"
"[ ] migrations.2_auto ... (migrations.1_auto)\n"
"[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
"[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
"[ ] migrations.7_auto ... (migrations.6_auto)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[x] migrations.1_auto\n"
"[x] migrations.2_auto\n"
"[x] migrations.3_squashed_5\n"
"[ ] migrations.6_auto\n"
"[ ] migrations.7_auto\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[x] migrations.1_auto\n"
"[x] migrations.2_auto ... (migrations.1_auto)\n"
"[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
"[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
"[ ] migrations.7_auto ... (migrations.6_auto)\n",
out.getvalue().lower()
)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.mutate_state_b',
'migrations.migrations_test_apps.alter_fk.author_app',
'migrations.migrations_test_apps.alter_fk.book_app',
])
def test_showmigrations_plan_single_app_label(self):
"""
`showmigrations --plan app_label` output with a single app_label.
"""
# Single app with no dependencies on other apps.
out = io.StringIO()
call_command('showmigrations', 'mutate_state_b', format='plan', stdout=out)
self.assertEqual(
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
# Single app with dependencies.
out = io.StringIO()
call_command('showmigrations', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n',
out.getvalue()
)
# Some migrations already applied.
call_command('migrate', 'author_app', '0001', verbosity=0)
out = io.StringIO()
call_command('showmigrations', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[X] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n',
out.getvalue()
)
# Cleanup by unmigrating author_app.
call_command('migrate', 'author_app', 'zero', verbosity=0)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.mutate_state_b',
'migrations.migrations_test_apps.alter_fk.author_app',
'migrations.migrations_test_apps.alter_fk.book_app',
])
def test_showmigrations_plan_multiple_app_labels(self):
"""
`showmigrations --plan app_label` output with multiple app_labels.
"""
# Multiple apps: author_app depends on book_app; mutate_state_b doesn't
# depend on other apps.
out = io.StringIO()
call_command('showmigrations', 'mutate_state_b', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n'
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
# Multiple apps: args order shouldn't matter (the same result is
# expected as above).
out = io.StringIO()
call_command('showmigrations', 'author_app', 'mutate_state_b', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n'
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
def test_showmigrations_plan_app_label_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', 'unmigrated_app', format='plan', stdout=out, no_color=True)
try:
self.assertEqual('(no migrations)\n', out.getvalue())
finally:
# unmigrated_app.SillyModel has a foreign key to
# 'migrations.Tribble', but that model is only defined in a
# migration, so the global app registry never sees it and the
# reference is left dangling. Remove it to avoid problems in
# subsequent tests.
apps._pending_operations.pop(('migrations', 'tribble'), None)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_forwards(self):
"""
sqlmigrate outputs forward looking SQL.
"""
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
output = out.getvalue().lower()
index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
index_op_desc_author = output.find('-- create model author')
index_create_table = output.find('create table')
index_op_desc_tribble = output.find('-- create model tribble')
index_op_desc_unique_together = output.find('-- alter unique_together')
index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
if connection.features.can_rollback_ddl:
self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_tx_start,
"Operation description (author) not found or found before transaction start"
)
self.assertGreater(
index_create_table, index_op_desc_author,
"CREATE TABLE not found or found before operation description (author)"
)
self.assertGreater(
index_op_desc_tribble, index_create_table,
"Operation description (tribble) not found or found before CREATE TABLE (author)"
)
self.assertGreater(
index_op_desc_unique_together, index_op_desc_tribble,
"Operation description (unique_together) not found or found before operation description (tribble)"
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_backwards(self):
"""
sqlmigrate outputs reverse looking SQL.
"""
# Cannot generate the reverse SQL unless we've applied the migration.
call_command("migrate", "migrations", verbosity=0)
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True)
output = out.getvalue().lower()
index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
index_op_desc_unique_together = output.find('-- alter unique_together')
index_op_desc_tribble = output.find('-- create model tribble')
index_op_desc_author = output.find('-- create model author')
index_drop_table = output.rfind('drop table')
index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
if connection.features.can_rollback_ddl:
self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before DROP TABLE"
)
self.assertGreater(
index_op_desc_unique_together, index_tx_start,
"Operation description (unique_together) not found or found before transaction start"
)
self.assertGreater(
index_op_desc_tribble, index_op_desc_unique_together,
"Operation description (tribble) not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_op_desc_tribble,
"Operation description (author) not found or found before operation description (tribble)"
)
self.assertGreater(
index_drop_table, index_op_desc_author,
"DROP TABLE not found or found before operation description (author)"
)
# Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"})
def test_sqlmigrate_for_non_atomic_migration(self):
"""
Transaction wrappers aren't shown for non-atomic migrations.
"""
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
output = out.getvalue().lower()
queries = [q.strip() for q in output.splitlines()]
if connection.ops.start_transaction_sql():
self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_sqlmigrate_for_non_transactional_databases(self):
"""
Transaction wrappers aren't shown for databases that don't support
transactional DDL.
"""
out = io.StringIO()
with mock.patch.object(connection.features, 'can_rollback_ddl', False):
call_command('sqlmigrate', 'migrations', '0001', stdout=out)
output = out.getvalue().lower()
queries = [q.strip() for q in output.splitlines()]
start_transaction_sql = connection.ops.start_transaction_sql()
if start_transaction_sql:
self.assertNotIn(start_transaction_sql.lower(), queries)
self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_ambiguous_prefix_squashed_migrations(self):
msg = (
"More than one migration matches '0001' in app 'migrations'. "
"Please be more specific."
)
with self.assertRaisesMessage(CommandError, msg):
call_command('sqlmigrate', 'migrations', '0001')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_squashed_migration(self):
out = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_squashed_0002', stdout=out)
output = out.getvalue().lower()
self.assertIn('-- create model author', output)
self.assertIn('-- create model book', output)
self.assertNotIn('-- create model tribble', output)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_replaced_migration(self):
out = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_initial', stdout=out)
output = out.getvalue().lower()
self.assertIn('-- create model author', output)
self.assertIn('-- create model tribble', output)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_no_operations'})
def test_migrations_no_operations(self):
err = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_initial', stderr=err)
self.assertEqual(err.getvalue(), 'No operations found.\n')
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.migrated_unapplied_app",
"migrations.migrations_test_apps.unmigrated_app",
],
)
def test_regression_22823_unmigrated_fk_to_migrated_model(self):
"""
Assuming you have 3 apps, `A`, `B`, and `C`, such that:
* `A` has migrations
* `B` has a migration we want to apply
* `C` has no migrations, but has an FK to `A`
When we try to migrate "B", an exception occurs because the
"B" was not included in the ProjectState that is used to detect
soft-applied migrations (#22823).
"""
call_command('migrate', 'migrated_unapplied_app', verbosity=0)
# unmigrated_app.SillyModel has a foreign key to 'migrations.Tribble',
# but that model is only defined in a migration, so the global app
# registry never sees it and the reference is left dangling. Remove it
# to avoid problems in subsequent tests.
apps._pending_operations.pop(('migrations', 'tribble'), None)
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app_syncdb'])
def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
"""
For an app without migrations, editor.execute() is used for executing
the syncdb deferred SQL.
"""
stdout = io.StringIO()
with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
call_command('migrate', run_syncdb=True, verbosity=1, stdout=stdout, no_color=True)
create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
self.assertEqual(create_table_count, 2)
# There's at least one deferred SQL for creating the foreign key
# index.
self.assertGreater(len(execute.mock_calls), 2)
stdout = stdout.getvalue()
self.assertIn('Synchronize unmigrated apps: unmigrated_app_syncdb', stdout)
self.assertIn('Creating tables...', stdout)
table_name = truncate_name('unmigrated_app_syncdb_classroom', connection.ops.max_name_length())
self.assertIn('Creating table %s' % table_name, stdout)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_migrate_syncdb_app_with_migrations(self):
msg = "Can't use run_syncdb with app 'migrations' as it has migrations."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', 'migrations', run_syncdb=True, verbosity=0)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.unmigrated_app_syncdb',
'migrations.migrations_test_apps.unmigrated_app_simple',
])
def test_migrate_syncdb_app_label(self):
"""
Running migrate --run-syncdb with an app_label only creates tables for
the specified app.
"""
stdout = io.StringIO()
with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
call_command('migrate', 'unmigrated_app_syncdb', run_syncdb=True, stdout=stdout)
create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
self.assertEqual(create_table_count, 2)
self.assertGreater(len(execute.mock_calls), 2)
self.assertIn('Synchronize unmigrated app: unmigrated_app_syncdb', stdout.getvalue())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_migrate_record_replaced(self):
"""
Running a single squashed migration should record all of the original
replaced migrations as run.
"""
recorder = MigrationRecorder(connection)
out = io.StringIO()
call_command("migrate", "migrations", verbosity=0)
call_command("showmigrations", "migrations", stdout=out, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower()
)
applied_migrations = recorder.applied_migrations()
self.assertIn(("migrations", "0001_initial"), applied_migrations)
self.assertIn(("migrations", "0002_second"), applied_migrations)
self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
# Rollback changes
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_migrate_record_squashed(self):
"""
Running migrate for a squashed migration should record as run
if all of the replaced migrations have been run (#25231).
"""
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0001_initial")
recorder.record_applied("migrations", "0002_second")
out = io.StringIO()
call_command('showmigrations', 'migrations', stdout=out, no_color=True)
self.assertEqual(
"migrations\n"
" [-] 0001_squashed_0002 (2 squashed migrations) "
"run 'manage.py migrate' to finish recording.\n",
out.getvalue().lower(),
)
out = io.StringIO()
call_command("migrate", "migrations", verbosity=0)
call_command("showmigrations", "migrations", stdout=out, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower()
)
self.assertIn(
("migrations", "0001_squashed_0002"),
recorder.applied_migrations()
)
# No changes were actually applied so there is nothing to rollback
def test_migrate_partially_applied_squashed_migration(self):
"""
Migrating to a squashed migration specified by name should succeed
even if it is partially applied.
"""
with self.temporary_migration_module(module='migrations.test_migrations'):
recorder = MigrationRecorder(connection)
try:
call_command('migrate', 'migrations', '0001_initial', verbosity=0)
call_command(
'squashmigrations',
'migrations',
'0002',
interactive=False,
verbosity=0,
)
call_command(
'migrate',
'migrations',
'0001_squashed_0002_second',
verbosity=0,
)
applied_migrations = recorder.applied_migrations()
self.assertIn(('migrations', '0002_second'), applied_migrations)
finally:
# Unmigrate everything.
call_command('migrate', 'migrations', 'zero', verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_migrate_inconsistent_history(self):
"""
Running migrate with some migrations applied before their dependencies
should not be allowed.
"""
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0002_second")
msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("migrate")
applied_migrations = recorder.applied_migrations()
self.assertNotIn(("migrations", "0001_initial"), applied_migrations)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.migrated_unapplied_app',
'migrations.migrations_test_apps.migrated_app',
])
def test_migrate_not_reflected_changes(self):