Pytest和Django设置运行时更改

时间:2016-11-08 20:42:43

标签: python django pytest pytest-django

我有一个接收器需要知道DEBUGTrue是否设置为settings.py

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的{​​{1}}中进行检查,则pytest_configure设置为DEBUG。它稍后改变,我不知道在哪里。

这会导致什么?我相信我不会在我的代码中的任何地方更改它。

编辑。

conftest.py

True

MyApp的/测试/ 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()

pytest.ini

# 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

3 个答案:

答案 0 :(得分:2)

对于有类似问题的人。我找到了原因。我下载了pytest-django的源文件,发现它在pytest-django/pytest_django/plugin.py:338中将DEBUG设置为False。我不知道为什么。

答案 1 :(得分:1)

显然pytest-django明确将DEBUG设置为False(source code link)。

仔细研究pytest-django的git历史,可以做到与Django's default behaviorpytest commit link)相匹配。

来自Django文档:

  

不管配置文件中DEBUG设置的值如何,所有Django测试都以DEBUG = False运行。这是为了确保   您观察到的代码输出与在   生产设置。

作为一种解决方法,您可以使用pytest-django's settings fixture覆盖,因此DEBUG = True(如果需要)。例如,

def test_my_thing(settings):
    settings.DEBUG = True
    # ... do your test ...

答案 2 :(得分:0)

在 pytest.ini 文件中添加以下行:

django_debug_mode = True