pytest学习(五)- @pytest.fixture和 conftest 使用

前言

  • 定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture(),fixture命名不要用test_开头,跟用例区分开。用例才是test_开头的命名。
  • fixture是可以有返回值的,如果没return默认返回None。用例调用fixture的返回值,直接就是把fixture的函数名称当成变量传入
  • fixture装饰器里的scope有四个级别的参数。”function(不写默认这个)”,”class”,”module”or”session”
  • 除scope之外。还有params、autouse、ids、name等。
  • fixture可以有返回值,如果没有return,默认会是None;用例调用fixture的返回值,就是直接把fixture的函数名称作为参数传入
  • fixture可以返回一个元组、列表或字典
  • test_用例可传单个、多个fixture参数
  • fixture与fixture间可相互调用

1、fixture可以返回一个元祖、列表、字典

代码示例:

import pytest

@pytest.fixture()
def postcode():
    print("========打印装饰器函数=====")
    user = 'admin'
    pwd = '123'
    return user, pwd

def test_01(postcode):
    print(postcode)
    assert postcode[0] == 'admin'
    assert postcode[1] == '123'

if __name__ == '__main__':
    pytest.main(['-sv', 'test_01.py'])

结果:

pytest学习(五)- @pytest.fixture和 conftest 使用

2、用例传多个fixture参数

代码示例:

import pytest

@pytest.fixture()
def user():
    print("=======user装饰器函数===========")
    user = 'root'
    return user

@pytest.fixture()
def pwd():
    print("========pwd装饰器函数=========")
    pwd = '123456'
    return pwd

def test_02(user, pwd):
    print(user, pwd)
    assert user == 'root'
    assert pwd == '123456'

if __name__ == '__main__':
    pytest.main(['-sv', 'test_02.py'])

结果:

pytest学习(五)- @pytest.fixture和 conftest 使用

3、fixture与fixture之间可以互相调用

import pytest

@pytest.fixture()
def first():
    print("\n===first===")
    user = 'root'
    assert user == 'root'
    return user

@pytest.fixture()
def second(first):
    print("\n===second===")
    pwd = 123456
    assert pwd == 123456
    return first, pwd

def test_01(second):
    print('\n', second)
    assert second[0] == 'root'
    assert second[1] == 123456

if __name__ == '__main__':
    pytest.main(['-sv', 'test_03.py'])

结果:

pytest学习(五)- @pytest.fixture和 conftest 使用

语法规则:

@pytest.fixture(scope=”,params=”,autouse=”,ids=”,name=”)

scope:表示的是被@pytest.fixture标记的方法的作用域,function(默认),class,modte,package/session
在定义固件时,通过 scope 参数声明作用域,可选项有:
function: 函数级,每个测试函数都会执行一次固件;
class: 类级别,每个测试类执行一次,所有方法都可以使用;
module: 模块级,每个模块执行一次,模块内函数和方法都可使用;
session: 会话级,一次测试只执行一次,所有被找到的函数和方法都可用。

Params: 参数化

Autouse = true :自动执行,默认False

Ids :当使用params参数化时,给每一个值一个变量名,意义不大。

name: 表示的是被@pytest.fixture标记的方法取一个别名。

1、function级别,在函数前后执行

代码示例:

import pytest

@pytest.fixture(scope="function")
def login():
    print("--这是前置方法--")
    user = 'root'
    pwd = '123'
    yield user, pwd
    print("--这是后置方法--")

class TestDemo:
    def test01(self):
        print("\ntest01")

    def test02(self, login):
        print("\ntest02")
        assert login[0] == 'root'
        assert login[1] == '123'

if __name__ == '__main__':
    pytest.main(['-sv', 'test_05.py'])

结果:

pytest学习(五)- @pytest.fixture和 conftest 使用

小结:
yield和return,都可以返回值,并且返回的值可以在测试用例中获取。
yield生成器,返回一个对象(可以有多个值),yield后面可以接代码。
return返回一个值,return后面不能接代码。
如果加入autouse=True参数,那么表示自动使用,那么和setup,和teardown功能一致。

2、class级别,在类前后执行

若class中的每个test用例都调用了login,只在class所有用例执行前运行一次

代码示例:

import pytest

@pytest.fixture(scope="class")
def login():
    print('\n---前置---')
    a = 'root'
    yield a
    print('\n---后置---')

class TestCase1:
    def test01(self, login):
        print("\ntest01")

    def test02(self, login):
        print("\ntest02")

结果:

pytest学习(五)- @pytest.fixture和 conftest 使用

3、module级别,在模块前后执行

代码示例:

import pytest

@pytest.fixture(scope="module")
def login():
    print("\n---前置---")
    yield
    print("\n---后置---")

class TestCase:
    def test01(self, login):
        print("\ntest01")

    def test02(self, login):
        print("\ntest02")

if __name__ == '__main__':
    pytest.main(['-sv', 'test_07.py'])

结果:

pytest学习(五)- @pytest.fixture和 conftest 使用

4、session会话级别

Original: https://blog.csdn.net/mghoumin/article/details/119874749
Author: mghoumin
Title: pytest学习(五)- @pytest.fixture和 conftest 使用



相关阅读

Title: 线性代数Python计算:矩阵的转置、方阵的行列式和方阵的逆

1.矩阵的转置

numpy用来表示矩阵的2维数组的array对象的T属性,返回矩阵的转置。
例1 设A = ( 2 0 1 1 3 2 ) \boldsymbol{A}=\begin{pmatrix}2&0&1\1&3&2\end{pmatrix}A =(2 1 ​0 3 ​1 2 ​),B = ( 1 7 − 1 4 2 3 2 0 1 ) \boldsymbol{B}=\begin{pmatrix}1&7&-1\4&2&3\2&0&1\end{pmatrix}B =⎝⎛​1 4 2 ​7 2 0 ​−1 3 1 ​⎠⎞​,在Python中验证( A B ) T = B T A T (\boldsymbol{AB})^{\text{T}}=\boldsymbol{B}^\text{T}\boldsymbol{A}^\text{T}(A B )T =B T A T。

import numpy as np
A=np.array([[2,0,-1],
            [1,3,2]])
B=np.array([[1,7,-1],
            [4,2,3],
            [2,0,1]])
print((np.matmul(A,B)).T)
print((np.matmul(B.T, A.T)))

程序中第2~3行和第4~6行分别设置矩阵A \boldsymbol{A}A和B \boldsymbol{B}B。第7行调用numpy的函数matmal(A,B)计算积A B \boldsymbol{AB}A B,然后访问其转置属性matmal(A,B).T输出( A B ) T (\boldsymbol{AB})^\text{T}(A B )T。第8行调用函数matmul(B.T,A.T)计算B T A T \boldsymbol{B}^\text{T}\boldsymbol{A}^\text{T}B T A T。运行程序,输出

[[ 0 17]
 [14 13]
 [-3 10]]
[[ 0 17]
 [14 13]
 [-3 10]]

2. 方阵的行列式

numpy包中用于处理线性代数的linalg模块提供的det函数可用来计算方阵的行列式。
例2:在Python中验算矩阵A = ( 3 1 − 1 2 − 5 1 3 − 4 2 0 1 − 1 1 − 5 3 − 3 ) \boldsymbol{A}=\begin{pmatrix}3&1&-1&2\-5&1&3&-4\2&0&1&-1\1&-5&3&-3\end{pmatrix}A =⎝⎜⎜⎛​3 −5 2 1 ​1 1 0 −5 ​−1 3 1 3 ​2 −4 −1 −3 ​⎠⎟⎟⎞​的行列式det ⁡ A \det\boldsymbol{A}det A。

import numpy as np
A=np.array([[3,1,-1,2],
            [-5,1,3,-4],
            [2,0,1,-1],
            [1,-5,3,-3]])
print(np.linalg.det(A))

运行程序,输出

40.0

即det ⁡ ( 3 1 − 1 2 − 5 1 3 − 4 2 0 1 − 1 1 − 5 3 − 3 ) = 40 \det\begin{pmatrix}3&1&-1&2\-5&1&3&-4\2&0&1&-1\1&-5&3&-3\end{pmatrix}=40 det ⎝⎜⎜⎛​3 −5 2 1 ​1 1 0 −5 ​−1 3 1 3 ​2 −4 −1 −3 ​⎠⎟⎟⎞​=4 0。

3. 方阵的逆阵

numpy.linalg的inv函数计算可逆方阵的逆矩阵。
例3 设矩阵A = ( 1 2 3 2 2 1 3 4 3 ) \boldsymbol{A}=\begin{pmatrix}1&2&3\2&2&1\3&4&3\end{pmatrix}A =⎝⎛​1 2 3 ​2 2 4 ​3 1 3 ​⎠⎞​,计算逆矩阵A − 1 \boldsymbol{A}^{-1}A −1。

import numpy as np
from utility import adjointMatrix
from fractions import Fraction as F
np.set_printoptions(formatter={'all':lambda x:
                               str(F(x).limit_denominator())})
A=np.array([[1,2,3],
            [2,2,1],
            [3,4,3]])
print('%.1f'%np.linalg.det(A))
print(np.linalg.inv(A))

注意程序中的第8行,调用numpy.linalg的inv函数,计算A的逆矩阵。运行程序输出

2.0
[[  1   3 -2]
 [-3/2 -3 5/2]
 [  1   1 -1]]

由于det ⁡ A = 2 \det\boldsymbol{A}=2 det A =2,故A \boldsymbol{A}A可逆,A = ( 1 3 − 2 − 3 2 − 3 5 2 1 1 − 1 ) \boldsymbol{A}=\begin{pmatrix}1&3&-2\-\frac{3}{2}&-3&\frac{5}{2}\1&1&-1\end{pmatrix}A =⎝⎛​1 −2 3 ​1 ​3 −3 1 ​−2 2 5 ​−1 ​⎠⎞​。
写博不易,敬请支持:
如果你从阅读这篇文章中得到了什么,请给出你的喜欢,评论和收藏。谢谢您一直鼓励我!

[En]

If you get something from reading this article, please give your likes, comments and collections. Thank you for your support!

Original: https://blog.csdn.net/u012958850/article/details/125261224
Author: 戌崂石
Title: 线性代数Python计算:矩阵的转置、方阵的行列式和方阵的逆

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/336903/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总