Search code examples
djangodjango-testingdjango-tests

Django test fails to run migrations


I'm trying to run a test script, following this django doc (which is the version being used here). It quickly fails with a long stack. I've selected what's the possible culprit.

  File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
    self.code(from_state.apps, schema_editor)
  File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 185, in migrate
    add_sistema_entidade_e_orgao_composicao(apps, sistema)
  File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 16, in add_sistema_entidade_e_orgao_composicao
    user = get_user(apps)
  File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 7, in get_user
    return User.objects.filter(
  File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/query.py", line 318, in __getitem__
    return qs._result_cache[0]
IndexError: list index out of range

As a workaround, I modified django's query.py

if qs._result_cache:
  return qs._result_cache[0]
else: 
  return ""

Which worked, until the next error:

  File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
    self.code(from_state.apps, schema_editor)
  File "/home/user11/app-master/app/core/migrations/0016_auto_20201120_0934.py", line 106, in migrate
    sistema = Sistema.objects.get(nom_alias=sistema)
  File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/query.py", line 439, in get
    raise self.model.DoesNotExist(
__fake__.DoesNotExist: Sistema matching query does not exist.

Now I'm stuck. The test_database gets created with all the tables up to these migrations' errors, with the vast majority lacking any data. Among those that are empty is the table that this last error seems to refer to.

Note that I'm not the developer, I had no hand in creating the DB being used nor any of the migrations. I strongly suspect the database (Postgres12) has to be created/restored from a "minimal" backup before migrations can work properly. Could that be the reason for these failures? If so, what are my options for running a django test that doesn't alter the deployed database? Any options for running the test as a query block and then doing a rollback, as it's using Postgres?


Solution

  • After some talk to the rest of the team, it was decided to reset all migrations to ensure this type of problem no longer happens. Maybe not the "expected" solution, but a decent solution.