14.5 测试模块
对于 C 扩展或 Python 模块,你可以使用 unittest
模块导入并测试它们。测试按模块或包组装而成。
例如,Python Unicode 字符串类型在 Lib/test/test_Unicode.py
中有测试。asyncio
包在 Lib /test/test_asyncio
中有测试包。
以下是 UnicodeTest
类的摘录:
class UnicodeTest(string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUnicodeTest,
unittest.TestCase):
...
def test_casefold(self):
self.assertEqual('hello'.casefold(), 'hello')
self.assertEqual('hELlo'.casefold(), 'hello')
self.assertEqual('ß'.casefold(), 'ss')
self.assertEqual('fi'.casefold(), 'fi')
你可以通过在 UnicodeTest
类中添加一个新的测试方法来扩展前面章节中为 Python Unicode 字符串实现的约等于运算符:
def test_almost_equals(self):
self.assertTrue('hello' ~= 'hello')
self.assertTrue('hELlo' ~= 'hello')
self.assertFalse('hELlo!' ~= 'hello')
你可以在 Windows 上运行此特定的测试模块:
> rt.bat -q -d -x64 test_unicode
或者你可以在 macOS 或 Linux 上运行它:
$ ./python -m test test_unicode -v
Last updated