pytest測試實戰和練習


開頭

經過前面幾章的學習,這時候要來個測試實戰會比較好鞏固一下學過的知識
任務要求
1、實現計算器(加法,除法)的測試用例

2、使用數據驅動完成測試用例的自動生成

3、在調用測試方法之前打印【開始計算】,在調用測試方法之后打印【計算結束】

目錄結構

目錄解析
datas/calc_list.yaml yaml文件用來保存相關的測試用例 要使用yaml先得安裝yaml相關的包 pyyaml
result目錄為pytest生成的來存放測試報告的目錄
calc.py 為 計算器通用函數的一個類
test_cala.py 執行pytest測試用例的文件

calc_list.yaml

# 計算器的測試用例合集
calc_case:
  add_list:
      - [1,2,3]
      - [100,200,300]
      - [0.1,0.2,0.3]
      - [-1,-2,-3]
      - [-0.1, 0.2, 0.3]

  sub_list:
      - [2,1,1]
      - [300,200,100]
      - [0.1,0.2,-0.1]
      - [-1,-2, 1]
      - [-0.1, -0.2, 0.3]

  mul_list:
      - [1,2,2]
      - [100,200,20000]
      - [0.1,0.2,0.02]
      - [-1,-2,2]
      - [-0.1, 0.2, 0.2]

  div_list:
      - [1,2,0.5]
      - [100,200,0.5]
      - [0.1,0.2,0.5]
      - [-1,-2,0.5]
      - [-0.1, 0, 0]
  all_ids:
      - 'int'
      - 'bigint'
      - 'float'
      - 'negative'
      - 'fail'

calc.py

# 計算器
class Calculator:
    def add(self, a, b):
        return a + b

    def sub(self, a, b):
        return a - b

    def mul(self, a, b):
        return a * b

    def division(self, a, b):
        return a / b

test_calc.py

from calc import Calculator
import yaml
import pytest
import allure


with open('./datas/calc_list.yaml', 'r', encoding='utf-8') as f:
    datas = yaml.safe_load(f)['calc_case']
    add_list = datas['add_list']  # 加法測試用例
    sub_list = datas['sub_list']  # 減法測試用例
    mul_list = datas['mul_list']  # 乘法測試用例
    div_list = datas['div_list']  # 除法測試用例
    ids = datas['all_ids']  # 全部的標簽
    print(datas)


@allure.feature("計算器模塊")
class TestCalc:
    def setup_class(self):
        print("計算器開始計算")
        self.calc = Calculator()

    def teardown_class(self):
        print("計算器結束計算")

    @allure.story("加法運算")
    @pytest.mark.parametrize("a, b, expect", add_list, ids=ids)
    def test_add(self, a, b, expect):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = self.calc.add(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result

    @allure.story("減法運算")
    @pytest.mark.parametrize("a, b, expect", sub_list, ids=ids)
    def test_sub(self, a, b, expect):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = self.calc.sub(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result

    @allure.story("乘法運算")
    @pytest.mark.parametrize("a, b, expect", mul_list, ids=ids)
    def test_mul(self, a, b, expect):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = self.calc.mul(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result

    @allure.story("除法運算")
    @pytest.mark.parametrize("a, b, expect", div_list, ids=ids)
    def test_div(self, a, b, expect):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = self.calc.division(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result


if __name__ == '__main__':
    # pytest.main(["-vs", "test_calc.py::TestCalc::test_div"])  # 不需要allure的時候執行, 指定某個測試用例
    pytest.main(["--alluredir=result/2", "test_calc.py"])  # 生成allure
    # 查看allure用例 allure serve .\result\2\

生成的allure如圖所示

任務改寫2

1、改造 計算器 測試用例,使用fixture函數獲取計算器的實例
2、計算之前打印開始計算,計算之后打印結束計算
3、添加用例日志,並將日志保存到日志文件目錄下
4、生成測試報告,展示測試用例的標題,用例步驟,與測試日志,截圖附到課程貼下

目錄結構

目錄解析
datas/calc_list.yaml yaml文件用來保存相關的測試用例 要使用yaml先得安裝yaml相關的包 pyyaml
result目錄為pytest生成的來存放測試報告的目錄
calc.py 為 計算器通用函數的一個類
test_cala2.py 執行pytest測試用例的文件
conftest.py 為所有測試用例執行前都會執行到這個的文件,要有__init__.py文件跟在同目錄下
pytest.ini pytest框架的一個設置, 可以設置開啟日志

conftest.py 用fixture改寫:

import pytest
from .calc import Calculator

@pytest.fixture(scope="class")
def get_cal():
    print("====實例化計算器, 開始計算===")
    cal = Calculator()
    yield cal
    print("====計算完成====")

pytest.ini 增加保存的日志

[pytest]
log_cli=true
log_level=NOTSET
log_format = %(asctime)s %(levelname)s %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
addopts = -vs

log_file = ./test.log
log_file_level = info
log_file_format = %(asctime)s %(levelname)s %(message)s
log_file_date_format = %Y-%m-%d %H:%M:%S

test_cala2.py 改寫第一部分

import yaml
import allure
import pytest
import logging


logging.basicConfig(level=logging.info)
logger = logging.getLogger()

with open('./datas/calc_list.yaml', 'r', encoding='utf-8') as f:
    datas = yaml.safe_load(f)['calc_case']
    add_list = datas['add_list']  # 加法測試用例
    sub_list = datas['sub_list']  # 減法測試用例
    mul_list = datas['mul_list']  # 乘法測試用例
    div_list = datas['div_list']  # 除法測試用例
    ids = datas['all_ids']  # 全部的標簽
    print(datas)


@allure.feature("計算器模塊")
class TestCalc2:
    @allure.story("加法運算")
    @pytest.mark.parametrize("a, b, expect", add_list, ids=ids)
    def test_add(self, a, b, expect, get_cal):
        logger.info('增加加法日志') 
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = get_cal.add(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result

    @allure.story("減法運算")
    @pytest.mark.parametrize("a, b, expect", sub_list, ids=ids)
    def test_sub(self, a, b, expect, get_cal):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = get_cal.sub(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result

    @allure.story("乘法運算")
    @pytest.mark.parametrize("a, b, expect", mul_list, ids=ids)
    def test_mul(self, a, b, expect, get_cal):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = get_cal.mul(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
        assert expect == result

    @allure.story("除法運算")
    @pytest.mark.parametrize("a, b, expect", div_list, ids=ids)
    def test_div(self, a, b, expect, get_cal):
        with allure.step(f"輸入測試用例{a}, {b}, 預期結果為{expect}"):
            result = get_cal.division(a, b)
            if isinstance(result, float):  # 判斷浮點數
                result = round(result, 2)
                print(result)
        assert expect == result


if __name__ == '__main__':
    # pytest.main(["-vs", "test_calc2.py::TestCalc2::test_add"])  # 不需要allure的時候執行, 指定某個測試用例
    pytest.main(["--alluredir=result/3", "test_calc2.py"])  # 生成allure
    # 查看allure用例 allure serve .\result\2\

最后完結。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM