栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python CLI程序单元测试

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python CLI程序单元测试

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

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

# content of test_pyconv.pyimport 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.fixturedef run(testdir):    def do_run(*args):        args = ["pyconv"] + list(args)        return testdir._run(*args)    return do_rundef test_pyconv_latin1_to_utf8(tmpdir, run):    input = tmpdir.join("example.txt")    content = unipre("xc3xa4xc3xb6", "latin1")    with input.open("wb") as f:        f.write(content.enpre("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.enpre("utf8") == newcontent

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

$ py.test test_pyconv.py=========================== test session starts ============================platform linux2 -- Python 2.7.3 -- pytest-2.4.5dev1collected 1 itemstest_pyconv.py .========================= 1 passed in 0.40 seconds =========================

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623757.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号