๋ค์๊ณผ ๊ฐ์ด ํ๋ ๊ฒ์ด ์ข์ต๋๋ค.
if settings.TESTING:
print("py.test is being ran")
"pytest" in sys.modules
?
ํ ์คํธ๋ฅผ ์ํ ๋ณ๋์ ์ค์ ํ์ผ๋ก ์ง์ ์ค์ ์ ์ถ๊ฐํ ์ ์์ต๋๋ค.
ํ์ํ ๊ฒฝ์ฐ @blueyed ๋ฐ @adamchainz ๊ฐ ์ ์ํ ์ ๊ทผ ๋ฐฉ์์ผ๋ก ์ถฉ๋ถํด์ผ ํ๋ค๊ณ ์๊ฐํฉ๋๋ค. ์ผ๋ฐ์ ์ผ๋ก ํ ์คํธ์์ ์ฝ๋๊ฐ ํธ์ถ๋์๋์ง ์ฌ๋ถ๋ฅผ ๊ฒ์ฌํ์ฌ ์ฝ๋ ์๋ ๋ฐฉ์์ ๋ณ๊ฒฝํ๋ ๊ฒ์ ๊ถ์ฅ๋์ง ์์ต๋๋ค. ์ด ์์ ์ ์ํํ๋ ค๋ฉด ์ผ๋ฐ์ ์ธ pytest ๋ฐฉ์์ผ๋ก ์ํํ ์ ์์ต๋๋ค(pytest-django์๋ง ๊ตญํ๋์ง ์์). ์ ์ํด ์ฃผ์ ์ ๊ฐ์ฌํฉ๋๋ค. ์ด ํธ์ ๋ํ ์ถ๊ฐ ์ ๋ณด๊ฐ ์์ผ๋ฉด ์ธ์ ๋ ์ง ์ด ํธ๋ฅผ ๋ค์ ์ฌ์ญ์์ค!
pytest ๋ฌธ์์ ๊ด๋ จ ์์ pytest run ๋ด์์ ์คํ ์ค์ธ ๊ฒฝ์ฐ ๊ฐ์ง :
# content of conftest.py
def pytest_configure(config):
import sys
sys._called_from_test = True
def pytest_unconfigure(config):
import sys
del sys._called_from_test
๋ฌธ์ ๋ pytest_configure
๊ฐ settings.py
๋ค์์ ์คํ๋๋ค๋ ๊ฒ์
๋๋ค. settings.py
์ ์ ์ด ์ฝ๋๋ฅผ ์คํํ๋ ๋ฐฉ๋ฒ์ด ์์ต๋๊น?
@์ฝ์ก
'pytest' in sys.modules
๋ฅผ) ์ฌ์ฉํ๋ ๋ฐ ์ด๋ค ๋ฌธ์ ๊ฐ ์์ต๋๊น?
ํ , ์, ์๋ํ์ต๋๋ค. ๋น๋ก ๋์๊ฒ๋ ์ฝ๊ฐ ํดํคํด ๋ณด์ด์ง๋ง.
settings.py์์ ์ด๊ฒ์ ํ์ธํ๋ ๋ ๋ค๋ฅธ ๋น ๋ฅด๊ณ ๋๋ฌ์ด ๋ฐฉ๋ฒ์
TESTING = os.path.basename(sys.argv[0]) in ('pytest', 'py.test')
@์ฝ์ก
'pytest' in sys.modules
๋ฅผ) ์ฌ์ฉํ๋ ๋ฐ ์ด๋ค ๋ฌธ์ ๊ฐ ์์ต๋๊น?
pytest๋ฅผ ๊ฐ์ ธ์๋ค๊ณ ํด์ pytest
๊ฐ ์คํ ์ค์ด๊ณ ํ
์คํธ์์ ์ฝ๋๊ฐ ํธ์ถ๋๋ ๊ฒ์ ์๋๋๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก ๋ด ์์
pytest
์ค ํ๋๋ ๋ค๋ฅธ ๊ฒ์
๋๋ค. ๋ํ pytest๋ CLI ๋์๋ง๋ง ํ์ํ๋๋ผ๋ pytest
๊ฐ์ ธ์ค๊ณ ์์ต๋๋ค. pytest --help
๋ค์์ ๋งค์ฐ ์ ํจํ ์ฌ์ฉ ์ฌ๋ก์
๋๋ค.
๋ค์ํ ์๊ฒฉ ์ฆ๋ช
๋ฐ ๊ธฐํ ๋ก์ปฌ ๊ฐ๋ฐ ํ๊ฒฝ ๊ตฌ์ฑ์ ๋ฃ๋ ๋ก์ปฌ ํ์ผ ๋ฐ ๋ณ์๋ก ๊ตฌ์ฑ ๊ฐ๋ฅํ django ์ค์ ์ด ์์ต๋๋ค. ๊ทธ๋ฌ๋ ๋ด ๋จ์ ํ
์คํธ๊ฐ ์ด ์๊ฒฉ ์ฆ๋ช
์ด๋ ํน์ ์ค์ ์ ์ค์๋ก ์ค์ ์์คํ
์์ ์ฌ์ฉํ์ง ์๊ฑฐ๋(๋ถ์ ์ ํ๊ฒ ์กฐ๋กฑ๋ ๊ฒฝ์ฐ) ๋ก์ปฌ ๊ฐ๋ฐ ํ๊ฒฝ ๊ตฌ์ฑ์์ ํต๊ณผ/์คํจํ์ง ์๊ธฐ๋ฅผ ๋ฐ๋๋๋ค. ๋ฐ๋ผ์ pytest๋ก ์คํํ ๋ ์ด๋ฌํ ๋ก์ปฌ ์ค์ ์ ์ ์ธํ๊ณ ์ถ์ต๋๋ค.
๋๋ ๋ค์๊ณผ ๊ฐ์ ๊ฒ์ ๊ฐ์ง๊ณ ์์ต๋๋ค.
import os
import os.path
import sys
from split_settings.tools import include, optional
def is_pytest_running():
return (os.getenv('PYTEST_RUNNING') == 'true' or
os.path.basename(sys.argv[0]) in ('pytest', 'py.test'))
ENVVAR_SETTINGS_PREFIX = 'MV_SERVER_'
local_settings_path = os.getenv(f'{ENVVAR_SETTINGS_PREFIX}SETTINGS', '../../../local/settings.py')
includes = [
'base.py',
'logging.py',
'custom.py',
]
if not is_pytest_running():
includes.append(optional(local_settings_path))
includes.append('envvars.py')
include(*includes)
os.getenv('PYTEST_RUNNING') == 'true'
๊ฒ์ด ๋ค์ ๊น๋ํ ๋ฐฉ๋ฒ์ด์ง๋ง ๋ฌธ์ ๋ ์ด ๋ณ์๋ฅผ ์ค์ ํ๋ ๊ฒ์
๋๋ค. pytest-django๋ conftest.py๊ฐ ์คํ๋๊ธฐ ์ ์ ์ค์ ์ ๊ฐ์ ธ์ค๊ธฐ ๋๋ฌธ์ conftest.py์์ ์ค์ ํ๋ฉด ์๋ํ์ง ์์ต๋๋ค. pytest๋ฅผ ์คํํ ๋ ๋ช
๋ น์ค์์ ์ค์ ํ๋ ๊ฒ์ ๋ถํธํ ๋ฟ๋ง ์๋๋ผ ๋ชฉ์ ๋ ๋ฌดํจํ๋ฉ๋๋ค. ๋๊ตฐ๊ฐ ์ค์ ํ๋ ๊ฒ์ ์์ด๋ฒ๋ฆฌ๋ฉด ๋ก์ปฌ dev env ๊ตฌ์ฑ์์ ์ค์ ์๊ฒฉ ์ฆ๋ช
์ด ์ฌ์ฉ๋ฉ๋๋ค.
os.path.basename(sys.argv[0]) in ('pytest', 'py.test')
sys.argv[0]
๊ฐ /home/project/venv/lib/python3.8/site-packages/pytest/__main__.py
๋ก ๋์ค๊ธฐ ๋๋ฌธ์ os.path.basename(os.path.dirname(sys.argv[0])) in ('pytest', 'py.test')
๋ก ๋ฐ๊ฟ์ผ ํ์ต๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
"pytest" in sys.modules
?