Mindee

主要记录各种包的使用代码例子, 遇到问题的处理方式 项目记录更新全部代码

  博客园  :: 首页  :: 新随笔  ::  ::  :: 管理

pytest

执行方式:

  1. pytest test_XXX.py
  2. py.test 也可以直接执行它自己识别到的带test_的py文件
  3. pytest test_math_func.py::test_add — 只测试其中一个函数
  4. pytest -v -k “add or string” —测试命名中带有’add’或‘string’字符串的所有函数
  5. pytest -v -m

可选参数:

-v verbose,会显示具体通过了哪些测试

-k keyword

-m marker

-x exit first —遇到一个测试用例报错程序就停止

—tb==no 去掉报错原因提示

—maxfail=2 遇到2个错误就停止运行

skip 跳过某个函数的测试

-s(—capture=no) 允许函数内的print函数也能输出(正常只显示assert 的 passed/failed)

-q quit mode 只显示一共有多少个用例通过

def test_add_strings():
    result = math_func_add('Hello','World')
    assert result == 'Hello World'
    assert type(result) is str 
    assert "Heloe" not in str

-m 的用法 — 只测试带有mark装饰器名称的函数

@pytest.mark.number
def test_product():
    assert math_func.product(5,5)  == 25
    assert math_func.product(5)  == 10
 
@pytest.mark.strings
def test_add_strings():
    result = math_func_add('Hello','World')
    assert result == 'Hello World'
    assert type(result) is str 
    assert "Heloe" not in str

@pytest.mark.strings
def test_product_strings():
    assert math_func.product("Hello ", 3) == 'Hello Hello Hellow '

pytest test_XXX.py -v -m number — 只测试带有@pytest.mark.number的方法,其他的忽略

skip, skipif 的用法

@pytest.mark.skip(reason="dont run number add test")
def test_add_strings():
    result = math_func_add('Hello','World')
    assert result == 'Hello World'
    assert type(result) is str 
    assert "Heloe" not in str

@pytest.mark.skipif(sys.version_info < (3,3), reason='dont run when python version is under 3.3')
def test_product():
    assert math_func.product(5,5)  == 25
    assert math_func.product(5)  == 9

 

装饰器方法 decorator functions 

#num1指的是第一个入参,num2指的是第二个入参, result也会被变量化
@pytest.mark.parameterize('num1, num2','result',
                          [
                              (7,3,10),
                              ('Hello',' World', 'Hello World'),
                              (10.5,24.0, 36)
                          ])
def test_add():
    assert math_func.add(num1,num2) == result

 

如何避免在测试中重复生成多个类的实例(一个类多个方法的测试)

  1. 使用 setup, teardown
  2. 使用fixture

data.json

math_func.py

import json 

class StudentDB:
    def __init__(self):
        self.__data = None 
        
    def connect(self, data_file):
        with open(data_file) as json_file:
            self.__data = json.load(json_file)
            
    def get_data(self, name):
        for student in self.__data['students']:
            if student['name'] == name:
                return student 

    def close(self):
        pass

test_math_func.py

import pytest
from math_func import StudentDB 

db = None 

def setup_module(module):
    #测试开启的操作
    print('-----test setup-----')
    global db 
    db = StudentDB()
    db.connect('data.json')

def teardown_module(module):
    #结束后的操作
    print('-----test teardown-----')
    db.close()

def test_scott_data():
    #有了setup生成module这里就不需要再实例化
    # db = StudentDB()
    db.connect('data.json')
    scott_data = db.get_data('Scott')
    assert scott_data['id'] == 1 
    assert scott_data['name'] == 'Scott'
    assert scott_data['result'] == 'pass'

def test_mark_data():
    #有了setup生成module这里就不需要再实例化
    # db = StudentDB()
    db.connect('data.json')
    mark_data = db.get_data('Mark')
    assert mark_data['id'] == 2 
    assert mark_data["name"] == 'Mark'
    assert mark_data['result'] == 'fail'

 

方法二:使用fixture

import pytest
from math_func import StudentDB 

#固定的操作,return回来的db, scope代表🈯只在开始执行一次即可
@pytest.fixture(scope='module')
def db():
    #测试开启的操作
    print('------test setup------')
    db = StudentDB()
    db.connect('data.json')
    yield db 
    print('-----test teardown(finished)')
    db.close()

def test_scott_data(db):

    db.connect('data.json')
    scott_data = db.get_data('Scott')
    assert scott_data['id'] == 1 
    assert scott_data['name'] == 'Scott'
    assert scott_data['result'] == 'pass'

def test_mark_data(db):
    db.connect('data.json')
    mark_data = db.get_data('Mark')
    assert mark_data['id'] == 2 
    assert mark_data["name"] == 'Mark'
    assert mark_data['result'] == 'fail'

 

posted on 2022-10-31 07:48  Mindee  阅读(28)  评论(0)    收藏  举报