在Linux項目中,使用TXT(Testing Tool XML)格式來實現自動化測試是一種可行的方法
pytest
,它是一個Python庫,可以輕松地處理TXT文件。要安裝pytest
,請運行以下命令:pip install pytest
[test_name]
command: your_command_here
exitcode: expected_exit_code
stdout: expected_output
stderr: expected_error
例如,假設你有一個名為my_program
的程序,你可以創建一個名為test_my_program.txt
的測試文件,其中包含以下內容:
[test_help]
command: my_program --help
exitcode: 0
stdout: Usage: my_program [options]
stderr:
[test_version]
command: my_program --version
exitcode: 0
stdout: my_program version 1.0.0
stderr:
pytest
庫來運行TXT測試文件。創建一個名為run_tests.py
的文件,并添加以下內容:import pytest
def test_txt(txt_file):
with open(txt_file, 'r') as f:
content = f.read()
tests = content.split('[')[1:]
for test in tests:
test_name, test_content = test.split(']', 1)
test_name = test_name.strip()
test_lines = [line.strip() for line in test_content.strip().split('\n') if line.strip()]
command = None
exitcode = None
stdout = None
stderr = None
for line in test_lines:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip()
if key == 'command':
command = value
elif key == 'exitcode':
exitcode = int(value)
elif key == 'stdout':
stdout = value
elif key == 'stderr':
stderr = value
assert command is not None, f"Missing command in test '{test_name}'"
assert exitcode is not None, f"Missing exitcode in test '{test_name}'"
result = pytest.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
assert result.returncode == exitcode, f"Expected exit code {exitcode}, but got {result.returncode}"
if stdout is not None:
assert result.stdout.decode('utf-8').strip() == stdout, f"Expected stdout '{stdout}', but got '{result.stdout.decode('utf-8').strip()}'"
if stderr is not None:
assert result.stderr.decode('utf-8').strip() == stderr, f"Expected stderr '{stderr}', but got '{result.stderr.decode('utf-8').strip()}'"
if __name__ == '__main__':
import sys
txt_file = sys.argv[1]
test_txt(txt_file)
python run_tests.py test_my_program.txt
這將運行test_my_program.txt
中定義的所有測試用例,并報告成功和失敗的測試。你可以根據需要添加更多的TXT測試文件,只需確保在運行測試時指定正確的文件名即可。