20220619 Python Pytest 实战训练营

参考链接

PPT

代码地址

学习路线

pytest 学习路线.xmind.zip (73.3 KB)

测试用例

计算器测试用例.xlsx (14.0 KB)

pytest pycharm 环境配置

pip install pytest

测试用例

测试用例编写 1

  • 题目:
    • 根据需求编写计算机器(加法和除法)相应的测试用例
    • 在调用每个测试方法之前打印【开始计算】
    • 在调用测试方法之后打印【结束计算】
    • 调用完所有的测试用例最终输出【结束测试】
    • 为用例添加标签
  • 注意:
    • a、使用等价类,边界值,错误猜测等方法进行用例设计
    • b、用例中要添加断言,验证结果
    • c、灵活使用测试装置

被测代码


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

测试代码


class TestAdd:

    def test_add1(self):
        self.cal = Calculator()
        # result 实际
        result = self.cal.add(1,1)
        expect = 2
        assert result == expect


import pytest

from calcalator.demoExample.calcator import Calculator


class TestCase:

    def set_up(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def teardown_class(self):
        print("结束测试")

    @pytest.mark.P0
    def test_add1(self):
        self.calc = Calculator()
        result = self.calc.add(1, 1)
        expect = 2
        assert result == expect

    @pytest.mark.P0
    def test_add2(self):
        self.calc = Calculator()
        result = self.calc.add(-0.01, 0.02)
        expect = 0.01
        assert result == expect

    @pytest.mark.P0
    def test_add3(self):
        self.calc = Calculator()
        result = self.calc.add(10, 0.02)
        expect = 10.02
        assert result == expect

    @pytest.mark.P1
    def test_add4(self):
        self.calc = Calculator()
        result = self.calc.add(98.99, 99)
        expect = 197.99
        assert result == expect

    @pytest.mark.P1
    def test_add5(self):
        self.calc = Calculator()
        result = self.calc.add(99, 98.99)
        expect = 197.99
        assert result == expect

    @pytest.mark.P1
    def test_add6(self):
        self.calc = Calculator()
        result = self.calc.add(-99, -98.99)
        expect = -197.99
        assert result == expect

    @pytest.mark.P1
    def test_add7(self):
        self.calc = Calculator()
        result = self.calc.add(-98.99, -99)
        expect = -197.99
        assert result == expect

    @pytest.mark.P1
    def test_add8(self):
        self.calc = Calculator()
        result = self.calc.add(-99.01, 0)
        expect = "参数大小超出范围"
        assert result == expect

    @pytest.mark.P1
    def test_add9(self):
        self.calc = Calculator()
        result = self.calc.add(-99.01, -1)
        expect = "参数大小超出范围"
        assert result == expect

    @pytest.mark.P1
    def test_add10(self):
        self.calc = Calculator()
        result = self.calc.add(2, 99.01)
        expect = "参数大小超出范围"
        assert result == expect

    @pytest.mark.P1
    def test_add11(self):
        self.calc = Calculator()
        result = self.calc.add(1, -99.01)
        expect = "参数大小超出范围"
        assert result == expect
    
    @pytest.mark.P1
    def test_add12(self):
        self.calc = Calculator()
        result = self.calc.add("文", 9.3)
        expect = "参数大小超出范围"
        assert result == expect
    

    @pytest.mark.P1
    def test_add13(self):
        self.calc = Calculator()
        result = self.calc.add(4, '字')
        expect = "参数大小超出范围"
        assert result == expect
 from script.calculator import Calculator


class TestAdd:
    def setup(self):
        self.cal = Calculator()
        print("开始计算")
    def teardown(self):
        print("结束计算")
    def teardown_class(self):
        print("测试结束")

    def test_add1(self):
        result=self.cal.add(1,1)
        expect = 2
        assert result == expect

    def test_add2(self):
        result=self.cal.add(-0.01,0.02)
        expect = 0.01
        assert result == expect

    def test_add3(self):
        result=self.cal.add(10,0.02)
        expect = 10.02
        assert result == expect

    def test_add4(self):
        result=self.cal.add(98.99,99)
        expect = 197.99
        assert result == expect

    def test_add5(self):
        result=self.cal.add(99,98.99)
        expect = 197.99
        assert result == expect

    def test_add6(self):
        result=self.cal.add(-98.99,-99)
        expect = -197.99
        assert result == expect

    def test_add7(self):
        result=self.cal.add(-99,-98.99)
        expect = -197.99
        assert result == expect

    def test_add8(self):
        result=self.cal.add(99.01,0)
        expect = "参数大小超出范围"
        assert result == expect

    def test_add9(self):
        result=self.cal.add(-99.01,-1)
        expect = "参数大小超出范围"
        assert result == expect

    def test_add10(self):
        result=self.cal.add(2,99.01)
        expect = "参数大小超出范围"
        assert result == expect

    def test_add11(self):
        result=self.cal.add(1,-99.01)
        expect = "参数大小超出范围"
        assert result == expect

    def test_add12(self):
        result=self.cal.add("文",9.3)
        expect = "参数大小超出范围"
        assert result == expect

    def test_add13(self):
        result=self.cal.add(4,"字")
        expect = "参数大小超出范围"
        assert result == expect

import pytest
from pytestStu.practice.caculator import Calculator


class TestAdd:
    def setup_class(self):
        self.cal = Calculator()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def teardown_class(self):
        print("结束测试")

    @pytest.mark.parametrize('a,b,expect', [(1, 1, 2), (-0.01, 0.02, 0.01), (10, 0.02, 10.02),
                                            (98.99, 99, 197.99), (99, 98.99, 197.99), (-98.99, -99, -197.99),
                                            (99.01, 0, "参数大小超出范围"), (-99.01, 0, "参数大小超出范围"), (2, 99.01, "参数大小超出范围"),
                                            (1, -99.01, "参数大小超出范围"), ("文", 9.3, "参数非数字"), (4, '字', "参数非数字")])
    def test_add1(self, a, b, expect):
        try:
            assert self.cal.add(a, b) == expect
        except TypeError:
            print("参数的类型输入错误")




import pytest
from script.calculator import Calculator

class TestAdd:

def setup(self):
    print("开始计算")

@pytest.mark.p0
def test_add1(self):
    self.cal = Calculator()
    result = self.cal.add(1,1)
    expect = 2
    assert result == expect

@pytest.mark.p0
def test_add2(self):
    self.cal = Calculator()
    result = self.cal.add(-0.01,0.02)
    expect = 0.01
    assert result == expect

@pytest.mark.p0
def test_add3(self):
    self.cal = Calculator()
    result = self.cal.add(10,0.02)
    expect = 10.02
    assert result == expect

@pytest.mark.p1
def test_add4(self):
    self.cal = Calculator()
    result = self.cal.add(98.99,99)
    expect = 197.99
    assert result == expect

@pytest.mark.p1
def test_add5(self):
    self.cal = Calculator()
    result = self.cal.add(99,98.99)
    expect = 197.99
    assert result == expect

@pytest.mark.p1
def test_add6(self):
    self.cal = Calculator()
    result = self.cal.add(-98.99, -99)
    expect = -197.99
    assert result == expect

@pytest.mark.p1
def test_add7(self):
    self.cal = Calculator()
    result = self.cal.add(-99, -98.99)
    expect = -197.99
    assert result == expect

@pytest.mark.p1
def test_add8(self):
    self.cal = Calculator()
    result = self.cal.add(99.01, 0)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.p1
def test_add9(self):
    self.cal = Calculator()
    result = self.cal.add(-99.01, -1)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.p1
def test_add10(self):
    self.cal = Calculator()
    result = self.cal.add(2,99.01)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.p1
def test_add11(self):
    self.cal = Calculator()
    result = self.cal.add(1, -99.01)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.p1
def test_add12(self):
    self.cal = Calculator()
    result = self.cal.add("文", 9.3)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.p1
def test_add13(self):
    self.cal = Calculator()
    result = self.cal.add(4, "字")
    expect = "参数大小超出范围"
    assert result == expect



def teardown(self):
    print("结束计算")


def teardown_class(self):
    print("结束测试")

import pytest

from calculator import Calculator

class TestAdd:

def setup_class(self):
    self.calc = Calculator()

def setup(self):
    print("开始计算")

def teardown(self):
    print("结束计算")

def teardown_class(self):
    print("结束计算")

def test_add1(self):
    expect = 0.01
    assert expect == self.calc.add(-0.01, 0.02)

def test_add2(self):
    expect = 10.02
    assert expect == self.calc.add(10, 0.02)

def test_add3(self):
    expect = 197.99
    assert expect == self.calc.add(98.99, 99)

def test_add4(self):
    expect = 197.99
    assert expect == self.calc.add(99, 98.99)

def test_add5(self):
    expect = -197.99
    assert expect == self.calc.add(-98.99, -99)

def test_add6(self):
    expect = -197.99
    assert expect == self.calc.add(-99, -98.99)
import pytest
from calculator.calculator import Calculator
import yaml

class TestAdd:

    def setup_class(self):
        self.cal = Calculator()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算 ")

    def teardown_class(self):
        print("结束测试")

    @pytest.mark.parametrize("a, b, excepted", [[1, 1, 2], [-0.01, 0.02, 0.01], [10, 0.02, 10.02],
                                                [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, "参数大小超出范围"]])
    def test_add1(self, a, b, excepted):
        reslut = self.cal.add(a, b)
        assert reslut == excepted

    def test_add2(self):
        excepted = "不支持中文,请输入整数或浮点数"

        with pytest.raises(TypeError) as e:
            raise TypeError(excepted)
            result = self.cal.add("文", 1)
            assert e.value.args[0] == excepted
from src.cal_culator import Calculator
import pytest

@pytest.mark.parametrize(
        'par1, par2, exp',
        [
            (1,1,2), 
            (-0.01,0.02, 0.01), 
            (10,0.02,10.02),
            (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,"参数大小超出范围"),
            ("文",9.3,"参数大小超出范围"), # 被测程序没有校验传入类型,抛TypeError
            (4,"字","参数大小超出范围"), # 被测程序没有校验传入类型,抛TypeError
        ])
class TestAdd:
    def setup_class(self):
        print("开始测试")
        self.cal = Calculator()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算 ")

    def teardown_class(self):
        print("结束测试")
        
    def test_add_001(self, par1, par2, exp):
        print(f"本次计算 {par1} + {par2},预期结果:{exp}")
        result = self.cal.add(par1, par2)
        assert result == exp


import pytest
from pytest_rumen.calculator.projectfile import Calculator

class TestAdd:

def setup(self):
    print("开始计算")

def teardown(self):
    print("结束运算")

@pytest.mark.P0
@pytest.mark.parametrize("a, b, expect", [(1, 1, 2), (-0.01, 0.02, 0.01), (10, 0.02, 10.02)], ids=["int_add", "int_float_add", "f_add"])
def test_add1(self, a, b, expect):
    self.cal = Calculator()
    # result 实际
    result = self.cal.add(a, b)
    assert result == expect

@pytest.mark.P1
@pytest.mark.parametrize("a, b, expect", [(98.99, 99, 197.99), (99, 98.99, 197.99), (-98.99, -99, -197.99), (-99, -98.99)])
def test_add2(self, a, expect):
    self.cal = Calculator()
    # result 实际
    result = self.cal.add(a, b)
    assert result == expect

@pytest.mark.P2
@pytest.mark.parametrize("a, b, expect", [(99.01, 0, "参数大小超出范围"), (-99.01, -1, "参数大小超出范围"), (2, 99.01, "参数大小超出范围"), (1, -99.01, "参数大小超出范围")])
def test_add3(self, a, b, expect):
    self.cal = Calculator()
    # result 实际
    result = self.cal.add(a, b)
    assert result == expect

@pytest.mark.P3
@pytest.mark.parametrize("a, b, expect", [("文", 9.3, "参数大小超出范围"), (4, "字", "参数大小超出范围"))
def test_add3(self, a, b, expect):
    self.cal = Calculator()
    # result 实际
    result = self.cal.add(a, b)
    assert result == expect

def teardown_class(self):
    print("结束测试")

import pytest
from script.calculator import Calculator

class TestAdd:

def setup_class(self):
    self.cal = Calculator()

def setup(self):
    print("开始计算")

def teardown(self):
    print("结束计算")

def teardown_class(self):
    print("测试完成")

@pytest.mark.P0
def test_add1(self):
    # result 实际
    result = self.cal.add(1,1)
    expect = 2
    assert result == expect

@pytest.mark.P0
def test_add2(self):
    result = self.cal.add(-0.01,0.02)
    expect = 0.01
    assert result == expect

@pytest.mark.P0
def test_add3(self):
    result = self.cal.add(10,0.02)
    expect = 10.02
    assert result == expect

@pytest.mark.P1
def test_add4(self):
    result = self.cal.add(98.99,99)
    expect = 197.99
    assert result == expect

@pytest.mark.P1
def test_add5(self):
    result = self.cal.add(99,98.99)
    expect = 197.99
    assert result == expect

@pytest.mark.P1
def test_add6(self):
    result = self.cal.add(-98.99, -99)
    expect = -197.99
    assert result == expect

@pytest.mark.P1
def test_add7(self):
    result = self.cal.add(-99, -98.99)
    expect = -197.99
    assert result == expect

@pytest.mark.P1
def test_add8(self):
    result = self.cal.add(99.01, 0)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.P1
def test_add9(self):
    result = self.cal.add(-99.01, 0)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.P1
def test_add10(self):
    result = self.cal.add(99.01, -1)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.P1
def test_add11(self):
    result = self.cal.add(2, -99.01)
    expect = "参数大小超出范围"
    assert result == expect

@pytest.mark.P1
def test_add12(self):
    # try:
    #     result = self.cal.add("文", 9.3)
    # except TypeError as e:
    #     print(e.typename)
    with pytest.raises(TypeError) as e:
        result = self.cal.add("文", 9.3)

测试代码:

import logging

import pytest
import yaml

def get_calc_datas():
    with open('./tmp_calc_datas_p0.yml')as f:
        calc_datas=yaml.safe_load(f)
        return calc_datas
def test_get_calc_datas():
    print(get_calc_datas()['add']['ids'])

class TestCalculator:
    @pytest.mark.parametrize('a,b,expect',get_calc_datas()['add']['datas'],ids=get_calc_datas()['add']['ids'])
    @pytest.mark.p0
    def test_add_p0(self,get_calc_object,a,b,expect):
        logging.info("加法运算")
        assert get_calc_object.add(a,b)==expect

    @pytest.mark.parametrize('a,b,expect', get_calc_datas()['div']['datas'], ids=get_calc_datas()['div']['ids'])
    @pytest.mark.p0
    def test_div(self, a, b, expect, get_calc_object):
        logging.info("除法运算")
        assert get_calc_object.div(a, b) == expect

测试报告:

base.py

from calcalator.demoExample.calcator import Calculator


class Base:
    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def setup_class(self):
        self.calc = Calculator()

    def teardown_class(self):
        print("结束测试")

    def teardown_module(self):
        print("所有用例执行完成")

test_add.py

import allure
import pytest

from calcalator.base.base import Base
from calcalator.demoExample.calcator import Calculator


class TestCase(Base):
    argnameddemo = (
    [1, 1, 2], [-0.01, 0.02, 0.01], [10, 0.02, 10.02], [98.99, 99, 197.99], [99, 98.99, 197.99], [-99, -98.99, -197.99]
    , [-98.99, -99, -197.99], [-99.01, 0, '参数大小超出范围'], [-99.01, -1, '参数大小超出范围'], [2, 99.01, '参数大小超出范围'],
    [1, -99.01, '参数大小超出范围'])

    @pytest.mark.P0
    @allure.feature("有效值及无效值用例")
    @pytest.mark.parametrize('a,b,expectvalue', argnameddemo)
    def test_add1(self, a, b, expectvalue):
        with allure.step("第一步:a,b两数相加"):
            result = self.calc.add(a, b)
        with allure.step("第二步:期望值结果赋值"):
            expect = expectvalue
        with allure.step("第三步:断言"):
            assert result == expect

    @pytest.mark.P1
    @allure.feature("异常情况处理1")
    def test_add12(self):
        # try:
        #     result = self.calc.add("文", 9.3)
        # except TypeError as e:
        #     print("发生异常信息")
        with pytest.raises(TypeError) as e:
            result = self.calc.add("文", 9.3)

    @pytest.mark.P1
    @allure.feature("异常情况处理2")
    def test_add13(self):
        try:
            result = self.calc.add(4, '字')
        except TypeError as e:
            print("发生异常")


import logging

import allure
import pytest
from pytestStu.practice.caculator import Calculator
from pytestStu.practice.cases.base.base import Base


@allure.feature("加法测试")
class TestAdd(Base):
    @pytest.mark.parametrize('a,b,expect', [(1, 1, 2), (-0.01, 0.02, 0.01), (10, 0.02, 10.02),
                                            (98.99, 99, 197.99), (99, 98.99, 197.99), (-98.99, -99, -197.99),
                                            (99.01, 0, "参数大小超出范围"), (-99.01, 0, "参数大小超出范围"), (2, 99.01, "参数大小超出范围"),
                                            (1, -99.01, "参数大小超出范围"), ("文", 9.3, "参数非数字"), (4, '字', "参数非数字")])
    @allure.story("测试 加法正向用例")
    def test_add1(self, a, b, expect):
        logging.info(f"输入的参数a={a},b={b},expect={expect}")
        try:
            assert self.cal.add(a, b) == expect
        except TypeError:
            logging.error("输入非法参数")

    @allure.story("测试加法 反向用例")
    def test_add2(self):
        with pytest.raises(TypeError) as e:
            result = self.cal.add("文", 9.3)

import allure
import pytest
import yaml
from test.base.Base import Base
from test.utils.log_util import logger


@allure.feature("计算器模块")
@allure.story("加法功能")
class TestAdd(Base):
    logger.info("读取yaml数据:字典类型")
    pathadd = r"C:\workplace\PycharmProject\PytestCalculator\test\cases\add\adddata.yml"
    with open(pathadd, "r", encoding="utf-8") as f:
        add_data = yaml.safe_load(f)

    @allure.title("加法:成功")
    @pytest.mark.success
    @pytest.mark.parametrize("add1,add2,expect",
                             add_data["success"].values(),
                             ids=add_data["success"].keys())
    def test_add_success(self,add1,add2,expect):
        logger.info(f"输入数据:{add1},{add2},期望结果:{expect}")
        with allure.step("step1:相加操作"):
            result = self.cal.add(add1,add2)
        logger.info(f"断言实际结果{result}=={expect}")
        with allure.step("step2:断言"):
            assert result == expect

    @allure.title("加法:入参提示")
    @pytest.mark.tips
    @pytest.mark.parametrize("add1,add2,expect",
                             add_data["tips"].values(),
                             ids=add_data["tips"].keys())
    def test_add_tips(self, add1, add2, expect):
        logger.info(f"输入数据:{add1},{add2},期望结果:{expect}")
        with allure.step("step1:相加操作"):
            result = self.cal.add(add1, add2)
        logger.info(f"断言实际结果{result}=={expect}")
        with allure.step("step2:断言"):
            assert result == expect

    @allure.title("加法:入参错误")
    @pytest.mark.error
    @pytest.mark.parametrize("add1,add2,expect",
                             add_data["error"].values(),
                             ids=add_data["error"].keys())
    def test_add_error(self, add1, add2, expect):
        logger.info(f"输入数据:{add1},{add2},期望结果:{expect}")
        with pytest.raises(TypeError):
            with allure.step("step1:相加操作"):
                result = self.cal.add(add1, add2)
            logger.info(f"断言实际结果{result}=={expect}")
            with allure.step("step2:断言"):
                assert result == expect