pytest是一款簡(jiǎn)單的測(cè)試庫(kù),方便對(duì)于自己的代碼進(jìn)行單元測(cè)試,簡(jiǎn)單的學(xué)習(xí)使用了一下告嘲。
安裝
- pytest-django安裝
$ pip install pytest-django
運(yùn)行
- 建立測(cè)試文件
# coding=utf-8
"""
test_1.py
"""
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert x == "hi"
- 執(zhí)行
$ pytest test_1.py
- 結(jié)果
tests_1.py .F [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________
self = <tests.tests_1.TestClass object at 0x04352690>
def test_two(self):
x = "hello"
> assert x == "hi"
E AssertionError: assert 'hello' == 'hi'
E - hello
E + hi
tests_1.py:11: AssertionError
===================== 1 failed, 1 passed in 0.43 seconds ======================
就這是么容易上手酣溃,就可以執(zhí)行測(cè)試單元了
django項(xiàng)目配置
對(duì)于django項(xiàng)目税稼,很多地方可能需要引入DJANGO_SETTINGS_MODULE郑什,這個(gè)該如何測(cè)試怠李,pytest也提供了簡(jiǎn)單的方法落塑,這里選擇了最方便的配置文件.
- 建立配置文件
在django項(xiàng)目根目錄下弥奸,創(chuàng)建pytest.ini文件
[pytest]
# 根據(jù)自己項(xiàng)目實(shí)際配置文件填充
DJANGO_SETTINGS_MODULE=myproject.settings.development
# 所有以test_開頭的文件榨惠,在單獨(dú)運(yùn)行pytest之時(shí)都會(huì)被執(zhí)行
python_files=tests_*.py
# 此項(xiàng)配置python路徑,若app在當(dāng)前目錄盛霎,可忽略赠橙,若app均在指定的目錄之下,例如apps愤炸,這里指定app文件目錄
python_paths=apps
demo項(xiàng)目目錄結(jié)構(gòu)如下:
├─apps
│ ├─app_polls
│ │ ├─migrations
├─configs
├─doc
│ └─source
├─myproject
│ ├─settings
├─requirements
├─static
├─templates
└─tests
- 執(zhí)行pytest命令
$ pytest
此時(shí)期揪,pytest將會(huì)遍歷當(dāng)前項(xiàng)目下以 pytest_
開頭的單元測(cè)試文件
若要單獨(dú)測(cè)試某個(gè)文件,可直接指定該文件
$ pytest test_xxx.py