pytest使用报错(以及解决pytest所谓的“抑制print输出”)

1. 测试类的类名问题

python 复制代码
#coding=utf-8

import pytest

class TestClass1:
    def setup(self) -> None:
        print('setup')

    def test_01(self) -> None:
        print('test_01111111111111111111111')

    def test_02(self) -> None:
        print('test_02')

以上述代码为例,如果类名是Test开头,可以正常运行,并且输出print的内容,

如果以Test结尾

python 复制代码
# coding=utf-8

import pytest


class Class1Test:
    def setup(self) -> None:
        print('setup')

    def test_01(self) -> None:
        print('test_01111111111111111111111')

    def test_02(self) -> None:
        print('test_02')

代码可以运行,但是结果会报错

所以,必须严格按照要求,测试类的文件名 以 test_ 开头进行命名,测试类 以 Test 开头进行命名,测试方法以 test_ 开头进行命名

2. setup方法

如果有需要调用其他实体类在setup中进行实例化的,需要按照要求,以实际需要进行命名,不能直接写set方法,会找不到具体的类。

2.1 模块级别 setup_module()

模块级别,执行所有的测试用例之前会执行一遍,有且只有一次

2.2 函数级别 setup_function()

class类之外的函数执行一次,这个setup就会执行一次

2.3 类级别 setup_class()

类执行一次,就会执行一次

2.4 方法级别 setup_method()

类中的方法执行一次,就会执行一次

2.5 举例

python 复制代码
#coding=utf-8
import pytest

def setup_module(module):
    print("初始化=================模块")

def teardown_module(module):
    print("清理===================模块")

def setup_function(module):
    print("初始化=================函数")

def teardown_function(module):
    print("清理===================函数")

def test_01():
    print("类外的函数方法1=========")
    assert 1+2==3

def test_02():
    print("类外的函数2=========")
    assert 3+2==5

class TestClass1:
    def setup_class(self):
        print("初始化==============类1")

    def teardown_class(self):
        print("清理================类1")

    def setup_method(self):
        print("初始化1==============方法")

    def teardown_method(self):
        print("清理1================方法")

    def test_1_01(self):
        print("类1 的 测试方法 1 ")
        assert 1+1 ==2

    def test_1_02(self):
        print("类1 的测试方法 2")
        assert 1+2 == 3

代码运行结果为

  • 模块级别setup
    • 函数setup1
    • 函数teardown1
    • 函数setup2
    • 函数teardown2
    • 类级别setup
      • 方法setup1
      • 方法teardown1
      • 方法setup2
      • 方法teardown2
    • 类级别teardown
  • 模块级别teardown
相关推荐
努力搬砖的咸鱼1 天前
从零开始搭建 Pytest 测试框架(Python 3.8 + PyCharm 版)
python·pycharm·pytest
FINE!(正在努力!)3 天前
PyTest框架学习
学习·pytest
程序员杰哥4 天前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
测试老哥4 天前
Pytest+Selenium UI自动化测试实战实例
自动化测试·软件测试·python·selenium·测试工具·ui·pytest
水银嘻嘻4 天前
07 APP 自动化- appium+pytest+allure框架封装
python·appium·自动化·pytest
天才测试猿5 天前
接口自动化测试之pytest接口关联框架封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
not coder6 天前
Pytest Fixture 详解
数据库·pytest
not coder6 天前
pytest 常见问题解答 (FAQ)
开发语言·python·pytest
程序员的世界你不懂6 天前
(1)pytest简介和环境准备
pytest
not coder6 天前
Pytest Fixture 是什么?
数据库·oracle·pytest