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


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

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

python单元测试学习笔记3https://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 -v

pytest -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 = id
        self.name = name 

def test_student():
    student = Student(id=1, name="Jack")

    assert student.id ==1
    assert student.name == "Jack"

class TestStudent:
    def test_student(self):
        student = Student(id=1, name="Jack")

        assert student.id ==1
        assert 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 ==1
    assert student.name == "Jack"

09.PyTest fixture基础

PyTest fixture定义和使用

使用@pytest.fixture定义

定义一个student.py

class Student:
    def __init__(self, id, name) -> None:
        self.id = id
        self.name = name

    def rename(self, new_name: str) ->bool:
        if 3 < len(new_name) < 10:
            self.name = new_name
            return True
        return False 

    def vaild_student(self) ->bool:
        if self.name:
            return 3 < len(self.name) < 10

测试代码:

import pytest
from student import Student

class TestStudent:
    @pytest.fixture
    def vaild_student(self):
        """使用yield很方便在测试用力之前做setup, 之后做cleanup
        """
        student = Student(id=1, name = "Mary")
        # setup....
        yield student
        # cleanup...

    def test_rename_false(self, vaild_student):
        # setup
        new_name = "dsadadddddddddasssssssssssss"
        excepted_result = False

        # Action
        actural_result = vaild_student.rename(new_name)

        # assert
        assert 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 course

def 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 = True
	actural_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 = 0

        for n in args:
            result += n
            if n==2:
                result += 5
        
        return result
    
    def is_odd(self, num:int)->bool:
        return num%2 !=0


import unittest
import parameterized
class TestCalculator(unittest.TestCase):
    @parameterized.expend([[1,True], [2, False]])
    def test_is_odd(self,num, excepted_out):
        # SetUp
        cal = Calculator()

        # Action
        actural_result = cal.is_odd(num)

        # assert
        assert actural_result == excepted_out

使用pytest实现

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

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

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值