1.安装pytest或ipytest(用于jupyter notebook)
pip install pytest
2.pytest是Python中非常流行的测试框架之一,它使得编写和运行测试变得非常简单。
3.简单DEMO(ipytest)
导入ipytest库,ipytest.autoconfig() 是 ipytest 模块的一个函数,用于自动配置 ipytest 以在 Jupyter Notebook 中运行。
import ipytest
ipytest.autoconfig()
首先编写了一个过滤参数列表中能被5整除的函数
def get_divisible_by_five(numbers):
"""Returns a list of numbers which are divisible by five in the list got as an argument"""
result = []
for num in numbers:
if not num % 5:
result.append(num)
return result
编写一个测试用例测试get_divisible_by_five函数能否正常工作
%%ipytest
#%%ipytest是一个Jupyter Notebook的魔法命令,它表明这个cell中的代码应该由ipytest模块来运行。
def test_get_divisible_by_five():
assert get_divisible_by_five([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [5, 10]
如果测试成功
> 如果测试失败