2016-11-08 71 views
0

我有一个接收器,需要知道我的settings.py中的DEBUG是否设置为TruePytest和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。如果我在pytest_configure中检查conftest.py,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的源文件,并发现它在pytest-django/pytest_django/plugin.py:338中将DEBUG设置为False。我不知道为什么。