练习1:
被测试代码为:
class Calculator:
def add(self, a, b):
if a > 99 or a < -99 or b > 99 or b < -99:
print("请输入范围为【-99, 99】的整数或浮点数")
return "参数大小超出范围"
return a + b
def div(self, a, b):
if a > 99 or a < -99 or b > 99 or b < -99:
print("请输入范围为【-99, 99】的整数或浮点数")
return "参数大小超出范围"
return a / b
用例设计为:
from pythoncode.calculator import Calculator
import pytest
class TestCalculator:
def setup_class(self):
print(‘创建实例化Calculator对象’)
self.calc = Calculator()
def setup(self):
print('开始计算')
def teardown(self):
print('结束计算')
def teardown_class(self):
print('测试结束')
#冒烟测试用例
@pytest.mark.parametrize('a,b,expected',[[1,1,2],[-0.01,0.02,0.01],[10,0.02,10.02]],ids=['整数相加','浮点数相加','整数和浮点数相加'])
@pytest.mark.p0
def test_add0(self,a,b,expected):
result = self.calc.add(a, b)
print(result)
assert result == expected
#有效边界值和无效边界值
@pytest.mark.parametrize('a,b,expected', [[98.99, 99, 197.99], [99, 98.99, 197.99], [-98.99,-99,-197.99],[-99,-98.99,-197.99],[99.01,0,'参数大小超出范围'],[-99.01,-1,'参数大小超出范围'],[2,99.01,'参数大小超出范围'],[1,-99.01,'参数大小超出范围']],
ids=['有效边界值1','有效边界值2','有效边界值3','有效边界值4','参数大小超出范围1','参数大小超出范围2','参数大小超出范围3','参数大小超出范围4'])
@pytest.mark.p1
def test_add1(self,a,b,expected):
result=self.calc.add(a,b)
print(result)
assert result==expected
# def test_add2(self):
# try:
# result=self.calc.add('中',9.3)
# except TypeError as e:
# print('异常信息:')
# print(e)
# def test_add2(self):
# with pytest.raises(TypeError) as e:
# result = self.calc.add('中', 9.3)
# print('异常信息:')
# print(e) #为什么需要对齐with才可以打印呢?---放在with里面是执行try里面的代码,print(e)应该是在捕获了之后才能打印
#异常情况的处理
@pytest.mark.parametrize('a,b,excepted',[['中',9.3,TypeError],['9.3','文',TypeError]],ids=['中文1','中文2'])
@pytest.mark.p2
def test_add2(self,a,b,excepted):
with pytest.raises(excepted) as e:
result = self.calc.add(a, b)
assert result==excepted