def test_monkeypatch(monkeypatch): c = Calculator() def fake_add(a, b): return 42 monkeypatch.setattr(c, "add", fake_add) assert c.add(2, 3) == 42
class TestCal: def setup(self): self.cal = Calculator() @pytest.mark.run(order=1) @pytest.mark.dependency(name='add') @pytest.mark.parametrize('a,b,c', yaml.safe_load(open('./data.yml', 'r'))['add']) def test_add(self, a, b, c): print(f"测试 {a} + {b} = {c}") assert c == self.cal.add(a, b) @pytest.mark.run(order=2) @pytest.mark.dependency(depends=["add"]) @pytest.mark.parametrize('a,b,c', yaml.safe_load(open('./data.yml', 'r'))['sub']) def test_sub(self, a, b, c): print(f"测试 {a} - {b} = {c}") assert c == self.cal.sub(a, b) @pytest.mark.run(order=4) @pytest.mark.dependency(depends=["mul"]) @pytest.mark.parametrize('a,b,c', yaml.safe_load(open('./data.yml', 'r'))['div']) def test_div(self, a, b, c): print(f"测试 {a} / {b} = {c}") assert c == self.cal.div(a, b) @pytest.mark.run(order=3) @pytest.mark.dependency(name='mul') @pytest.mark.parametrize('a,b,c', yaml.safe_load(open('./data.yml', 'r'))['mul']) def test_mul(self, a, b, c): print(f"测试 {a} * {b} = {c}") assert c == self.cal.mul(a, b)
def test_add_weird(): c = Calculator() # Raise error when any one is string with pytest.raises(CalculatorError) as context: result = c.add('10', 20) assert str(context.value) == '10 is not a number'
class ModuleTest(unittest.TestCase): def setUp(self): self.calc = Calculator(8, 4) def tearDown(self): pass def test_add(self): result = self.calc.add() self.assertEqual(result, 12) def test_sub(self): result = self.calc.sub() self.assertEqual(result, 4) def test_mul(self): result = self.calc.mul() self.assertEqual(result, 32) def test_div(self): result = self.calc.div() self.assertEqual(result, 2)
def test_add(self, a, b, c): cal = Calculator() assert c == cal.add(a, b)
def test_add_parameterize(a, b, expected): c = Calculator() assert c.add(a, b) == expected
def test_add_range(): c = Calculator() for i in range(10): assert c.add(i, 2) == i+2
def test_add(): c = Calculator() result = c.add(3, 4) assert result == 7
def test_calculator_add_method_returns_correct_result(self): calc = Calculator() result = calc.add(2,2) self.assertEqual(4, result)