ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

pytest-如何实现注册接口不出现数据已存在的现象

2022-04-10 18:33:35  阅读:216  来源: 互联网

标签:username 删除 fixture request 接口 pytest 注册 delete


在注册接口测试中,经过会遇到xxx已注册的现象。在接口请求和参数化的时候如何解决这个问题?

方法1、给唯一参数添加时间戳,避免重复注册的现象

  导入time模块,生成一个时间戳,在注册时加入到唯一参数后面

import time

import requests


def register_user(username, password, email):
    url = "http://xxx:xxx"
    body = {
        "username": username,
        "password": password,
        "email": email
    }
    r = requests.post(url, json=body)
    return r


if __name__ == '__main__':
    a = time.time()
    r = register_user(username='test_xds{}'.format(int(a)), password='1234577', email='13445@qq.com')
    print(r.text)

多次添加,都不会重复

 

 方法2、连接数据库,通过fixture的方式,将已存在的数据删除

  连接数据库         --- python如何连接数据库

  写一个删除的fixture  --- fixture只能在测试用例中用到。注意:普通的python函数无法调用fixture

import pytest


@pytest.fixture(scope='function')
def delete_userid():
    yield
    result = ConnectDb(db_info, database='apps')
    sql = 'delete from auth_user where username = "test_xds";'
    response = result.execute(sql)
    print("打印返回的信息:%s" % response)
    return response

 ---删除fixture的是在注册接口执行之后删除username = 'test_xds'的这条数据。多次执行接口后也不会出现已注册的现象:

      从图中用例执行时打印出注册的username固定为test_xds。fixture打印的信息为None,因为在执行delete语句后是没返回结果的

 数据库中查询test_xds这条数据也是为空的

方法2的整体思路:连接数据库,通过fixture来删除数据库中的某条数据。如果数据在注册前就存在,那么就使用前置。如果数据在注册前不存在,就使用后置yield。该方法只能指定一条数据来进行操作,不是动态删除

方法3、通过pytest内置request fixture动态删除注册接口的注册数据。通过request.config来获取上下文的信息,将注册时的username传入request.config下。在动态删除的fixture下,定义一个变量来接收request.config下的username。在执行delet语句时,在where条件后直接指定需要删除的username=username变量即可。

import pytest


@pytest.fixture(scope='function')
def delete_request_username(request):
    yield
    result = ConnectDb(db_info, database='apps')
    username = request.config.username
    sql = 'delete from auth_user where username = "{}";'.format(username)
    response = result.execute(sql)
    print("打印动态删除的delete语句:{}".format(response))
    return response

---测试。(此时注册接口是采用➕时间戳的方式)

 数据库中查询username='test_xds1649585335'的数据,查询出来是为空的。

 方法3的整体思路:通过pytest内置fixture request来获取上下文,把注册时的username传入request.config下。在写删除fixture的时候,直接取出username,传入delete语句where条件后。适用于在测试完需要清理数据和实时删除的场景。

 

标签:username,删除,fixture,request,接口,pytest,注册,delete
来源: https://www.cnblogs.com/xdsa/p/16124728.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有