CS50P中test_twttr练习的pytest无测试运行问题排查
CS50P test_twttr练习pytest无测试运行问题
我正在学习CS50P旁听版本,在test_twttr练习里对pytest的使用感到困惑。主程序功能是移除字符串中的元音,我写了测试代码,但运行pytest时始终返回“no test ran”,课程检查工具首项检查也报错——正常功能正常的话应该无错误提示。请问我在pytest使用上漏了什么?
测试代码:
from twttr import shorten def main(): upperV() lowerV() number() symbol() def upperV(): assert shorten("sAo") == "so" assert shorten("sEo") == "so" assert shorten("sIo") == "so" assert shorten("sOo") == "so" assert shorten("sUo") == "so" def lowerV(): assert shorten("sao") == "so" assert shorten("seo") == "so" assert shorten("sio") == "so" assert shorten("soo") == "so" assert shorten("suo") == "so" def number(): assert shorten("s1o") == "s1o" assert shorten("s0o") == "s0o" assert shorten("s2o") == "s2o" assert shorten("s4o") == "s4o" assert shorten("s5o") == "s5o" def space(): assert shorten("s o") == "s o" assert shorten("s o") == "s o" assert shorten("s o") == "s o" assert shorten("s o") == "s o" assert shorten("s o") == "s o" def symbol(): assert shorten("s@o") == "s@o" assert shorten("s#o") == "s#o" if __name__ == "__main__": main()
问题原因及解决方法
pytest识别测试用例有固定规则,你的代码不符合这些规则,导致它找不到要运行的测试:
- 测试函数命名不符合规范:pytest默认只会识别以
test_开头的函数作为测试用例,你的函数名是upperV、lowerV这类,pytest不会把它们当成测试函数。 - 测试文件命名需注意:确保你的测试文件命名是
test_*.py格式(比如test_twttr.py),pytest只会自动发现这类命名的文件里的测试。
修改后的测试代码示例:
from twttr import shorten def test_upper_vowels(): assert shorten("sAo") == "so" assert shorten("sEo") == "so" assert shorten("sIo") == "so" assert shorten("sOo") == "so" assert shorten("sUo") == "so" def test_lower_vowels(): assert shorten("sao") == "so" assert shorten("seo") == "so" assert shorten("sio") == "so" assert shorten("soo") == "so" assert shorten("suo") == "so" def test_numbers(): assert shorten("s1o") == "s1o" assert shorten("s0o") == "s0o" assert shorten("s2o") == "s2o" assert shorten("s4o") == "s4o" assert shorten("s5o") == "s5o" def test_spaces(): assert shorten("s o") == "s o" assert shorten("s o") == "s o" assert shorten("s o") == "s o" assert shorten("s o") == "s o" assert shorten("s o") == "s o" def test_symbols(): assert shorten("s@o") == "s@o" assert shorten("s#o") == "s#o"
另外,不需要写main()函数和if __name__ == "__main__"的执行逻辑,pytest会自动遍历并运行所有符合规则的测试函数。
内容的提问来源于stack exchange,提问作者AGhoul
相关产品推荐
相关产品推荐

