首页 > 其他分享 >Pytest接口测试框架实战项目搭建(三)—— 统一登录处理

Pytest接口测试框架实战项目搭建(三)—— 统一登录处理

时间:2022-11-12 19:12:56浏览次数:44  
标签:get self 接口 headers json Pytest env login 搭建

一、前言

  业务系统的登录均要经过统一登录系统S,本篇演示2个业务系统的登录,一个是内部业务系统C,一个是外部用户使用的系统W,因为账号密码以及headers信息都不一样,所以要分开处理登录。这里要先贴一下请求要用到的数据。

1、conf/config.ini

[ENV]
env = QA1

[QA1]
y_api_url = https://qa1-api.y.cn
s_api_url = https://qa-s-xxx.cn

[QA2]
y_api_url = https://qa1-api.y.cn
s_api_url = https://qa-s-xxx.cn

2、data/userInfo.yaml

QA1:
  s_login_info:
    loginFromServer: 'https://qa-xxx.cn/#/'
    loginFromSystemCode: S
    #passwordVersion: 1 #去掉该参数,password传输可不加密
    username: zhangsan
    password: 1231234
    verification:

  w_login_info:
    loginFromServer: 'https://qa-xxx.cn/#/'
    loginFromSystemCode: S
    #passwordVersion: 1 #去掉该参数,password传输可不加密
    username: lisi
    password: 123456
    verification:

QA2:
  s_login_info:
    loginFromServer: 'https://qa-xxx.cn/#/'
    loginFromSystemCode: S
    #passwordVersion: 1 #去掉该参数,password传输可不加密
    username: zhangsan111
    password: 1231234
    verification:

  w_login_info:
    loginFromServer: 'https://qa-xxx.cn/#/'
    loginFromSystemCode: S
    #passwordVersion: 1 #去掉该参数,password传输可不加密
    username: lisi222
    password: 123456
    verification:

3、data/headers.json

{
  "QA1": {
    "s_login_headers": {
      "Content-Type": "application/x-www-form-urlencoded",
      "Accept": "application/json, text/plain, */*"
    },
    "s_headers": {
      "Content-Type": "application/json;charset=UTF-8",
      "Accept": "application/json, text/plain, */*",
      "sToken": ""
    },
    "w_headers": {
      "T-Id": "1095",
      "System-Code": "w",
      "Content-Type": "application/json;charset=UTF-8",
      "Accept": "application/json, text/plain, */*",
      "sToken": ""
    }
  },
  "QA2": {
    "s_login_headers": {
      "Content-Type": "application/x-www-form-urlencoded",
      "Accept": "application/json, text/plain, */*"
    }
   
  }
}

 4、conf/api_path.py

# -*- coding:utf-8 -*-
'''
@Date:2022/10/3  20:56
@Author:一加一
'''

from tools.operate_config import OperateConfig
from urllib.parse import urljoin

class ApiPath:

    '''管理api地址'''

    def __init__(self,env=None):
        if env is None:
            self.env = OperateConfig().get_node_value('ENV', 'env')
        else:
            self.env = env
        self.y_api_url = OperateConfig().get_node_value(self.env,'y_api_url') #读取配置文件config.ini 的接口域名
        self.s_api_url = OperateConfig().get_node_value(self.env, 's_api_url') #读取配置文件config.ini 的s系统接口域名

        # s系统 api
        self.s_login_url = urljoin(self.s_api_url, "/saas-xxx/login") #登录
        self.s_exchangeToken_url = urljoin(self.sso_api_url, "/saas-xxx/exchangeToken") #生成sToken
        self.employee_paging_list = urljoin(self.s_api_url,"/saas-xxx/list") #查询员工列表获取companyId

二、封装方法:获取JSON

  要登录的话肯定要涉及接口请求了,所以这里首先封装下读取json文件的方法,具体如下。

1、tools/get_userjson.py

  tools文件夹下新建get_userjson.py文件,源码如下:

  • get_yaml主要用于读取data/userInfo.yaml里的用户信息
  • OperateConfig主要读取config.ini里的域名地址
from tools.operate_config import get_yaml,OperateConfig

class GetuserJson:

    def __init__(self, env=None):
        if env is None:
            env = OperateConfig().get_node_value('ENV', 'env')
        self.env = env
        self.user_info = get_yaml(self.env)

    # 统一登录系统s 登陆的用户信息
    def  get_s_login_info(self):
        s_login_info = self.user_info['s_login_info']
        return s_login_info

    # 业务系统W 登陆的用户信息
    def  get_w_login_info(self):
        w_login_info = self.user_info['w_login_info']
        return w_login_info

2、tools/get_headerjson.py

  tools文件夹下新建get_headerjson.py文件,源码如下:

  • get_s_login_headers,获取headers.json里名为"s_login_headers”的json串
  • get_s_headers,获取headers.json里名为"s_headers”的json串
  • set_s_headers,往json文件里set字段值
# -*- coding:utf-8 -*-
from conf.setting import CASE_DATA_PATH
from tools.operate_json import OperationJson
import os
from tools.operate_config import get_yaml,OperateConfig

class GetHeaderjson:

    def __init__(self,env=None):
        if env is not None:
            self.env = env
        else:
            self.env = OperateConfig().get_node_value('ENV', 'env')
        self.headers_json = os.path.join(CASE_DATA_PATH, "headers.json")

    def get_s_login_headers(self):
        return OperationJson(self.headers_json).key_get_data(self.env,"s_login_headers")
    def get_s_headers(self):
        return OperationJson(self.headers_json).key_get_data(self.env,"s_headers")
    def set_s_headers(self,stoken):
        OperationJson(self.headers_json).write_datas(stoken,self.env, "s_headers", "sToken")def get_w_headers(self):
        return OperationJson(self.headers_json).key_get_data(self.env, "w_headers")
    def set_w_headers(self,stoken):
        OperationJson(self.headers_json).write_datas(stoken,self.env, "w_headers", "sToken")
    def set_w_headers_companyId(self,companyId):
        OperationJson(self.headers_json).write_datas(companyId,self.env, "w_headers", "T-Id")

三、统一登录处理conftest.py

1、conftest.py源码如下

  conftest文件之前的博客有讲过,常用来处理用例的前置条件,文件名称是pytest框架写死的,即是在执行用例前框架会先执行一次conftest.py的代码

'''
@Date:2022/10/2  14:22
@Author:一加一
'''

import pytest
from tools.common import *
from tools.get_headerjson import GetHeaderjson
from conf.api_path import ApiPath
from tools.get_userjson import GetuserJson
from tools.get_wjson import *
'''处理登录:统一登录S、业务系统登录W'''

# 实例化对象
api_path = ApiPath()
get_header = GetHeaderjson(None)
get_userinfo = GetuserJson(None)
get_wjson = GetwJson(None)


@pytest.fixture(scope="session",autouse=True)
def test_s_login():
    # s登录:用户名密码登录
    url = api_path.s_login_url #调用api_path方法获取url
    headers = get_header.get_s_login_headers() #调用get_header获取s系统接口请求头
    data = get_userinfo.get_s_login_info() #调用get_userinfo获取入参
    res_json = Common.r_post_form(url=url, headers=headers, data=data)
    # 获取code
    code = res_json['data'].split('?')[-1]

    # 生成stoken
    res_json = Common.r_post_form(url=api_path.s_exchangeToken_url,headers=get_header.get_s_login_headers(),data=code)
    # 将生成的sToken写入headers.json文件
    get_header.set_c_headers(res_json['data']['sToken'])
    get_header.set_p_headers(res_json['data']['sToken'])

@pytest.fixture(scope="session",autouse=True)
def test_w_login():
    # s登录:用户名密码登录
    url = api_path.s_login_url #调用api_path方法获取url
    headers = get_header.get_s_login_headers() #调用get_header获取s请求头
    data = get_userinfo.get_w_login_info() #调用get_userinfo获取入参
    res_json = Common.r_post_form(url=url, headers=headers, data=data)
    # 获取code
    code = res_json['data'].split('?')[-1]

    # 生成stoken
    res_json = Common.r_post_form(url=api_path.s_exchangeToken_url,headers=get_header.get_s_login_headers(),data=code)
    # 将生成的sToken写入headers.json文件
    get_header.set_w_headers(res_json['data']['sToken'])
    get_header.set_s_headers(res_json['data']['sToken'])

    # 查询s系统员工列表获取T-id写入headers.json文件的T-Id
    res_json = Common.r_s_post(url=api_path.employee_paging_list,
                             headers=get_header.get_s_headers(),
                             json=get_wjson.get_w_companyId())
    # 将响应结果转换成json格式
    rep_json = res_json.json()
    # 断言
    Common.assert_s_code_message(rep_json)
    # 将生成的companyId写入headers.json文件(w_headers对应的T-Id)
    TenantId = str(rep_json['data']['pageData'][0]['companyId'])
    get_header.set_w_headers_companyId(TenantId)

四、新建测试用例 testcase/test_case.py

  主要用于调试执行用例前是否会先处理conftest.py代码,以及调试conftest.py的登录代码

'''
@Date:2022/11/12  13:35
@Author:一加一
'''

import allure

@allure.feature("测试业务")
@allure.story("测试订单")
class TestCase:
    @allure.title("case1:获取列表")
    def test_case1(self):
        with allure.step("step1:获取列表"):
            print("测试第一步")
        with allure.step("step2:获取响应结果"):
            print("测试第二步")

 五、执行test_case.py文件后,生成的日志如下

  

 

标签:get,self,接口,headers,json,Pytest,env,login,搭建
From: https://www.cnblogs.com/Chilam007/p/16882671.html

相关文章

  • ubuntu搭建sftp服务
    sftp直接使用系统的sshd服务,无需额外安装软件,配置也比较简单。一、添加用户添加一个sftp用户,不设置家目录,指定不能登录的shell,然后设置登录密码useradd-M-s/sbin/n......
  • 如何使用vite搭建vue3项目详解
    目录一:npm构建二:更改http://localhost:3000/到8080与Network路由访问三:配置vite别名(npminstall@types/node--save-dev)四:路由(npminstallvue-router@4)五:vuex(n......
  • 1.PHP Study搭建Dvwa,Pikachu,Sqli环境
    原文链接:​​https://blog.csdn.net/qq_43360657/article/details/127819241?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%......
  • 元进网络自动化(3)---Python自动给路由器配置接口IP
    利用Python自动登录到网络设备,根据回显不同来配置不同的参数,避免简单重复的劳动,提高网络相关工作的效率。【网络拓扑】【打印登录配置过程】H:\Alphism\venv\Scripts\python......
  • 使用vue 搭建猫眼后台演员列表
    首先创建一个DirectorList.vue js部分 ......
  • 深度学习环境搭建
    深度学习环境配置注意--pycharm+anaconda+torchanaconda是python的一个大的发行版,里面有很多python相关的包,若要进行深度学习环境搭建,必须要下载它和pycharm联合使......
  • 项目搭建-react-app
    项目搭建-react-app点击查看代码项目搭建1、使用脚手架create-react-app初始化项目2、进入到项目根目录并使用npmstart安装3、安装antd-mobile组件4、导入......
  • 元进网络自动化(2)---搭建Python和eNSP互联环境
    1.使用eSNP里面的cloud让Python能通过telnet访问到eNSP里的网络设备。经过诸多失败,就Npcap和GE加Hub能同时使用,VM那个不行!2.配置Router1和Router2能被telnet访问。interface......
  • 【Java复健指南12】OOP高级03-抽象类与接口
    抽象类引出问题:​ 父类方法有时候具有不确定性小结:当父类的某些方法,需要声明,但是又不确定如何实现时,可以将其声明为抽象方法,那么这个类就是抽象类例子:publicclas......
  • 电影推荐系统项目实战:环境配置与搭建-----Linux环境下GIT、 Azkaban的安装与环境配置
    1.安装Git  2.通过git下载Azkaban源代码  3.切换到3.36版本  4.安装编译环境sudoyuminstallgccsudoyuminstall-ygcc-c++*  ./gr......