使用pytest而非django原生test理由(from官方文件)
Why would I use this instead of Django’s manage.py test command?

pytest提供了比django test還多的功能
Running the test suite with pytest offers some features that are not present in Django’s standard test mechanism:
比較少麻煩,不需要import unittest,創建子類別,可以直接寫一般的function
Less boilerplate: no need to import unittest, create a subclass with methods. Just write tests as regular functions.
使用fixtures來管理依賴
Manage test dependencies with fixtures.
多進程執行測試,加快速度
Run tests in multiple processes for increased speed.
很多友善的外掛
There are a lot of other nice plugins available for pytest.
可以容易地從unittest style轉換過來
Easy switching: Existing unittest-style tests will still work without any modifications.

1.檔案配置:
pytest.ini

[pytest]
addopts = ds=AMASCloud.settings reuse-db #使用在AMASCloud下的settings,並reuse db,這邊的reuse並非reuse 原本的db,而是創建一個test_開頭的新db後,之後測試都reuse此db
python_files = tests.py #尋找名稱為tests.py的檔案,作為測試檔案,也能依據需求客製化test_*.py就是尋找test_開頭的檔案

conftest.py(不一定需要,這邊是變動使用的資料庫的範例)

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'xxx.mysql.database.azure.com',
        'NAME': 'xxx_cloud',
    }

2.使用原本django幫忙建立的tests.py,這邊以cloud專案gateway這個app作為範例

import pytest
from gateway.models import Gateway #這邊import你需要的model!不一定是gateway
def setup_module():
    print("setup_module:在pytest執行時最先執行,且只執行一次")
def teardown_module():
    print("teardown_module:在pytest最後執行,且只執行一次")

3.寫測試的function,也能用class,但目前測試檔案很少,也只針對api,就直接用function來做測試

@pytest.mark.django_db #告訴程式你要使用db,不然會不給你用
def test_get_gateway_connection_string(): #function名稱要test開頭,不然pytest抓不到
    response = request.get("xxx") #測試邏輯,照自行需求寫
    assert response.status_code == 200 # pytest裡的function,assert可以判斷是否相等,這邊如果status_code等於200,測試就會成功,沒有就會失敗,當然也有其他判斷式(不等於之類的),之後我一併整理
    # All of Django’s TestCase Assertions are available in pytest_django.asserts

4.在terminal下指令
pytest # 執行pytest,可能會有一堆很雜的warning,但不印出print內容
pytest -s # 執行pytest,並在terminal印出print 內容
Pytest —disable-pytest-warnings # 不顯示warning

Pytest 其他學習分享

setup,teardown 相關介紹
https://iter01.com/544649.html