您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python CLI程序单元测试

Python CLI程序单元测试

我认为在整个程序级别上进行功能测试是完全可以的。仍然可以在每个测试中测试一个方面/选项。这样,您可以确定该程序确实可以整体运行。编写单元测试通常意味着您可以更快地执行测试,并且故障通常更易于解释/理解。但是,单元测试通常与程序结构更紧密地联系在一起,当您在内部进行更改时,需要更多的重构工作。

无论如何,使用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的fixture机制来重用pytest自身测试的一些内部机制,请参阅http://pytest.org/latest/fixture.html。如果暂时忘记了细节,则可以通过提供“运行”和“ tmpdir”来帮助您准备和运行测试这一事实来工作。如果您想玩,可以尝试插入一个失败的断言语句或简单地“断言0”,然后查看回溯或发出“ py.test –pdb”以输入python提示符。

python 2022/1/1 18:41:32 有282人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶