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


不依赖测试文件执行测试

利用临时文件。如:

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

声明:阿啊阿吖丁|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - pytest 不依赖测试文件执行测试


这句话一共有五十四笔