calculater.py
def mySum(x, y):
ret = x + y
return ret
def mySub(x, y):
a = 0
ret = x - y
return ret
创建测试文件test.py
#测试模块
import unittest
from calculater import mySum, mySub
#测试类
class Test(unittest.TestCase):
# 每个测试开始之前调用
def setUp(self):
print("开始测试……")
# 每个测试结束之后调用
def tearDown(self):
print("结束测试……")
# 测试函数名:tset__待测试函数名
# 注意:其实也可以不是待测试函数名
# 本质:只要是以test__开头的函数就都会被执行
def test_mySum(self):
self.assertEqual(mySum(1,1), 2)
def test__mySub(self):
self.assertEqual(mySub(1, 1), 0)
if __name__ == "__main__":
unittest.main()
main.py
from calculater import mySum, mySub
if __name__ == "__main__":
ret1 = mySum(1,2)
if ret1 == 3:
print("ret1 = %d"%ret1)
else:
print("我不想看ret1")
print("-------------")
ret2 = mySum(1,2)
# 认为逻辑是正确的
if ret2 == 4:
print("ret2 = %d" % ret2)
else:
print("我不想看ret2")
myDict.py
class MyDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, item):
try:
return self[item]
except KeyError as e:
raise AttributeError("dict not has the key")
# def run(self):
# print("------------")
创建测试文件test.py
import unittest
from myDict import MyDict
# 定义测试类,一个测试类只能测试一个类
# 类名:Test待测试的类名
class TestMyDict(unittest.TestCase):
# 每个测试开始之前调用
def setUp(self):
print("开始测试……")
# 每个测试结束之后调用
def tearDown(self):
print("结束测试……")
# 实例化阶段
def test__init(self):
d = MyDict(a=1)
#断言
self.assertEqual(d.a, 1)
self.assertTrue(isinstance(d, dict))
#测试设置值
def test_key(self):
d = MyDict()
d["key"] = 1
self.assertTrue("key" in d)
self.assertEqual(d["key"],1)
def test_attr(self):
d = MyDict()
d.key = 1
self.assertTrue("key" in d)
self.assertEqual(d.key, 1)
#判断
def test_keyerror(self):
d = MyDict()
#通过d["key"]访问不存在的属性抛出KeyError异常
with self.assertRaises(KeyError):
value = d["key"]
def test_attrerror(self):
d = MyDict()
# 通过d.key访问不存在的属性抛出AttributeError异常
with self.assertRaises(AttributeError):
value = d.key
# def test__run(self):
# d = MyDict()
# d.run()
# self.assertEqual(d.run(), 1)
if __name__ == "__main__":
unittest.main()
main.py
from myDict import MyDict
if __name__ == "__main__":
d = MyDict(a=0)
print(d, type(d))
d.a = 1
if d.a == 1:
print("----------------------")
else:
print("*************")
# d.c = 3
# if d.c == 4:
# print("**********************")
# 该模块可以直接提取注释中的代码并执行测试
import doctest
def mySum(x, y):
# doctest严格按照python交互模式命令的输入和输出来判断结果
'''
>>> print(mySum(1,1))
2
'''
return x + y + 1
print(mySum(1,2))
doctest.testmod()