欢迎光临散文网 会员登陆 & 注册

第十一章 自动化测试 Pytest

2023-07-04 13:43 作者:littersho  | 我要投稿

一,pytest配置项  pytest.ini

在主目录ApiTest下面新建一个File(注意这里不是测试用例的 python File ),命名为pytest.ini

[pytest]

testpaths=./test_xx(具体目录/文件)#执行时就只执行该目录下的测试用例


补充:点三角符号执行多条测试用例,引入main函数

if __name__ =='__main__':

       pytest.main()

会把当前py文件中的所有测试用例全部执行

二,setup/teardown

前置操作和后置操作:

ui自动化,前置打开浏览器,后置关闭浏览器

接口自动化, 前置登录或插入测试数据,后置清理垃圾数据


模块级    setup_module/teardown_module  开始于模块始末,生效一次

函数级    setup_function/teardown_function   对每条函数用例生效(不在类中)

类级      setup_class/teardown_class    只在类中前后运行一次(在类中)

方法级    setup_method/teardown_method  开始于方法始末(在类中)

具体使用:

(1)模块级   不管有几条测试用例,只执行一次

def  setup_module():

      print(“准备测试数据”)

def  eardown_module():

      print(“清理测试数据”)

会遇到清理测试数据在准备测试数据前的情况,这种为控制台显示问题,其实执行顺序是正确的

(2)函数级  对每个函数都会执行一次

def  setup_function():

      print(“准备测试数据”)

def  eardown_function():

      print(“清理测试数据”)

(3)类级  和模块级类似,在类中只执行一次

classTestMobile:

    def  setup_class(self):

          print(“准备测试数据”)

    def  eardown_class(self):

          print(“清理测试数据”)

     def test_mobile(self):

 。。。

     def test_baidu(self):

 。。。

需要放在类中的内容圈起来,用tab键调下格式,方法重要加上 self

(4)方法级    对类中的每个函数都会执行一次

classTestMobile:

    def  setup_method(self):

          print(“准备测试数据”)

    def  eardown_method(self):

          print(“清理测试数据”)

     def test_mobile(self):

 。。。

     def test_baidu(self):

 。。。

三,fixture

fixture是pytest用于将测试前后进行预备,清理工作的代码处理机制。

fixture相对于setup/teardown来说有一下几点优势:

  • fixture命名更加灵活,局限性比较小

比如:一个测试.py文件中写了10条测试用例,只有5条想要执行前置后置步骤,就不要需要分成两个文件来处理

  • conftest.py 配置里面可以实现数据共享,不需要import就能自动找到一些配置

fixture夹具,@pytest.fixture

(scope='function')  每一个函数或方法都会调用

(scope='class')  每一个类调用一次

(scope='module')  每一个.py文件会调用一次

(scope='session')  多个文件调用一次,.py文件就是module

fixture的作用范围:session>module>class>function

具体应用:

import request

import pytest

@pytest.fixture

def func():

       print(“我是前置步骤”)

def test_mobile(func):#传func方法执行前置

 。。。

def test_baidu():#不传func方法不执行前置

 。。。

**

①def func(autouse=true):#范围内所有函数都执行,不管是否传func,可以在测试方法中不用一一去添加fixture的名称   

#autouse默认为false

**

②def func(scope=“function”) : ==   def func():

#scope默认为function

四,YAML写法

(1)对象

key:

    child-key:value

    child-key2:value2

等于

{“key”:{“child-key”:“value”,“child-key2”:“value2”}}

(2)数组

key:

    -A

    -B

    -C

等于

{“key”:[A,B,C]}

(3)组合

key:

    -child-key:value

    child-key2:value2

等于

{“key”:[{“child-key”:“value”,“child-key2”:“value2”}]}

(4)数组嵌套

key:

    -

            -A

            -B

            -C

等于

{“key”:[[A,B,C]]}

具体用法:

在主目录ApiTest下面新建一个普通文件夹Directory,命名为config

再在config文件下建立一个file,命名为data.yaml文件

(1)

hero:     #   对象

    name: 安琪拉

    word: 火焰是我最喜欢的玩具

    HP: 血量455.5

补充:也可以用字典形式来写

hero:{name: 安琪拉,word: 火焰是我最喜欢的玩具,HP: 血量455.5}

(2)

hero_name: #数组

    -安琪拉

    -小乔

    -李白

(3)

hero2:     #   组合(字典外面包一个数组)

    -name: 小乔

     word: 风,听从我的呼唤

     HP: 血量389.5

(4)

hero_name2: #数组嵌套(数组外面包一个数组)

    -

     -安琪拉

     -小乔

     -李白

五,YAML读取方式:

第三方包安装:pip install pyyaml

在主目录ApiTest下面新建一个普通文件夹python package,命名为utils

#主要用来放各种工具

utils下在新建一个python file 命名为 read_data.py

import yaml

f=open("../config/data.yaml",encoding="UTF-8")#打开文件

data=yaml.safe_load(f)

print(data)

print(data['hero'])#也可以打印具体的某个数据

补充:很多数据放在json的话就比较乱,层级也不容易看,所以用yaml更便捷一些

json:

[{

"key":"value"

}

]

六,参数化 parametrize

参数化可以组装测试数据,在测试前定义好测试数据,并在测试用例中使用

#单次循环

@pytest.mark.parametrize("a",["b"])   #   (字符串  “”,数组  [])

def test_parametrize(a):

      print(a)

#多次循环


@pytest.mark.parametrize("a,b",[("c","d"),("e","f")])

def test_parametrize(a,b):

      print(a,b)


具体用法:

在testcase下面新建python package 命名为test_parametrize

再在下面新建python file  命名为test_parametrize_01

import pytest

#单参数单次循环

@pytest.mark.parametrize("name",["小白"])

def test_parametrize(name):

      print(“测试parametrize,我的名字是”+name)


#单参数多次循环

@pytest.mark.parametrize("name",["小白",“哈基米”,“小乔”])

def test_parametrize(name):

      print(“测试parametrize,我的名字是”+name)


#多参数单次循环

@pytest.mark.parametrize("name,age",[("哈基米",“3”)])

def test_parametrize(name,age):

      print(“测试parametrize,我的名字是”+name+",年龄是"+age+“岁。”)

注意:单次循环写法
@pytest.mark.parametrize("name,age",[["哈基米",“3”]]) #用[]数组也可以,()元组也可以

@pytest.mark.parametrize("name,age",["哈基米",“3”])#这样写是错误的


#多参数多次循环

@pytest.mark.parametrize("name,age",[["小白","35"],[“哈基米”,"3"],[“小乔”,"18"])

def test_parametrize(name,age):

     print(f‘{name}的年龄是{age}’)


六,数据驱动  参数化 parametrize+yaml

①在data.yaml文件中定义参数

mobile_params:# 定义 number,appkey 

# 功能同params1={“number”:“13167894587”,“appkey”:“0c565f14687d84”}# python中字典数据类型

    - [13167894587,0c565f14687d84]

    - [13187465319,0c554ge9go0235]

②在测试用例中

import requests 

import get_data 

@pytest.mark.parametrize("number,appkey",get_data()['mobile_params'])

def test_mobile(number,appkey):

    params01={"shouji":number,"appkey":appkey}

    r = requests.get(url="https://www.baidu.com",params=params01)

    print (r.status_code)  

    print (r.json())

    assert r.status_code==200

七,allure报告

allure常用方法

1、title 标题

可以自定义用例标题,标题默认为函数名。@allure.title

2、description 描述

可以添加测试的详细说明

3、标签 @allure.feature

4、标签@allure.story

5、 标签 @allure.severity

定义用例的级别,Graphs主要有BLOCKER,CRITICAL,MINOR,NORMAL,TRIVIAL等几种类型,默认是NORMAL。

只运行指定级别的用例 --allure_severities=critical,blocker

6、 动态生成allure.dynamic

可以使用函数体内的数据动态生成

使用方式

1)安装python插件

  • 使用命令安装

  • $ pip3 install allure-pytest

2)配置pytest.ini

[pytest]

testpaths = ./testcases

markes =

p0:高优先级

test:测试环境

pro:生产环境

addopts = -vs -- alluredir./report        # 执行测试用例的报告都会放在这个目录下面

##如果单个函数运行,会在当前目录下生成一个report文件

##还可以通过命令行运行 pytest  testcase/test_case1.py  终端执行时会在根目录生成report文件(pytest.ini中配置的路径)

##report文件下包含:

attachment.txt    日志输出

container.json     测试用例前后操作,执行时间,结束时间

result.json   本条测试用例的执行结果


ps:在线json校验格式化工具: bejson.com

3)打开报告

终端 输入allure,显示allure帮助文档

①allure serve ./report   自动打开报告  # 也可以使用绝对路径

allure generate report     生成报告(allure-report文件在根目录下) 

   allure open  allure-report  跟②结合使用

allure generate report -o allure-report1  (通过-o  自定义报告名称


八,Jenkins配置

Jenkins创建项目

打开Jenkins

(1)安装allure插件

主页--系统管理--插件管理(plugin manager)-- 可选插件--输入allure,不用回车,自动出现,勾选安装

主页--系统管理--全局工具配置--配置Allure Commandline--新增Allure Commandline--输入别名 allure,勾选自动安装,版本选择2.18.1--应用,保存

(2)新建一个freestyle项目

主页--create a job --  任务名称自定义,选择第一个(自由风格的软件项目)--

①描述,

②勾选丢弃旧的构建,保持构建天数:5,保持构建最大个数:5,

③增加源码,

源码管理 :repository url:git项目中克隆/下载,https,复制地址;

添加凭据:username with password  ,输入用户名,密码(git登录用账号);

分支:*/master;

定时构建:日程表:*9***(每天早上9点运行);

构建环境:勾选 delete workspace before build starts

构建:执行shell         

#!/bin/bash  

cd $ {WORKSPACE}   

pip3 install -r requirements.txt -- user

pytest  #如果需要指定用例目录 加上用例path

构建后操作:

path:report  #pytest.ini中定义的

点击应用,保存

之后就可以使用,点击构建

可以点击allure report 查看报告


第十一章 自动化测试 Pytest的评论 (共 条)

分享到微博请遵守国家法律