Python3+Pytest 接口自动化测试全方案设计与开发-No.2接口自动化框架编写-6-结果断言

1、常用断言

  • 介绍     
    • 断言是自动化最终的目的,一个用例没有断言,就失去了自动化测试的意义
    • 断言用到的是assert关键字
    • 预期的结果是实际结果做对比
判断XX为真         assert xx
判断XX不为真

assert not xx

判断b包含a assert a in b
判断a等于b assert a == b
判断a不等于b assert a != b
# -*- coding: utf-8 -*- 
# @Time : 2021/12/10 9:22 
# @Author : jeffky
# @File : pytest_assert.py

# 判断xx为真
# 定义方法进行assert
import pytest as pytest

def test_1():
    a = True
    assert a

# 判断XX不为真
def test_2():
    a = True
    assert not a
# 判断b包含a
def test_3():
    a = 'a'
    b = 'abcd'
    assert a in b
# 判断a等于b
def test_4():
    a = 'a'
    b = 'a'
    assert a == b
# 判断a不等于b
def test_5():
    a = 'a'
    b = 'a'
    assert a != b


# 运行查看结果
if __name__ == '__main__':
    pytest.main(["-s","pytest_assert.py"])





============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: E:\2021code\Jeffky_InterAutoTest, configfile: pytest.ini
plugins: html-3.1.1, metadata-1.11.0, rerunfailures-10.2
collected 5 items

pytest_assert.py .F..F

================================== FAILURES ===================================
___________________________________ test_2 ____________________________________

    def test_2():
        a = True
>       assert not a
E       assert not True

pytest_assert.py:17: AssertionError
___________________________________ test_5 ____________________________________

    def test_5():
        a = 'a'
        b = 'a'
>       assert a != b
E       AssertionError: assert 'a' != 'a'

pytest_assert.py:32: AssertionError
- generated html file: file://E:\2021code\Jeffky_InterAutoTest\testcase\t_pytest\report\report.html -
=========================== short test summary info ===========================
FAILED pytest_assert.py::test_2 - assert not True
FAILED pytest_assert.py::test_5 - AssertionError: assert 'a' != 'a'
========================= 2 failed, 3 passed in 0.06s =========================

Process finished with exit code 0



2、结果断言

# -*- coding: utf-8 -*- 
# @Time : 2021/12/10 9:32 
# @Author : jeffky
# @File : AssertUtil.py
from utils.LogUtil import my_log
import json
# 1、定义封装类
class AssertUtil:
# 2、初始化数据,日志
    def __init__(self):
        self.log = my_log("AssertUtil")

# 3、code相等
    def assert_code(self,code,expected_code):
        '''
        验证返回验证码
        :param code:
        :param expected_code:
        :return:
        '''
        try:
            assert int(code) == int(expected_code)
            return True
        except:
            self.log.error("code error,code is %s,expected_code is %s"%(code,expected_code))
            raise
# 4、body相等
    def assert_body(self,body,expected_body):
        '''
        验证返回结果内容相等
        :param body:
        :param expected_body:
        :return:
        '''
        try:
            assert body == expected_body
            return True
        except:
            self.log.error("body error,body is %s,expected_body is %s"%(body,expected_body))
            raise
# 5、body包含
    def assert_in_body(self,body,expected_body):
        '''
        验证返回结果是否包含期望结果
        :param body:
        :param expected_body:
        :return:
        '''
        try:
            body = json.dumps(body)
            assert expected_body in body
            return True
        except:
            self.log.error("不包含或者body是错误的,body is %s,expected_body is %s" % (body, expected_body))
            raise

修改测试用例

from utils.AssertUtil import AssertUtil
conf_y = ConfigYaml()
url_path = conf_y .get_conf_url()
def test_login():

# 3、定义测试数据
    url = url_path+'/authorizations/'
    data = {
            "username":"python",
            "password":"12345678"
		}

# 4、发送POST请求
#     r = requests_post(url,json=data)
    request = Request()
    r = request.post(url, json=data)
# 5、输出结果
#     pprint(r)
    #验证
    #返回状态码
    code = r['code']
    AssertUtil().assert_code(code,200)
    body = r["body"]
    expected_body =  '"username": "python", "user_id": 1'
    AssertUtil().assert_in_body(body,expected_body)
    return r['body']

3、数据库结果断言

PyMysql安装及简单使用

安装

  •  pip install pymysql

简单使用

# @File : MysqlUtil.py
# 1、导入pymysql包
import pymysql
# 2、连接database
conn = pymysql.connect(
    host="211.103.136.242",
    user = "test",
    password="test123456",
    database = "meiduo",
    charset="utf8",
    port=7090
)
# 3、获取执行sql的光标对象
cursor = conn.cursor()
# 4、执行sql
sql = "select id,username,mobile,email from tb_users where username='python'"
cursor.execute(sql)
res = cursor.fetchone()
print(res)
# 5、关闭对象
cursor.close()
conn.close()


(1, 'python', '17701397029', '[email protected]')

Process finished with exit code 0

 工具类封装

# @File : MysqlUtil.py
# 1、导入pymysql包
import pymysql
from utils.LogUtil import my_log
# 1、创建封装类
class Mysql:
# 2、初始化数据,连接数据库,光标对象
    def __init__(self,host,user,password,database,charset="utf8",port=3306):
        self.log = my_log()
        self.conn = pymysql.connect(
            host=host,
            user=user,
            password=password,
            database=database,
            charset=charset,
            port=port
         )
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
# 3、创建查询、执行方法
    #查询单个
    def fetchone(self,sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        return res
    #查询多个
    def fetchall(self,sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        return res
    #执行
    def exec(self,sql):
        try:
            if self.conn and self.cursor:
                self.cursor.execute(sql)
                self.conn.commit()
        except Exception as ex:
            self.conn.rollback()
            self.log.error("Mysql执行失败")
            self.log.error(ex)
            return False
        return True


# 4、关闭对象
    def __del__(self):
        if self.cursor is not None:
            self.cursor.close()
        if self.conn is not None:
            self.conn.close()


if __name__ == '__main__':
    mysql = Mysql(
        host="211.103.136.242",
        user = "test",
        password="test123456",
        database = "meiduo",
        charset="utf8",
        port=7090
        )
    # sql = "select id,username,mobile,email from tb_users where username='python'"
    # res = mysql.fetchone(sql)
    # res = mysql.fetchall(sql)
    sql1 = "update tb_users set first_name='jeffky' where username='python'"
    res1 = mysql.exec(sql1)
    # print(res)
    print(res1)

配置文件

 Conf.py增加读取db_conf功能

# -*- coding: utf-8 -*- 
# @Time : 2021/12/8 16:19 
# @Author : jeffky
# @File : Conf.py
import os
from utils.YamlUtil import YamlReader
# 1、获取项目基本信息
#获取当前项目的绝对路径
current = os.path.abspath(__file__)
BASE_DIR = os.path.dirname(os.path.dirname(current))
#定义config目录的路径
_config_path = BASE_DIR+os.sep+"config"
#定义conf.yml文件的路径
_config_file = _config_path+os.sep+"conf.yml"
#定义db_conf.yml文件的路径
_db_config_file = _config_path+os.sep+"db_conf.yml"
#定义logs目录的路径
_log_path = BASE_DIR+os.sep+"logs"
def get_config_path():
    return _config_path
def get_config_file():
    return _config_file
def get_db_config_file():
    return _db_config_file
def get_log_path():
    return _log_path
#2、读取配置文件
#创建类
class ConfigYaml:
# 初始化yaml读取配置文件
    def __init__(self):
        self.config = YamlReader(get_config_file()).data()
        self.db_config = YamlReader(get_db_config_file()).data()
# 定义方法获取需要信息
    def get_conf_url(self):
        return self.config['BASE']['test']['url']
    def get_conf_log_level(self):
        '''
        获取日志级别
        :return:
        '''
        return self.config['BASE']['log_level']
    def get_conf_log_extension(self):
        '''
        获取日志扩展名
        :return:
        '''
        return self.config['BASE']['log_extension']
    def get_db_conf_info(self,db_alias):
        '''
        根据db_alias获取该名称下的数据库信息
        :param db_alias:
        :return:
        '''
        return self.db_config[db_alias]
if __name__ == '__main__':
    conf_read = ConfigYaml()
    # print(conf_read.get_conf_url())
    # print(conf_read.get_conf_log_level())
    # print(conf_read.get_conf_log_extension())
    print(conf_read.get_db_conf_info('db_1'))

数据库结果验证(通过数据库对比登录信息)

# @File : Test_Mail.py
# 1、导包
import json
from pprint import pprint

import pytest
import pytest_metadata.plugin

from common.Base import init_db
from utils.RequestsUtil import requests_get, requests_post, Request
from utils.AssertUtil import AssertUtil
from config.Conf import ConfigYaml

#登录
'''
登录成功
http://211.103.136.242:8064
/authorizations/
		POST
		json
		{
            "username":"python",
            "password":"12345678"
		}
		user_id': 1, 'username': 'python'
'''


import requests
# 2、定义登录方式

conf_y = ConfigYaml()
url_path = conf_y .get_conf_url()
def test_login():

# 3、定义测试数据
    url = url_path+'/authorizations/'
    data = {
            "username":"python",
            "password":"12345678"
		}

# 4、发送POST请求
#     r = requests_post(url,json=data)
    request = Request()
    r = request.post(url, json=data)
# 5、输出结果
#     pprint(r)
    #验证
    #返回状态码
    code = r['code']
    AssertUtil().assert_code(code,200)
    body = r["body"]
    expected_body =  '"username": "python", "user_id": 1'
    AssertUtil().assert_in_body(body,expected_body)

    #数据库验证
    # 1、初始化数据库对象
    conn = init_db('db_1')
    # 2、查询结果
    sql = "select id,username from tb_users where username='python'"
    res_db = conn.fetchone(sql)
    print("数据库查询结果:",res_db)
    # 3、验证
    user_id = body['user_id']
    assert user_id == res_db['id']

    return r['body']

猜你喜欢

转载自blog.csdn.net/python_jeff/article/details/121848584