- May 3, 2016
- testing unittest database migration
- 0 (after 0 ratings)
DB migration support has been added in Django 1.7+, superseding South. More specifically, it's possible to automatically generate migrations steps when one or more changes in the application models are detected. Definitely a nice feature!
I've written a small generic unit-test that one should be able to drop into the tests directory of any Django project and that checks there's no pending migrations, ie. if the models are correctly in sync with the migrations declared in the application. Handy to check nobody has forgotten to git add the migration file or that an innocent looking change in models.py doesn't need a migration step generated. Enjoy!
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
# The MIT License (MIT) # # Copyright (c) 2016 Damien Lespiau # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys from cStringIO import StringIO from contextlib import contextmanager from django.core import management from django.test import TestCase @contextmanager def capture(command, *args, **kwargs): out, sys.stdout = sys.stdout, StringIO() command(*args, **kwargs) sys.stdout.seek(0) yield sys.stdout.read() sys.stdout = out def makemigrations(): management.call_command('makemigrations') class MigrationTest(TestCase): def testPendingMigration(self): """Make sure there's no pending migration.""" with capture(makemigrations) as output: self.assertEqual(output, "No changes detected\n")
More like this
- Serialize a model instance by chriswedgwood 1 week, 2 days ago
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 1 week ago
- Crispy Form by sourabhsinha396 10 months ago
- ReadOnlySelect by mkoistinen 10 months, 2 weeks ago
- Verify events sent to your webhook endpoints by santos22 11 months, 2 weeks ago