结对伙伴:苗威
经过学习编写的单元测试代码:
import unittest from f4 import * class TestMathFunc(unittest.TestCase): def test_f4(self): pass def test_f4_answer(self): print("_f4_answer函数单元测试开始:") _eq = input("输入一个四则运算:") _eq_ans = input("输入一个正确的答案:") self.assertEqual(_eq_ans ,f4()._f4_answer(eq = _eq)) print("_f4_answer函数单元测试结束。") print("OK") def test_f4_input(self): print("_f4_input函数单元测试开始:") self.assertEqual(0,f4()._f4_input()) print("_f4_input函数单元测试结束。") print("OK") def test_f4_integer_parser(self): print("_f4_integer_parser函数单元测试开始:") x = input("输入命令行参数:") self.assertEqual(0,f4()._f4_integer_parser(x)) print("_f4_integer_parser函数单元测试结束。") print("OK") if __name__ == "__main__": unittest.main()
运行结果如下:
先写的程序后完成的单元测试,所以都是一次pass
代码:
def _f4_answer(self,eq): from fractions import Fraction as f _answer = f(eval(eq)).limit_denominator(1000) _answer = str(_answer) return(_answer)
def _f4_input(self): try: _y = 0 _n = 0 for i in range(20): _eq = f4()._f4() print(_eq, "=") _ans_right = f4()._f4_answer(eq = _eq) _ans = input("?") if _ans == _ans_right: print("答对了,你真是个天才!") _y = _y + 1 else: print("你再想想吧,答案似乎是", _ans_right, "喔!") _n = _n + 1 print("你一共答对", _y, "道题,一共20道题。") except: print("输入有误") return (0)
def _f4_integer_parser(self,x): _p = "请输入正整数。" try: x = int(x) if x >= 0: for i in range(x): _eq = f4()._f4() _right = f4()._f4_answer(eq = _eq) _eq = _eq + "=" print(_eq.ljust(40), _right) else: print(_p) except: print(_p) return(0)
体会:
单元测试可以帮助编码的人减少bug,避免浪费时间,思路更加清晰。