当前位置: 首页 > news >正文

【Python单元测试】学习笔记3

文章目录

    • 08.PyTest框架
      • 什么是PyTest
      • PyTest的优点
      • PyTest的测试环境
      • PyTest常用参数
      • 跳过测试
    • 09.PyTest fixture基础
      • PyTest fixture定义和使用
      • 引用多个Fixture
    • 10. conftest.py
      • conftest.py的用途
    • 11. 参数化测试用例
      • 为什么需要参数化测试用例
      • 使用parameterizer插件实现
      • 使用pytest实现

python单元测试学习笔记1: https://blog.csdn.net/qq_42761751/article/details/141144477?spm=1001.2014.3001.5501

python单元测试学习笔记2 :https://blog.csdn.net/qq_42761751/article/details/141202123?spm=1001.2014.3001.5501

python单元测试学习笔记3 : https://blog.csdn.net/qq_42761751/article/details/141233236?spm=1001.2014.3001.5501

08.PyTest框架

unittest是python内置的框架,pytest是第三方测试框架,在目前实际应用中比较流行

  1. 什么是PyTest
  2. PyTest的优点
  3. PyTest的测试环境
  4. PyTest的常用参数
  5. 跳过测试

什么是PyTest

PyTest是一个基于Python语言的第三方的测试框架

PyTest的优点

  1. 语法简单
  2. 自动检测测试代码
  3. 跳过指定测试
  4. 开源

PyTest的测试环境

安装PyTest

pip install pytest

运行PyTest

# -v 可以显示详细信息
pytest -vpytest -v test_xxx.py
  1. 自动查找test_*.py, *_test.py测试文件
  2. 自动查找测试文件中的test_开头的函数和Test开头的类中的test_开头的方法。如果不是test_开头的函数或者不是Test开头的类中的test_开头的方法是不会被执行的
  3. 之前unittest的代码不用改变,可以直接用pytest执行

代码示例:

class Student:def __init__(self, id, name) -> None:self.id = idself.name = name def test_student():student = Student(id=1, name="Jack")assert student.id ==1assert student.name == "Jack"class TestStudent:def test_student(self):student = Student(id=1, name="Jack")assert student.id ==1assert student.name == "Jack"

PyTest常用参数

-v : 输出详细的执行信息,比如文件及用例名称等
-s:输出调试信息,比如print的打印信息
-x:遇到错误用例立即停止

跳过测试

跳过测试的方式有两种

  1. @pytest.mark.skip 无论如何都跳过
  2. @pytest.mark.skipif
import sys
import pytest
def is_skip():# 判断是否为MacOS操作系统return sys.platform.casefold() == "darwin".casefold()# @pytest.mark.skip(reason="hahaha")  # 无论如何都跳过
@pytest.mark.skipif(condition=is_skip(), reason="skip on macos")  # 如果is_skip返回是True就跳过,is_skip不是True就不跳过
def test_student():student = Student(id=1, name="Jack")assert student.id ==1assert student.name == "Jack"

09.PyTest fixture基础

PyTest fixture定义和使用

使用@pytest.fixture定义

定义一个student.py

class Student:def __init__(self, id, name) -> None:self.id = idself.name = namedef rename(self, new_name: str) ->bool:if 3 < len(new_name) < 10:self.name = new_namereturn Truereturn False def vaild_student(self) ->bool:if self.name:return 3 < len(self.name) < 10

测试代码:

import pytest
from student import Studentclass TestStudent:@pytest.fixturedef vaild_student(self):"""使用yield很方便在测试用力之前做setup, 之后做cleanup"""student = Student(id=1, name = "Mary")# setup....yield student# cleanup...def test_rename_false(self, vaild_student):# setupnew_name = "dsadadddddddddasssssssssssss"excepted_result = False# Actionactural_result = vaild_student.rename(new_name)# assertassert actural_result == excepted_result

引用多个Fixture

  1. 一个unit test或fixture可以使用多个其他的fixture:
import pytest@pytest.fixture
def student():yield Student()@pytest.fixture
def course():yield Course()def test_regisiter_course(student, course):...
  1. 一个fixture可以被一个test引用多次
@pytest.fixture
def student():return Student()@pytest.fixture
def course():return Course()@pytest.fixture
def course_student(course, student):course.add_student(student)return coursedef test_regisiter_course(course_student, course):...

10. conftest.py

conftest.py的用途

使得fixture可以被多个文件中的测试用例复用

在项目目录下直接新建conftest.py:

import pytest@pytest.ficture
def male_student_fixture():student = Student(id =1, name = "Jack")

在测试代码中可直接使用,pytest会自动找到这个文件:

def test_vaild_gender_true(self, male_student_fixture):expected_result = Trueactural_result = male_student_fixture.vaild_gender()assert actual_result == expected_result

方式2:在conftest.py中引入fixture(建议使用这种方式)

# conftest.py
import pytest
from student_fixture import male_student_fixture

11. 参数化测试用例

为什么需要参数化测试用例

针对同一个被测试函数需要进行多组数据的测试,比如测试一个奇偶性判断的函数,我们一个可以n个数一起测试写到一个测试函数中,而不是每个数单独写一个测试函数

使用parameterizer插件实现

安装parameterizer

pip install parameterized

测试代码:(为了方便将代码与测试代码放在一个py文件下)

class Calculator:def add(self, *args):result = 0for n in args:result += nif n==2:result += 5return resultdef is_odd(self, num:int)->bool:return num%2 !=0import unittest
import parameterized
class TestCalculator(unittest.TestCase):@parameterized.expend([[1,True], [2, False]])def test_is_odd(self,num, excepted_out):# SetUpcal = Calculator()# Actionactural_result = cal.is_odd(num)# assertassert actural_result == excepted_out

使用pytest实现

import pytest
@pytest.mark.parametrize("num, excepted_result", [(1, True), (2,False)])
def test_is_odd(num, excepted_result):# setupcal = Calculator()# Actionresult = cal.is_odd(num)# assertassert result == excepted_result

本文参考:https://www.bilibili.com/video/BV1z64y177VF/?spm_id_from=pageDriver&vd_source=cf0b4c9c919d381324e8f3466e714d7a

http://www.lryc.cn/news/424995.html

相关文章:

  • OpenSSL源码编译及Debug
  • go之goburrow/modbus 学习
  • 开放词汇目标检测(Open-Vocabulary Object Detection, OVOD)算法是什么?
  • 【教程】Ubuntu给pycharm添加侧边栏快捷方式
  • 三个月外贸小白好迷茫,该何去何从?
  • MySQL数据库——基本查询(Create)
  • spring-security-1-快速入门
  • 5 大场景上手通义灵码企业知识库 RAG
  • 免费远程控制电脑的软件有哪些?
  • Linux软件包yum
  • 网页的切换与嵌套
  • 基于飞桨框架的稀疏计算使用指南
  • 启明云端WT32C3-S6物联网模块,乐鑫ESP32-C3芯片技术应用
  • 超越流水线,企业研发规范落地新思路
  • 财务会计与管理会计(四)
  • 回归分析系列1-多元线性回归
  • web小游戏开发:拼图——蜂巢拼图
  • springCloud集成activiti5.22.0流程引擎(分支)
  • ppt模板免费网站有哪些?自动美化工具推荐
  • java实现解析pdf格式发票
  • 数据结构初阶——算法复杂度超详解
  • ArcGIS Pro SDK (十二)布局 4 预定义的形状和箭头
  • 在 Ubuntu 14.04 服务器上安装 ISPConfig3 的方法
  • ELK学习笔记
  • Python+Selenium+Pytest+POM自动化测试框架封装详解
  • Hidden Marlov Model(HMM)
  • mamba的安装及下载速度慢问题解决
  • 【Linux入门】Linux环境搭建
  • CPU缓存一致性机制详解
  • Android 12系统源码_屏幕设备(一)DisplayManagerService的启动