为Python函数编写测试是确保代码正确性和稳定性的关键步骤。通常,我们使用单元测试框架如unittest
或pytest
来编写和运行测试。以下是一个示例,展示如何为一个简单的Python函数编写测试。
假设我们有一个函数add
,它接受两个参数并返回它们的和:
def add(a, b):
return a + b
unittest
编写测试unittest
是Python内置的单元测试框架。以下是如何使用unittest
为add
函数编写测试:
test_add.py
。unittest
模块和要测试的函数。unittest.TestCase
。test_
开头。import unittest
from your_module import add # 替换为实际的模块名
class TestAddFunction(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(1, 2), 3)
def test_add_negative_numbers(self):
self.assertEqual(add(-1, -2), -3)
def test_add_positive_and_negative(self):
self.assertEqual(add(1, -2), -1)
def test_add_zero(self):
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main()
pytest
编写测试pytest
是一个更强大且易于使用的测试框架。以下是如何使用pytest
为add
函数编写测试:
test_add.py
。pytest
模块和要测试的函数。test_
开头。import pytest
from your_module import add # 替换为实际的模块名
def test_add_positive_numbers():
assert add(1, 2) == 3
def test_add_negative_numbers():
assert add(-1, -2) == -3
def test_add_positive_and_negative():
assert add(1, -2) == -1
def test_add_zero():
assert add(0, 0) == 0
unittest
运行测试在终端中导航到包含测试文件的目录,然后运行:
python -m unittest test_add.py
pytest
运行测试在终端中导航到包含测试文件的目录,然后运行:
pytest test_add.py
如果你的函数更复杂,可能需要测试更多的场景和边界条件。以下是一个更复杂的示例:
假设我们有一个函数divide
,它接受两个参数并返回它们的商,但如果除数为零,则抛出一个异常:
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
为这个函数编写测试:
unittest
import unittest
from your_module import divide # 替换为实际的模块名
class TestDivideFunction(unittest.TestCase):
def test_divide_positive_numbers(self):
self.assertEqual(divide(6, 2), 3)
def test_divide_negative_numbers(self):
self.assertEqual(divide(-6, -2), 3)
def test_divide_positive_and_negative(self):
self.assertEqual(divide(6, -2), -3)
def test_divide_by_zero(self):
with self.assertRaises(ValueError):
divide(6, 0)
if __name__ == '__main__':
unittest.main()
pytest
import pytest
from your_module import divide # 替换为实际的模块名
def test_divide_positive_numbers():
assert divide(6, 2) == 3
def test_divide_negative_numbers():
assert divide(-6, -2) == 3
def test_divide_positive_and_negative():
assert divide(6, -2) == -3
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(6, 0)
领取专属 10元无门槛券
手把手带您无忧上云