2016-11-08 6 views
0

У меня есть приемник, который должен знать, установлен ли DEBUG на True в моем settings.py.Настройки времени выполнения Pytest и Django

from django.conf import settings 
... 
@receiver(post_save, sender=User) 
def create_fake_firebaseUID(sender, instance, created=False, **kwargs): 
    # Fake firebaseUID if in DEBUG mode for development purposes 
    if created and settings.DEBUG: 
     try: 
      instance.userprofile 
     except ObjectDoesNotExist: 
      UserProfile.objects.create(user=instance, firebaseUID=str(uuid.uuid4())) 

Проблема заключается в том, что при создании пользователя с помощью manage.py shell все работает, как ожидалось. Однако, если я проведу свои тесты через py.test, значение settings.DEBUG изменится на False. Если я проверил его в conftest.py в pytest_configure, DEBUG настроен на True. Он меняется где-то позже, и я понятия не имею, где.

Что может быть причиной этого? Я уверен, что не меняю его нигде в своем коде.

Редактировать.

conftest.py

import uuid 

import pytest 
import tempfile 
from django.conf import settings 
from django.contrib.auth.models import User 


@pytest.fixture(scope='session', autouse=True) 
def set_media_temp_folder(): 
    with tempfile.TemporaryDirectory() as temp_dir: 
     settings.MEDIA_ROOT = temp_dir 
     yield None 


def create_normal_user() -> User: 
    username = str(uuid.uuid4())[:30] 
    user = User.objects.create(username=username) 
    user.set_password('12345') 
    user.save() 
    return user 


@pytest.fixture 
def normal_user() -> User: 
    return create_normal_user() 


@pytest.fixture 
def normal_user2() -> User: 
    return create_normal_user() 

MyApp/тесты/conftest.py

# encoding: utf-8 
import os 

import pytest 
from django.core.files.uploadedfile import SimpleUploadedFile 

from userprofile.models import ProfilePicture 


@pytest.fixture 
def test_image() -> bytes: 
    DIR_PATH = os.path.dirname(os.path.realpath(__file__)) 
    with open(os.path.join(DIR_PATH, 'test_image.jpg'), 'rb') as f: 
     yield f 


@pytest.fixture 
def profile_picture(test_image, normal_user) -> ProfilePicture: 
    picture = SimpleUploadedFile(name='test_image.jpg', 
           content=test_image.read(), 
           content_type='image/png') 
    profile_picture = ProfilePicture.objects.get(userprofile__user=normal_user) 
    profile_picture.picture = picture 
    profile_picture.save() 
    return profile_picture 

pytest.ini

[pytest] 
addopts = --reuse-db 
DJANGO_SETTINGS_MODULE=mysite.settings 
+0

Трудно сказать, почему ваши тесты показывают «DEBUG» как «False», если вы не предоставляете код для своих тестов. Было бы также полезно увидеть ваш 'conftest.py'. –

+1

Также вы используете импорт 'из настроек импорта django.conf'? Если вы импортируете свой модуль настроек напрямую, это может вызвать странные проблемы. –

ответ

0

Для тех, кто оказывает подобную проблему. Я нашел причину. Я загрузил исходные файлы pytest-django и обнаружил, что он устанавливает DEBUG в False в pytest-django/pytest_django/plugin.py:338. Я не знаю, зачем.