如何在lin命令上测试python代码

2024-09-30 14:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在编写和测试python方法时,我目前使用以下方法:

import foo as f
bar = f.bar()

bar.runMyMethodAndSeeIfItWorks()

如果我更改了方法中的某些内容,并且需要重新测试,则必须执行以下操作:

^{pr2}$

我想知道有没有更简单的方法来解决这个问题


Tags: 方法import内容fooasbarpr2runmymethodandseeifitworks
3条回答

编写一个真实的单元测试,并从命令行运行它。我发现这是采用单元测试的最有说服力的原因之一:不管怎样,你都需要在编写方法的同时尝试它们,你也可以用一种此后永远都可以运行的形式来完成它。在

你应该看看Doctests。学习测试是一种非常简单的方法。 基本上,您可以在交互式解释器中编写测试,然后可以将它们复制/粘贴到函数的docstring中。 示例(来自Python文档)

def factorial(n):
"""Return the factorial of n, an exact integer >= 0.

If the result is small enough to fit in an int, return an int.
Else return a long.

>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
    ...
ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
    ...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L

It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
    ...
OverflowError: n too large
"""
<do stuff>


if __name__ == "__main__":
import doctest
doctest.testmod()

tldr; 在要测试的代码行前面加上“>>>;”,并在其下一行上显示预期结果。还有更多的事情要做,但这应该足够让你开始了。在

您必须引用使用reload的pythonshell[x]进行测试。在这种情况下,reload就可以了-我不必担心它。您还可以:

import foomodule

以及以后:

^{pr2}$

[x]不要只使用普通shell(在命令行上运行python),而应该尝试像IPython或Spyder这样的工具。在

相关问题 更多 >