From 1d317b1ecbae39c470357cd7eb5a454e2e5f4f07 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 23:16:00 +1100 Subject: [PATCH 01/20] Add django-test-migrations package --- requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index e4ffe6be75..f0e9fbef4d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -29,6 +29,7 @@ django-debug-toolbar==2.2 # Debug / profiling toolbar django-admin-shell==0.1.2 # Python shell for the admin interface django-money==1.1 # Django app for currency management certifi # Certifi is (most likely) installed through one of the requirements above -django-error-report==0.2.0 # Error report viewer for the admin interface +django-error-report==0.2.0 # Error report viewer for the admin interface +django-test-migrations==1.1.0 # Unit testing for database migrations inventree # Install the latest version of the InvenTree API python library From 34dbfe6d28cde72c21f26b93433f61b76e20570a Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 23:16:23 +1100 Subject: [PATCH 02/20] Test troublesome migration 0019 --- .../migrations/0019_auto_20200413_0642.py | 62 ++++++++------ InvenTree/company/test_migrations.py | 80 +++++++++++++++++++ 2 files changed, 119 insertions(+), 23 deletions(-) create mode 100644 InvenTree/company/test_migrations.py diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index 509c45aaa2..2bd059edb9 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -1,14 +1,21 @@ # Generated by Django 2.2.10 on 2020-04-13 06:42 +import sys import os from rapidfuzz import fuzz from django.db import migrations, connection from django.db.utils import OperationalError, ProgrammingError +""" +When this migration is tested by CI, it cannot accept user input. +So a simplified version of the migration is implemented. +""" +TESTING = 'test' in sys.argv def clear(): - os.system('cls' if os.name == 'nt' else 'clear') + if not TESTING: + os.system('cls' if os.name == 'nt' else 'clear') def reverse_association(apps, schema_editor): @@ -222,23 +229,31 @@ def associate_manufacturers(apps, schema_editor): clear() # Present a list of options - print("----------------------------------") + if not TESTING: + print("----------------------------------") + print("Checking part [{pk}] ({idx} of {total})".format(pk=part_id, idx=idx+1, total=total)) - print("Manufacturer name: '{n}'".format(n=name)) - print("----------------------------------") - print("Select an option from the list below:") + + if not TESTING: + print("Manufacturer name: '{n}'".format(n=name)) + print("----------------------------------") + print("Select an option from the list below:") - print("0) - Create new manufacturer '{n}'".format(n=name)) - print("") + print("0) - Create new manufacturer '{n}'".format(n=name)) + print("") - for i, m in enumerate(matches[:10]): - print("{i}) - Use manufacturer '{opt}'".format(i=i+1, opt=m)) + for i, m in enumerate(matches[:10]): + print("{i}) - Use manufacturer '{opt}'".format(i=i+1, opt=m)) - print("") - print("OR - Type a new custom manufacturer name") + print("") + print("OR - Type a new custom manufacturer name") while True: - response = str(input("> ")).strip() + if TESTING: + # When running unit tests, simply select the name of the part + response = '0' + else: + response = str(input("> ")).strip() # Attempt to parse user response as an integer try: @@ -300,18 +315,19 @@ def associate_manufacturers(apps, schema_editor): print("") clear() - print("---------------------------------------") - print("The SupplierPart model needs to be migrated,") - print("as the new 'manufacturer' field maps to a 'Company' reference.") - print("The existing 'manufacturer_name' field will be used to match") - print("against possible companies.") - print("This process requires user input.") - print("") - print("Note: This process MUST be completed to migrate the database.") - print("---------------------------------------") - print("") + if not TESTING: + print("---------------------------------------") + print("The SupplierPart model needs to be migrated,") + print("as the new 'manufacturer' field maps to a 'Company' reference.") + print("The existing 'manufacturer_name' field will be used to match") + print("against possible companies.") + print("This process requires user input.") + print("") + print("Note: This process MUST be completed to migrate the database.") + print("---------------------------------------") + print("") - input("Press to continue.") + input("Press to continue.") clear() diff --git a/InvenTree/company/test_migrations.py b/InvenTree/company/test_migrations.py new file mode 100644 index 0000000000..16d9059f23 --- /dev/null +++ b/InvenTree/company/test_migrations.py @@ -0,0 +1,80 @@ +""" +Tests for the company model database migrations +""" + +from django_test_migrations.contrib.unittest_case import MigratorTestCase + + +class TestManufacturerField(MigratorTestCase): + """ + Tests for migration 0019 which migrates from old 'manufacturer_name' field to new 'manufacturer' field + """ + + migrate_from = ('company', '0018_supplierpart_manufacturer') + migrate_to = ('company', '0019_auto_20200413_0642') + + def prepare(self): + """ + Prepare the database by adding some test data 'before' the change: + + - Part object + - Company object (supplier) + - SupplierPart object + """ + + Part = self.old_state.apps.get_model('part', 'part') + Company = self.old_state.apps.get_model('company', 'company') + SupplierPart = self.old_state.apps.get_model('company', 'supplierpart') + + # Create an initial part + part = Part.objects.create( + name='Screw', + description='A single screw' + ) + + # Create a company to act as the supplier + supplier = Company.objects.create( + name='Supplier', + description='A supplier of parts', + is_supplier=True, + is_customer=False, + ) + + # Add some SupplierPart objects + SupplierPart.objects.create( + part=part, + supplier=supplier, + SKU='SCREW.001', + manufacturer_name='ACME', + ) + + SupplierPart.objects.create( + part=part, + supplier=supplier, + SKU='SCREW.002', + manufacturer_name='Zero Corp' + ) + + self.assertEqual(Company.objects.count(), 1) + + def test_company_objects(self): + """ + Test that the new companies have been created successfully + """ + + # Two additional company objects should have been created + Company = self.new_state.apps.get_model('company', 'company') + self.assertEqual(Company.objects.count(), 3) + + # The new company/ies must be marked as "manufacturers" + acme = Company.objects.get(name='ACME') + self.assertTrue(acme.is_manufacturer) + + SupplierPart = self.new_state.apps.get_model('company', 'supplierpart') + parts = SupplierPart.objects.filter(manufacturer=acme) + self.assertEqual(parts.count(), 1) + part = parts.first() + + # Checks on the SupplierPart object + self.assertEqual(part.manufacturer_name, 'ACME') + self.assertEqual(part.manufacturer.name, 'ACME') From bd9447d9aac63d0dc8d78aad24691ea9ffb263cd Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 23:29:14 +1100 Subject: [PATCH 03/20] Add django-migration-linter to ensure django migrations are tippy-top --- InvenTree/InvenTree/settings.py | 1 + requirements.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index 06908e76bf..9587b09d4a 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -213,6 +213,7 @@ INSTALLED_APPS = [ 'djmoney', # django-money integration 'djmoney.contrib.exchange', # django-money exchange rates 'error_report', # Error reporting in the admin interface + 'django_migration_linter', # Linting checking for migration files ] MIDDLEWARE = CONFIG.get('middleware', [ diff --git a/requirements.txt b/requirements.txt index f0e9fbef4d..8c33b7d37e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -31,5 +31,6 @@ django-money==1.1 # Django app for currency management certifi # Certifi is (most likely) installed through one of the requirements above django-error-report==0.2.0 # Error report viewer for the admin interface django-test-migrations==1.1.0 # Unit testing for database migrations +django-migration-linter==2.5.0 # Linting checks for database migrations inventree # Install the latest version of the InvenTree API python library From c2b5d96186d7889a49771f9c92f2724898d75de0 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 23:39:43 +1100 Subject: [PATCH 04/20] Ensure migration files are covered in coverage tests --- .coveragerc | 2 -- 1 file changed, 2 deletions(-) diff --git a/.coveragerc b/.coveragerc index 409c378cac..dbfd8d176d 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,8 +1,6 @@ [run] source = ./InvenTree omit = - # Do not run coverage on migration files - */migrations/* InvenTree/manage.py InvenTree/setup.py InvenTree/InvenTree/middleware.py From f135f11564fa922931786f7f35a1b97600fe2f5d Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 23:56:59 +1100 Subject: [PATCH 05/20] Run lint checks on migration files --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index 52d0ef1c5c..071b50fec5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -48,6 +48,11 @@ script: - rm inventree_default_db.sqlite3 - invoke migrate - invoke import-records -f data.json + # Run linting checks on migration files (django-migration-linter) + # Run subset of linting checks on *ALL* migration files + - cd InvenTree && python manage.py lintmigrations --exclude-migration-test NOT_NULL ADD_UNIQUE -q ok ignore --no-cache && cd .. + # Run stricter checks on *NEW* migrations (old ones are what they are) + - cd InvenTree && python manage.py lintmigrations 79ddea50f507e34195bad635008419daac0d7a5f -q ok ignore --no-cache && cd .. after_success: - coveralls \ No newline at end of file From 5c8e65c2856a283de5d1537f0a8f7f02d9683391 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 00:01:16 +1100 Subject: [PATCH 06/20] Only run linter checks for *new* migration files --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 071b50fec5..872ef0eb0d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -50,8 +50,7 @@ script: - invoke import-records -f data.json # Run linting checks on migration files (django-migration-linter) # Run subset of linting checks on *ALL* migration files - - cd InvenTree && python manage.py lintmigrations --exclude-migration-test NOT_NULL ADD_UNIQUE -q ok ignore --no-cache && cd .. - # Run stricter checks on *NEW* migrations (old ones are what they are) + # Run strict migration file checks on *NEW* migrations (old ones are what they are) - cd InvenTree && python manage.py lintmigrations 79ddea50f507e34195bad635008419daac0d7a5f -q ok ignore --no-cache && cd .. after_success: From 29bb735dc4748d4f03e30a4f8776d1063c688e80 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 00:25:00 +1100 Subject: [PATCH 07/20] Helper functions to automatically extract migration file info --- InvenTree/InvenTree/helpers.py | 64 ++++++++++++++++++++++++++++ InvenTree/company/test_migrations.py | 27 ++++++++++++ 2 files changed, 91 insertions(+) diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index 99dc255dac..5cb6cc18dd 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -492,3 +492,67 @@ def addUserPermissions(user, permissions): for permission in permissions: addUserPermission(user, permission) + + +def getMigrationFileNames(app): + """ + Return a list of all migration filenames for provided app + """ + + local_dir = os.path.dirname(os.path.abspath(__file__)) + + migration_dir = os.path.join(local_dir, '..', app, 'migrations') + + files = os.listdir(migration_dir) + + # Regex pattern for migration files + pattern = r"^[\d]+_.*\.py$" + + migration_files = [] + + for f in files: + if re.match(pattern, f): + migration_files.append(f) + + return migration_files + + +def getOldestMigrationFile(app, exclude_extension=True): + """ + Return the filename associated with the oldest migration + """ + + oldest_num = -1 + oldest_file = None + + for f in getMigrationFileNames(app): + num = int(f.split('_')[0]) + + if oldest_file is None or num < oldest_num: + oldest_num = num + oldest_file = f + + if exclude_extension: + oldest_file = oldest_file.replace('.py', '') + + return oldest_file + +def getNewestMigrationFile(app, exclude_extension=True): + """ + Return the filename associated with the newest migration + """ + + newest_file = None + newest_num = -1 + + for f in getMigrationFileNames(app): + num = int(f.split('_')[0]) + + if newest_file is None or num > newest_num: + newest_num = num + newest_file = f + + if exclude_extension: + newest_file = newest_file.replace('.py', '') + + return newest_file diff --git a/InvenTree/company/test_migrations.py b/InvenTree/company/test_migrations.py index 16d9059f23..8ff2cc2a8b 100644 --- a/InvenTree/company/test_migrations.py +++ b/InvenTree/company/test_migrations.py @@ -4,6 +4,33 @@ Tests for the company model database migrations from django_test_migrations.contrib.unittest_case import MigratorTestCase +from InvenTree import helpers + + +class TestForwardMigrations(MigratorTestCase): + + migrate_from = ('company', helpers.getOldestMigrationFile('company')) + migrate_to = ('company', helpers.getNewestMigrationFile('company')) + + def prepare(self): + """ + Create some simple Company data, and ensure that it migrates OK + """ + + Company = self.old_state.apps.get_model('company', 'company') + + Company.objects.create( + name='MSPC', + description='Michael Scotts Paper Company', + is_supplier=True + ) + + def test_migrations(self): + + Company = self.new_state.apps.get_model('company', 'company') + + self.assertEqual(Company.objects.count(), 1) + class TestManufacturerField(MigratorTestCase): """ From e417ff2b4dd06e2dc83384109d2a8612f221e168 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 00:44:37 +1100 Subject: [PATCH 08/20] Test migrations for build app --- InvenTree/InvenTree/helpers.py | 6 +- .../build/migrations/0018_build_reference.py | 2 +- InvenTree/build/test_migrations.py | 118 ++++++++++++++++++ 3 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 InvenTree/build/test_migrations.py diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index 5cb6cc18dd..33136d76ce 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -517,7 +517,7 @@ def getMigrationFileNames(app): return migration_files -def getOldestMigrationFile(app, exclude_extension=True): +def getOldestMigrationFile(app, exclude_extension=True, ignore_initial=True): """ Return the filename associated with the oldest migration """ @@ -526,6 +526,10 @@ def getOldestMigrationFile(app, exclude_extension=True): oldest_file = None for f in getMigrationFileNames(app): + + if ignore_initial and f.startswith('0001_initial'): + continue + num = int(f.split('_')[0]) if oldest_file is None or num < oldest_num: diff --git a/InvenTree/build/migrations/0018_build_reference.py b/InvenTree/build/migrations/0018_build_reference.py index bcf4f9b9d4..e8fd938b6a 100644 --- a/InvenTree/build/migrations/0018_build_reference.py +++ b/InvenTree/build/migrations/0018_build_reference.py @@ -9,7 +9,7 @@ def add_default_reference(apps, schema_editor): Best we can do is use the PK of the build order itself. """ - Build = apps.get_model('build', 'Build') + Build = apps.get_model('build', 'build') count = 0 diff --git a/InvenTree/build/test_migrations.py b/InvenTree/build/test_migrations.py new file mode 100644 index 0000000000..1e95cfb54e --- /dev/null +++ b/InvenTree/build/test_migrations.py @@ -0,0 +1,118 @@ +""" +Tests for the build model database migrations +""" + +from django_test_migrations.contrib.unittest_case import MigratorTestCase + +from InvenTree import helpers + + +class TestForwardMigrations(MigratorTestCase): + """ + Test entire schema migration sequence for the build app + """ + + migrate_from = ('build', helpers.getOldestMigrationFile('build')) + migrate_to = ('build', helpers.getNewestMigrationFile('build')) + + def prepare(self): + """ + Create initial data! + """ + + Part = self.old_state.apps.get_model('part', 'part') + + buildable_part = Part.objects.create( + name='Widget', + description='Buildable Part', + active=True, + ) + + with self.assertRaises(TypeError): + # Cannot set the 'assembly' field as it hasn't been added to the db schema + Part.objects.create( + name='Blorb', + description='ABCDE', + assembly=True + ) + + Build = self.old_state.apps.get_model('build', 'build') + + Build.objects.create( + part=buildable_part, + title='A build of some stuff', + quantity=50 + ) + + def test_items_exist(self): + + Part = self.new_state.apps.get_model('part', 'part') + + self.assertEqual(Part.objects.count(), 1) + + Build = self.new_state.apps.get_model('build', 'build') + + self.assertEqual(Build.objects.count(), 1) + + # Check that the part object now has an assembly field + part = Part.objects.all().first() + part.assembly = True + part.save() + part.assembly = False + part.save() + + +class TestReferenceMigration(MigratorTestCase): + """ + Test custom migration which adds 'reference' field to Build model + """ + + migrate_from = ('build', helpers.getOldestMigrationFile('build')) + migrate_to = ('build', '0018_build_reference') + + def prepare(self): + """ + Create some builds + """ + + Part = self.old_state.apps.get_model('part', 'part') + + part = Part.objects.create( + name='Part', + description='A test part' + ) + + Build = self.old_state.apps.get_model('build', 'build') + + Build.objects.create( + part=part, + title='My very first build', + quantity=10 + ) + + Build.objects.create( + part=part, + title='My very second build', + quantity=10 + ) + + Build.objects.create( + part=part, + title='My very third build', + quantity=10 + ) + + # Ensure that the builds *do not* have a 'reference' field + for build in Build.objects.all(): + with self.assertRaises(AttributeError): + print(build.reference) + + def test_build_reference(self): + + Build = self.new_state.apps.get_model('build', 'build') + + self.assertEqual(Build.objects.count(), 3) + + # Check that the build reference is properly assigned + for build in Build.objects.all(): + self.assertEqual(str(build.reference), str(build.pk)) From 75431f0ee4f7fff9e1a1653cf45fb1562803c945 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 00:51:00 +1100 Subject: [PATCH 09/20] Flake errors --- InvenTree/InvenTree/helpers.py | 1 + setup.cfg | 2 ++ 2 files changed, 3 insertions(+) diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index 33136d76ce..62e50bd52f 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -540,6 +540,7 @@ def getOldestMigrationFile(app, exclude_extension=True, ignore_initial=True): oldest_file = oldest_file.replace('.py', '') return oldest_file + def getNewestMigrationFile(app, exclude_extension=True): """ diff --git a/setup.cfg b/setup.cfg index 6e2a44f055..ea232522a5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -9,6 +9,8 @@ ignore = C901, # - N802 - function name should be lowercase (In the future, we should conform to this!) N802, + # - N806 - variable should be lowercase + N806, N812, exclude = .git,__pycache__,*/migrations/*,*/lib/*,*/bin/*,*/media/*,*/static/*,*ci_*.py* max-complexity = 20 From b284fe7f2b706ff682684a14fcfe4bb3e8365b75 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 15:15:49 +1100 Subject: [PATCH 10/20] Remove quotes around column names (cherry picked from commit 386cb2dd3ac03de49b037e171109cf124001a030) --- InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index 2bd059edb9..fe35311201 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -165,7 +165,7 @@ def associate_manufacturers(apps, schema_editor): # Manually create a new database row # Note: Have to fill out all empty string values! - new_manufacturer_query = f"insert into company_company ('name', 'description', 'is_customer', 'is_supplier', 'is_manufacturer', 'address', 'website', 'phone', 'email', 'contact', 'link', 'notes') values ('{company_name}', '{company_name}', false, false, true, '', '', '', '', '', '', '');" + new_manufacturer_query = f"insert into company_company (name, description, is_customer, is_supplier, is_manufacturer, address, website, phone, email, contact, link, notes) values ('{company_name}', '{company_name}', false, false, true, '', '', '', '', '', '', '');" cursor = connection.cursor() From ad0b59bf11015349876e5d67a08b3afd803ff920 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 15:19:28 +1100 Subject: [PATCH 11/20] Bug fxi (cherry picked from commit 0e11b722be67175ad4d8cb80ae703441201a186a) --- InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index fe35311201..c07265f9eb 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -151,7 +151,7 @@ def associate_manufacturers(apps, schema_editor): # Have we already mapped this if name in links.keys(): - print(" - Part[{pk}]: Mapped '{n}' - '{c}'".format(pk=part_id, n=name, c=links[name].name)) + print(" - Part[{pk}]: Mapped '{n}' - manufacturer <{c}>".format(pk=part_id, n=name, c=links[name])) query = f"update part_supplierpart set manufacturer_id={manufacturer_id} where id={part_id};" result = query.execute() From 93f0dbd4eecc849e6498792543578bcf41d7d163 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 15:56:49 +1100 Subject: [PATCH 12/20] Bug fix: add missing line (cherry picked from commit 2303e03580d1b34976ac93c124d33d3aa32da238) --- InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index c07265f9eb..053bd62360 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -153,6 +153,8 @@ def associate_manufacturers(apps, schema_editor): if name in links.keys(): print(" - Part[{pk}]: Mapped '{n}' - manufacturer <{c}>".format(pk=part_id, n=name, c=links[name])) + manufacturer_id = links[name] + query = f"update part_supplierpart set manufacturer_id={manufacturer_id} where id={part_id};" result = query.execute() return True From d811f3c48a80ec703f1f457e41e6f11c0a0156b4 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Wed, 3 Feb 2021 15:57:15 +1100 Subject: [PATCH 13/20] Typo fix (cherry picked from commit c58399206c523b88594d63d5e696f6468639e466) --- InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index 053bd62360..1e1bcda922 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -156,7 +156,7 @@ def associate_manufacturers(apps, schema_editor): manufacturer_id = links[name] query = f"update part_supplierpart set manufacturer_id={manufacturer_id} where id={part_id};" - result = query.execute() + result = cursor.execute(query) return True # Mapping not possible From e407b99d0d1f89bab3d90fa519631b0088735f4e Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 09:13:11 +1100 Subject: [PATCH 14/20] Add initial migration unit test for the 'part' app --- InvenTree/part/test_migrations.py | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 InvenTree/part/test_migrations.py diff --git a/InvenTree/part/test_migrations.py b/InvenTree/part/test_migrations.py new file mode 100644 index 0000000000..0dbcdb1af8 --- /dev/null +++ b/InvenTree/part/test_migrations.py @@ -0,0 +1,52 @@ +""" +Unit tests for the part model database migrations +""" + +from django_test_migrations.contrib.unittest_case import MigratorTestCase + +from InvenTree import helpers + + +class TestForwardMigrations(MigratorTestCase): + """ + Test entire schema migration sequence for the part app + """ + + migrate_from = ('part', helpers.getOldestMigrationFile('part')) + migrate_to = ('part', helpers.getNewestMigrationFile('part')) + + def prepare(self): + """ + Create initial data + """ + + Part = self.old_state.apps.get_model('part', 'part') + + Part.objects.create(name='A', description='My part A') + Part.objects.create(name='B', description='My part B') + Part.objects.create(name='C', description='My part C') + Part.objects.create(name='D', description='My part D') + Part.objects.create(name='E', description='My part E') + + # Extract one part object to investigate + p = Part.objects.all().last() + + # Initially some fields are not present + with self.assertRaises(AttributeError): + print(p.has_variants) + + with self.assertRaises(AttributeError): + print(p.is_template) + + + def test_models_exist(self): + + Part = self.new_state.apps.get_model('part', 'part') + + self.assertEqual(Part.objects.count(), 5) + + for part in Part.objects.all(): + part.is_template = True + part.save() + part.is_template = False + part.save() From cabac6614cbe9f11ce711dce8f389c4131e05f46 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 09:13:23 +1100 Subject: [PATCH 15/20] Add unit test for currency migration --- InvenTree/company/test_migrations.py | 64 ++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/InvenTree/company/test_migrations.py b/InvenTree/company/test_migrations.py index 8ff2cc2a8b..1a51a5a5b0 100644 --- a/InvenTree/company/test_migrations.py +++ b/InvenTree/company/test_migrations.py @@ -105,3 +105,67 @@ class TestManufacturerField(MigratorTestCase): # Checks on the SupplierPart object self.assertEqual(part.manufacturer_name, 'ACME') self.assertEqual(part.manufacturer.name, 'ACME') + + +class TestCurrencyMigration(MigratorTestCase): + """ + Tests for upgrade from basic currency support to django-money + """ + + migrate_from = ('company', '0025_auto_20201110_1001') + migrate_to = ('company', '0026_auto_20201110_1011') + + def prepare(self): + """ + Prepare some data: + + - A part to buy + - A supplier to buy from + - A supplier part + - Multiple currency objects + - Multiple supplier price breaks + """ + + Part = self.old_state.apps.get_model('part', 'part') + + part = Part.objects.create( + name="PART", description="A purchaseable part", + purchaseable=True, + level=0, + tree_id=0, + lft=0, + rght=0 + ) + + Company = self.old_state.apps.get_model('company', 'company') + + supplier = Company.objects.create(name='Supplier', description='A supplier', is_supplier=True) + + SupplierPart = self.old_state.apps.get_model('company', 'supplierpart') + + sp = SupplierPart.objects.create(part=part, supplier=supplier, SKU='12345') + + Currency = self.old_state.apps.get_model('common', 'currency') + + aud = Currency.objects.create(symbol='$', suffix='AUD', description='Australian Dollars', value=1.0) + usd = Currency.objects.create(symbol='$', suffix='USD', description='US Dollars', value=1.0) + + PB = self.old_state.apps.get_model('company', 'supplierpricebreak') + + PB.objects.create(part=sp, quantity=10, cost=5, currency=aud) + PB.objects.create(part=sp, quantity=20, cost=3, currency=aud) + PB.objects.create(part=sp, quantity=30, cost=2, currency=aud) + + PB.objects.create(part=sp, quantity=40, cost=2, currency=usd) + PB.objects.create(part=sp, quantity=50, cost=2, currency=usd) + + for pb in PB.objects.all(): + self.assertIsNone(pb.price) + + def test_currency_migration(self): + + PB = self.new_state.apps.get_model('company', 'supplierpricebreak') + + for pb in PB.objects.all(): + # Test that a price has been assigned + self.assertIsNotNone(pb.price) From b107c54eb252deb9795f0f19fd383792ddb19720 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 09:13:45 +1100 Subject: [PATCH 16/20] PEP fix --- InvenTree/part/test_migrations.py | 1 - 1 file changed, 1 deletion(-) diff --git a/InvenTree/part/test_migrations.py b/InvenTree/part/test_migrations.py index 0dbcdb1af8..41fead4b30 100644 --- a/InvenTree/part/test_migrations.py +++ b/InvenTree/part/test_migrations.py @@ -38,7 +38,6 @@ class TestForwardMigrations(MigratorTestCase): with self.assertRaises(AttributeError): print(p.is_template) - def test_models_exist(self): Part = self.new_state.apps.get_model('part', 'part') From 140c8b5395a3e615a45835d1cd20d508a59ddebc Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 21:33:10 +1100 Subject: [PATCH 17/20] Use integer field instead of boolean literal (not correct SQL) --- InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index 1e1bcda922..8a7f3d5945 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -167,7 +167,7 @@ def associate_manufacturers(apps, schema_editor): # Manually create a new database row # Note: Have to fill out all empty string values! - new_manufacturer_query = f"insert into company_company (name, description, is_customer, is_supplier, is_manufacturer, address, website, phone, email, contact, link, notes) values ('{company_name}', '{company_name}', false, false, true, '', '', '', '', '', '', '');" + new_manufacturer_query = f"insert into company_company (name, description, is_customer, is_supplier, is_manufacturer, address, website, phone, email, contact, link, notes) values ('{company_name}', '{company_name}', 0, 0, 1, '', '', '', '', '', '', '');" cursor = connection.cursor() From 74704a7c1ef7a566a5850e88edbc7724510f4876 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 22:19:15 +1100 Subject: [PATCH 18/20] Mark migrations with data operations "non atomic" Ref: https://docs.djangoproject.com/en/dev/howto/writing-migrations/#non-atomic-migrations --- InvenTree/build/migrations/0013_auto_20200425_0507.py | 2 ++ InvenTree/build/migrations/0018_build_reference.py | 2 ++ InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 ++ .../company/migrations/0024_unique_name_email_constraint.py | 2 ++ InvenTree/company/migrations/0026_auto_20201110_1011.py | 2 ++ InvenTree/part/migrations/0020_auto_20190908_0404.py | 2 ++ InvenTree/part/migrations/0034_auto_20200404_1238.py | 2 ++ InvenTree/part/migrations/0039_auto_20200515_1127.py | 2 ++ InvenTree/part/migrations/0056_auto_20201110_1125.py | 2 ++ InvenTree/stock/migrations/0012_auto_20190908_0405.py | 2 ++ InvenTree/stock/migrations/0022_auto_20200217_1109.py | 2 ++ 11 files changed, 22 insertions(+) diff --git a/InvenTree/build/migrations/0013_auto_20200425_0507.py b/InvenTree/build/migrations/0013_auto_20200425_0507.py index d960e416c8..9a9eba06e2 100644 --- a/InvenTree/build/migrations/0013_auto_20200425_0507.py +++ b/InvenTree/build/migrations/0013_auto_20200425_0507.py @@ -17,6 +17,8 @@ def nupdate_tree(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('build', '0012_build_sales_order'), ] diff --git a/InvenTree/build/migrations/0018_build_reference.py b/InvenTree/build/migrations/0018_build_reference.py index e8fd938b6a..be4f7da36f 100644 --- a/InvenTree/build/migrations/0018_build_reference.py +++ b/InvenTree/build/migrations/0018_build_reference.py @@ -31,6 +31,8 @@ def reverse_default_reference(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('build', '0017_auto_20200426_0612'), ] diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index 8a7f3d5945..2468b864c2 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -354,6 +354,8 @@ def associate_manufacturers(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('company', '0018_supplierpart_manufacturer'), ] diff --git a/InvenTree/company/migrations/0024_unique_name_email_constraint.py b/InvenTree/company/migrations/0024_unique_name_email_constraint.py index e6d1fd93dd..b0fd88e780 100644 --- a/InvenTree/company/migrations/0024_unique_name_email_constraint.py +++ b/InvenTree/company/migrations/0024_unique_name_email_constraint.py @@ -19,6 +19,8 @@ def make_empty_email_field_null(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('company', '0023_auto_20200808_0715'), ] diff --git a/InvenTree/company/migrations/0026_auto_20201110_1011.py b/InvenTree/company/migrations/0026_auto_20201110_1011.py index 553eced0fc..c6be37b967 100644 --- a/InvenTree/company/migrations/0026_auto_20201110_1011.py +++ b/InvenTree/company/migrations/0026_auto_20201110_1011.py @@ -138,6 +138,8 @@ def reverse_currencies(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('company', '0025_auto_20201110_1001'), ] diff --git a/InvenTree/part/migrations/0020_auto_20190908_0404.py b/InvenTree/part/migrations/0020_auto_20190908_0404.py index 4f27191099..7766ba38f9 100644 --- a/InvenTree/part/migrations/0020_auto_20190908_0404.py +++ b/InvenTree/part/migrations/0020_auto_20190908_0404.py @@ -12,6 +12,8 @@ def update_tree(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('part', '0019_auto_20190908_0404'), ] diff --git a/InvenTree/part/migrations/0034_auto_20200404_1238.py b/InvenTree/part/migrations/0034_auto_20200404_1238.py index afd463d30d..3868191c02 100644 --- a/InvenTree/part/migrations/0034_auto_20200404_1238.py +++ b/InvenTree/part/migrations/0034_auto_20200404_1238.py @@ -18,6 +18,8 @@ def create_thumbnails(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('part', '0033_auto_20200404_0445'), ] diff --git a/InvenTree/part/migrations/0039_auto_20200515_1127.py b/InvenTree/part/migrations/0039_auto_20200515_1127.py index bc25097888..a95775f6a0 100644 --- a/InvenTree/part/migrations/0039_auto_20200515_1127.py +++ b/InvenTree/part/migrations/0039_auto_20200515_1127.py @@ -16,6 +16,8 @@ def nupdate_tree(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('part', '0038_auto_20200513_0016'), ] diff --git a/InvenTree/part/migrations/0056_auto_20201110_1125.py b/InvenTree/part/migrations/0056_auto_20201110_1125.py index 13a512bdd0..b382dded71 100644 --- a/InvenTree/part/migrations/0056_auto_20201110_1125.py +++ b/InvenTree/part/migrations/0056_auto_20201110_1125.py @@ -138,6 +138,8 @@ def reverse_currencies(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('part', '0055_auto_20201110_1001'), ] diff --git a/InvenTree/stock/migrations/0012_auto_20190908_0405.py b/InvenTree/stock/migrations/0012_auto_20190908_0405.py index 52071e5cd4..5f52e75093 100644 --- a/InvenTree/stock/migrations/0012_auto_20190908_0405.py +++ b/InvenTree/stock/migrations/0012_auto_20190908_0405.py @@ -13,6 +13,8 @@ def update_tree(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('stock', '0011_auto_20190908_0404'), ] diff --git a/InvenTree/stock/migrations/0022_auto_20200217_1109.py b/InvenTree/stock/migrations/0022_auto_20200217_1109.py index 0db3985361..f86fd51691 100644 --- a/InvenTree/stock/migrations/0022_auto_20200217_1109.py +++ b/InvenTree/stock/migrations/0022_auto_20200217_1109.py @@ -12,6 +12,8 @@ def update_stock_item_tree(apps, schema_editor): class Migration(migrations.Migration): + atomic = False + dependencies = [ ('stock', '0021_auto_20200215_2232'), ] From 3c5169c79310b010c0c6b3c30e57203a4e443385 Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 23:10:10 +1100 Subject: [PATCH 19/20] So I learned something today... In migration files you can access the "historical" pythonic model, and use that, with *all* the helpers, rather than writing clunky old SQL!!!! :'( --- .../migrations/0019_auto_20200413_0642.py | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index 2468b864c2..af84b485b3 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -165,24 +165,19 @@ def associate_manufacturers(apps, schema_editor): def create_manufacturer(part_id, input_name, company_name): """ Create a new manufacturer """ - # Manually create a new database row - # Note: Have to fill out all empty string values! - new_manufacturer_query = f"insert into company_company (name, description, is_customer, is_supplier, is_manufacturer, address, website, phone, email, contact, link, notes) values ('{company_name}', '{company_name}', 0, 0, 1, '', '', '', '', '', '', '');" + Company = apps.get_model('company', 'company') - cursor = connection.cursor() - - cursor.execute(new_manufacturer_query) - - # Extract the company back from the database - response = cursor.execute(f"select id from company_company where name='{company_name}';") - row = cursor.fetchone() - manufacturer_id = int(row[0]) + manufacturer = Company.objects.create( + name=company_name, + description=company_name, + is_manufacturer=True + ) # Map both names to the same company - links[input_name] = manufacturer_id - links[company_name] = manufacturer_id + links[input_name] = manufacturer.pk + links[company_name] = manufacturer.pk - companies[company_name] = manufacturer_id + companies[company_name] = manufacturer.pk print(" - Part[{pk}]: Created new manufacturer: '{name}'".format(pk=part_id, name=company_name)) From 978ea7cc0b9e082ea50bd7c4a454e21d7c7c733b Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 4 Feb 2021 23:11:19 +1100 Subject: [PATCH 20/20] Typo fix --- InvenTree/company/migrations/0019_auto_20200413_0642.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/InvenTree/company/migrations/0019_auto_20200413_0642.py b/InvenTree/company/migrations/0019_auto_20200413_0642.py index af84b485b3..fe283f561b 100644 --- a/InvenTree/company/migrations/0019_auto_20200413_0642.py +++ b/InvenTree/company/migrations/0019_auto_20200413_0642.py @@ -182,7 +182,7 @@ def associate_manufacturers(apps, schema_editor): print(" - Part[{pk}]: Created new manufacturer: '{name}'".format(pk=part_id, name=company_name)) # Update SupplierPart object in the database - cursor.execute(f"update part_supplierpart set manufacturer_id={manufacturer_id} where id={part_id};") + cursor.execute(f"update part_supplierpart set manufacturer_id={manufacturer.pk} where id={part_id};") def find_matches(text, threshold=65): """