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



