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

在注册接口测试中,经过会遇到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条件后。适用于在测试完需要清理数据和实时删除的场景。

 

posted @ 2022-04-10 18:21  夏大帅  阅读(67)  评论(0编辑  收藏  举报