Project

General

Profile

0001-prevent-inconsistent-use-of-db-alias-36028.patch

Emmanuel Cazenave, 12 Sep 2019 11:01 AM

Download (3.27 KB)

View differences:

Subject: [PATCH] prevent inconsistent use of db alias (#36028)

 django_journal/journal.py |  7 ++++++-
 test_settings.py          | 12 +++++++++++-
 tests/test_main.py        | 15 ++++++++++++++-
 3 files changed, 31 insertions(+), 3 deletions(-)
django_journal/journal.py
1 1
import logging
2 2

  
3 3
from django.conf import settings
4
from django.contrib.contenttypes.models import ContentType
4 5
import django.db.models
5 6

  
6 7
from .decorator import atomic
......
55 56
            continue
56 57
        tag = Tag.objects.using(using).get_cached(name=name)
57 58
        if isinstance(value, django.db.models.Model):
58
            journal.objectdata_set.create(tag=tag, content_object=value)
59
            journal.objectdata_set.create(
60
                tag=tag, content_type=ContentType.objects.db_manager(using).get_for_model(value),
61
                object_id=value.pk
62
            )
59 63
        else:
60 64
            journal.stringdata_set.create(tag=tag, content=unicode(value))
61 65
    return journal
......
71 75
    '''
72 76
    if kwargs.get('using') is None:
73 77
        kwargs['using'] = getattr(settings, 'JOURNAL_DB_FOR_ERROR_ALIAS', 'default')
78

  
74 79
    return record(tag, tpl, **kwargs)
test_settings.py
3 3
    'django.contrib.sessions'
4 4
)
5 5
DATABASES = {
6
    'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2'}
6
    'default': {
7
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
8
        'NAME': '_test'
9
    },
10
    'error': {
11
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
12
        'NAME': '_test'
13
    }
7 14
}
15

  
8 16
SECRET_KEY = "django_tests_secret_key"
9 17
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
10 18
ROOT_URLCONF = 'test_urls'
19

  
20
JOURNAL_DB_FOR_ERROR_ALIAS = 'error'
tests/test_main.py
5 5

  
6 6
from django_journal.journal import record, error_record
7 7
from django_journal.actions import export_as_csv_generator
8
from django_journal.models import Journal
8
from django_journal.models import Journal, Tag
9 9

  
10 10

  
11 11
class JournalTestCase(TestCase):
......
63 63
    # specifying None as database use the defaut one
64 64
    error_record('error', 'error message', using=None)
65 65
    assert Journal.objects.count() == 2
66

  
67

  
68
def test_error_record_with_db_obj(db):
69
    tag = Tag.objects.create(name='some-tag')
70
    journal = error_record('error', 'error message', someobj=tag)
71
    objdata = journal.objectdata_set.first()
72
    assert objdata.object_id == tag.pk
73

  
74
    # If journal is not deleted test_export_as_csv crashes
75
    # probably some db rollback not done since error_record
76
    # uses a different db router
77
    # to be investigated
78
    journal.delete()
66
-