今天Nelly問我Pytest能不能支持從TestClass類外傳入參數?從類外批量傳入各個test方法需要的參數。因為數據文件可能有很多情況,不方便依次匹配。
然而又必須用類對用例進行歸類及復用,數據要通過類外進行遍歷。不能直接使用pytest.mark.parametrize。
這里采取的一個做法是:
- 添加命令行選項 --data,接受一個yaml文件
- data這個fixture方法里,獲取--data傳進來的文件路徑,打開並加載所有數據,從request中獲取調用data 的用例名,從所有數據中取出該條用例的數據返回
具體參考以下代碼:
data.yaml文件內容,注意數據字段要與測試方法名一致,方便自動對應數據。
test_a:
a: 1
b: 2
test_b:
a: 3
b: 4
conftest.py文件內容
import pytest
import yaml
def pytest_addoption(parser): # 添加運行參數
parser.addoption("--data", action="store", help="data file")
@pytest.fixture
def data(request):
file_path = request.config.getoption("--data") # 獲取--data參數傳的文件路徑
with open(file_path) as f: # 加載所有數據
all_data = yaml.safe_load(f)
test_case_name = request.function.__name__ # 獲取調用的data這個fixture方法的測試方法名稱
return all_data.get(test_case_name) # 只返回指定用例的數據
測試模塊test_demo3.py內容
import pytest
class TestDemo(object):
def test_a(self, data): # 所有用例要帶上data這個fixture參數
print(data)
def test_b(self, data):
print(data)
if __name__ == '__main__':
pytest.main(['test_demo3.py', '-sq', '--data=data.yaml'])