gpt4 book ai didi

Python CLI 程序单元测试

转载 作者:太空狗 更新时间:2023-10-29 16:56:38 25 4
gpt4 key购买 nike

我在做一个python Command-Line-Interface程序,做测试的时候觉得很无聊,例如,这里是程序的帮助信息:

usage: pyconv [-h] [-f ENCODING] [-t ENCODING] [-o file_path] file_path

Convert text file from one encoding to another.

positional arguments:
file_path

optional arguments:
-h, --help show this help message and exit
-f ENCODING, --from ENCODING
Encoding of source file
-t ENCODING, --to ENCODING
Encoding you want
-o file_path, --output file_path
Output file path

当我对程序进行更改并想测试一些东西时,我必须打开一个终端,键入命令(带有选项和参数),键入回车,然后查看是否发生任何错误在运行的时候。如果真的出现错误,我必须回到编辑器中检查代码从头到尾,猜测错误位置,进行小改动,编写 print 行,返回终端,再次运行命令...

递归地。

所以我的问题是,使用 CLI 程序进行测试的最佳方法是什么?作为普通 python 脚本的单元测试?

最佳答案

我认为在整个程序级别进行功能测试非常好。仍然可以在每个测试中测试一个方面/选项。这样您就可以确定该程序作为一个整体确实有效。编写单元测试通常意味着您可以更快地执行测试,并且失败通常更容易解释/理解。但单元测试通常更依赖于程序结构,当您在内部更改内容时需要更多的重构工作。

无论如何,使用 py.test ,这里有一个小例子,用于测试 pyconv::latin1 到 utf8 的转换:

# content of test_pyconv.py

import pytest

# we reuse a bit of pytest's own testing machinery, this should eventually come
# from a separatedly installable pytest-cli plugin.
pytest_plugins = ["pytester"]

@pytest.fixture
def run(testdir):
def do_run(*args):
args = ["pyconv"] + list(args)
return testdir._run(*args)
return do_run

def test_pyconv_latin1_to_utf8(tmpdir, run):
input = tmpdir.join("example.txt")
content = unicode("\xc3\xa4\xc3\xb6", "latin1")
with input.open("wb") as f:
f.write(content.encode("latin1"))
output = tmpdir.join("example.txt.utf8")
result = run("-flatin1", "-tutf8", input, "-o", output)
assert result.ret == 0
with output.open("rb") as f:
newcontent = f.read()
assert content.encode("utf8") == newcontent

安装 pytest(“pip install pytest”)后,您可以像这样运行它::

$ py.test test_pyconv.py
=========================== test session starts ============================
platform linux2 -- Python 2.7.3 -- pytest-2.4.5dev1
collected 1 items

test_pyconv.py .

========================= 1 passed in 0.40 seconds =========================

该示例通过利用 pytest 的夹具机制重用了 pytest 自己测试的一些内部机制,请参阅 http://pytest.org/latest/fixture.html .如果您暂时忘记了细节,您可以从提供“run”和“tmpdir”来帮助您准备和运行测试这一事实开始工作。如果你想玩,你可以尝试插入失败的断言语句或简单地“断言 0”,然后查看回溯或发出“py.test --pdb”以输入 python 提示符。

关于Python CLI 程序单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13493288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com