跳转至

pytest 不依赖测试文件执行测试

约 44 个字 44 行代码 预计阅读时间 1 分钟

不依赖测试文件执行测试

利用临时文件。如:

import time

import pytest
import tempfile


test_code_str = ["""
def test_01_01_testfun():
    assert 1 == 1
""",
"""
def test_02_01_testfun():
    assert 2 == 1
"""]

if __name__ == '__main__':
    with tempfile.TemporaryDirectory() as temp_dir:
        file = temp_dir + f'/test_{int(time.time())}.py'
        with open(file, 'w+') as f:
            f.writelines(test_code_str)
        pytest.main([temp_dir, '-v'])

获取输入、输出和返回信息

使用 subprocess

import subprocess
import time

import pytest
import tempfile

test_code_str = ["""
def test_01_01_testfun():
    assert 1 == 1
""",
"""
def test_02_01_testfun():
    assert 2 == 1
"""]

if __name__ == '__main__':
    with tempfile.TemporaryDirectory() as temp_dir:
        file = temp_dir + f'/test_{int(time.time())}.py'
        with open(file, 'w+') as f:
            f.writelines(test_code_str)
        p = subprocess.Popen(f'pytest "{temp_dir}" -v', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, error = p.communicate()
        returncode = p.returncode