간단히 정리하면 아래와 같이 Django 웹 애플리케이션이 서버에서 실행 중인지 아니면 테스트 실행 중인지 알아낼 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core import mail | |
@property | |
is_django_in_test_mode(): | |
return hasattr(mail, 'outbox') |
Detect django testing mode에서 Mark Lavin이 한 말이 정확하다.
This attributed is added by the Django test runner in setup_test_environment and removed in teardown_test_environment. You can check the source here: https://code.djangoproject.com/browser/django/trunk/django/test/utils.py
Django 공식 문서를 보면
Sets up the test environment by calling
setup_test_environment()
and settingDEBUG
toFalse
.
라고 한다. 그러니까 settings.DEBUG
의 값을 쓰면 안 된다. 그 대신 어떤 값을 쓰면 될지는 setup_test_environment
의 소스 코드에서 힌트를 얻을 수 있다.
def setup_test_environment():
"""Perform any global pre-test setup. This involves:
- Installing the instrumented test renderer
- Set the email backend to the locmem email backend.
- Setting the active locale to match the LANGUAGE_CODE setting.
"""
Template._original_render = Template._render
Template._render = instrumented_test_render
# Storing previous values in the settings module itself is problematic.
# Store them in arbitrary (but related) modules instead. See #20636.
mail._original_email_backend = settings.EMAIL_BACKEND
settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
request._original_allowed_hosts = settings.ALLOWED_HOSTS
settings.ALLOWED_HOSTS = ['*']
mail.outbox = []
deactivate()
처음에는 settings
에 TEST_MODE
같은 값을 설정해주리라 기대했는데 그런 것 없다. 대신 Django Testing Tools에 나오는 바와 같이 테스트 모드일 때는 mail.outbox
가 만들어지니 이걸 이용해 테스트 중인지 여부를 판별하면 된다.
Author Details
Kubernetes, DevSecOps, AWS, 클라우드 보안, 클라우드 비용관리, SaaS 의 활용과 내재화 등 소프트웨어 개발 전반에 도움이 필요하다면 도움을 요청하세요. 지인이라면 가볍게 도와드리겠습니다. 전문적인 도움이 필요하다면 저의 현업에 방해가 되지 않는 선에서 협의가능합니다.