利用临时文件,如:
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