Qub*_*uba 6 python django pytest pytest-django
我有一个接收器需要知道是否DEBUG设置为True我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()))
Run Code Online (Sandbox Code Playgroud)
问题是,当我使用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()
Run Code Online (Sandbox Code Playgroud)
myapp/tests/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
Run Code Online (Sandbox Code Playgroud)
pytest.ini
[pytest]
addopts = --reuse-db
DJANGO_SETTINGS_MODULE=mysite.settings
Run Code Online (Sandbox Code Playgroud)
对于任何有类似问题的人。我找到了原因。我下载了 pytest-django 的源文件,发现它在pytest-django/pytest_django/plugin.py:338. 我不知道为什么。
显然 pytest-django 明确地将 DEBUG 设置为 False (源代码链接)。
深入了解 pytest-django 的 git 历史,这样做是为了匹配Django 的默认行为(pytest commit link)。
来自 Django 文档:
无论配置文件中 DEBUG 设置的值如何,所有 Django 测试都以 DEBUG=False 运行。这是为了确保观察到的代码输出与在生产环境中看到的输出相匹配。
作为一种解决方法,您可以使用pytest-django 的settings固定装置来覆盖因此 DEBUG=True 如果您需要它。例如,
def test_my_thing(settings):
settings.DEBUG = True
# ... do your test ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3701 次 |
| 最近记录: |