28、pytest实战:获取多用户鉴权

前提

测试过程中有用户体系,例如包括管理员、商家、用户角色,不同测试用例需要使用不同角色来操作,操作权限根据用户的鉴权来判断实现。

技能点

  • 建立全局变量文件,保存账号相关信息
  • 获取鉴权信息变为module级别fixture,同一module级别只请求一次鉴权

代码实现

shell 复制代码
# 目录
└─monitor_token
    │  __init__.py
    │
    ├─case
    │  │  __init__.py
    │  │
    │  └─monitor_token
    │          conftest.py
    │          test_get_token.py
    │          __init__.py
    │
    └─data
            userinfo.py

init.py全是空文件,无内容

python 复制代码
# content of conftest.py
import pytest
from monitor_token.data.userinfo import project_info

@pytest.fixture(scope='package')
def get_token():
    token_dict = {}
    get_token_url = 'http://192.168.1.40/api/cityos/sso/web/v2/user/login'
    headers = {
		'Content-Type':'application/json',
	}
    user_info = project_info['test']['user_info']
    for key, value in user_info.items():
        body = {
            'username': value[0],
            'password': value[1],
            'tenantId':'1'
        }
        # req = requests.post(url, body, headers=headers)
        token_dict[key] = 'Bearer-' + str(value[0]) + "-" + str(value[1])
    return  token_dict
python 复制代码
# content of test_get_token.py
import pytest

class TestGetToken:
    def test_get_manager_token(self, get_token):
        token = get_token['管理员']
        print('管理员token:'+token)
        assert 1
        
    def test_get_saler_token(self, get_token):
        token = get_token['商家']
        print('商家token:' + token)
        assert 1
    def test_get_cus_token(self, get_token):
        token = get_token['顾客']
        print("顾客token:" + token)
        assert 1
python 复制代码
# content of userinfo.py
import time
import sys

project_info = {
	'test':{
		'app_base_url':'http://192.168.1.50',
		'user_info':{
			'管理员':('manageuser','testpassword'),
            '商家':('saleruser','salerpassword'),
            '顾客':('cususer','cususerpassword'),
		},
		'database_info':{
			'url':'',
			'username':'',
			'password':'',
			'port':3306,
			'db_name':{
				'测试创新应用':'',
			}
		}
	},
	'prod':{
		'app_base_url':'http://192.168.1.40',
		'user_info':{
			'管理员':('testuser','testpassword'),
            '商家':('saleruser','salerpassword'),
            '顾客':('cususer','cususerpassword'),
		},
		'database_info':{
			'url':'',
			'username':'',
			'password':'',
			'port':3306,
			'db_name':{
				'生产创新应用':'',
			}
		}
	}
}

场景应用

用例文件夹下的conftest.py中实现获取token的fixture,测试用例中直接获取该fixture,并根据用户名称来使用。fixtrue设置作用域为包级,只能包内测试用例执行结束后,才会销毁,可以保证一次测试,只请求了一次token。

相关推荐
碳基沙盒1 天前
OpenClaw 多 Agent 配置实战指南
运维
Sinclair3 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
Rockbean4 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
蝎子莱莱爱打怪4 天前
Centos7中一键安装K8s集群以及Rancher安装记录
运维·后端·kubernetes
茶杯梦轩4 天前
CompletableFuture 在 项目实战 中 创建异步任务 的核心优势及使用场景
服务器·后端·面试
海天鹰5 天前
【免费】PHP主机=域名+解析+主机
服务器
DianSan_ERP5 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅5 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
不是二师兄的八戒5 天前
Linux服务器挂载OSS存储的完整实践指南
linux·运维·服务器
芝士雪豹只抽瑞克五5 天前
Nginx 高性能Web服务器笔记
服务器·nginx