Closed
Description
Typos such as mistakenly writing user.pk
instead of e.g. user.profile.pk
are sometimes not caught in tests (e.g. assert may pass as both have pk==1
). I wrote a small snippet to make such mistakes more easily blow up in tests. Perhaps a modification of it could be considered for an optional feature?
def setup_modified_seq(connection):
# detect cases where we are using the wrong pk (either in test or in code, e.g. user.pk vs user.profile.pk)
if connection.vendor == 'postgresql':
print('is postgres vnedor:', connection.vendor)
def get_seqs(cursor):
cursor.execute("SELECT c.relname FROM pg_class c WHERE c.relkind = 'S'")
for seq_row in cursor.fetchall():
seq = seq_row[0]
yield seq
cursor = connection.cursor()
for count, seq in enumerate(get_seqs(cursor)):
cursor.execute("ALTER SEQUENCE {} RESTART WITH %s;".format(seq), [(count+1)*1000])
and in hook def pytest_configure(config):
adding:
from django.db import connections
for connection in connections.all():
from pytest_django.db_reuse import _monkeypatch
create_test_db = connection.creation.create_test_db
def create_test_db_with_modified_sequences(self, *args, **kwargs):
create_test_db(*args, **kwargs)
setup_modified_seq(connection)
_monkeypatch(connection.creation, 'create_test_db', create_test_db_with_modified_sequences)