当前位置:   article > 正文

编写http接口api及接口自动化测试

编写http接口api及接口自动化测试

片言

此文中代码都是笔者工作中源码,所以不会很完整,主要摘常见场景的api片段用以举例说明

另:此文主要针对自动化测试人员,尤其有python基础阅读更佳。

笔者使用 python3.6 + postgresql10 + flask 0.12 的环境

场景介绍 

我们要实现后台管理中的用户管理功能,实现对用户的增、修改、删除、查询操作。

文中场景省去登录和用户权限部分,但我会在接口代码片段中进行注释说明

接口:新增用户

(定义访问的http链接地址,以及请求使用的 method)    http://127.0.0.1:7070/guardian/users

  1. @app.route('/guardian/users', methods=['POST']) # 使用 POST 方法
  2. @require_role('guardian_admin') # 登录用户的角色权限必须是guardian_admin 此处是自定义的更角色管理中的设置管理员角色一致即可。不需要角色权限也可以注释此行即可
  3. @login_required # 验证用户登录 flask_login插件
  4. def create_user():
  5. '''
  6. 下面json串是新增时候前台表单提交的内容以及格式,也就是我们接口测试时候需要添加的测试数据
  7. {
  8. "user": {
  9. "domain_id": "default",
  10. "enabled": True,
  11. "name": "tsbc1",
  12. "password": "111111",
  13. "realname": "Ray",
  14. "email": "tsbc@vip.qq.com",
  15. "tel": "+86-029-88880000",
  16. "phone": "13800138000",
  17. "org_id": "7d22d25a-b648-4ad3-a834-2398eb989a9e",
  18. "org_array":[],
  19. "comments": "备注信息"
  20. }
  21. }
  22. '''
  23. try:
  24. domain_id = None
  25. user_name = None
  26. user_passwd = None
  27. project_id = None
  28. real_name = None
  29. email = None
  30. phone = None
  31. org_id = None
  32. org_array = None
  33. comments = None
  34. try:
  35. # 接收前端请求数据,并使用json.loads 把数据转换成Python可以读格式
  36. resq_obj = request.data
  37. resq_json = None
  38. if type(resq_obj) is bytes:
  39. resq_json = resq_obj.decode()
  40. else:
  41. resq_json = resq_obj
  42. user_obj = jsonpickle.loads(resq_json) # 此处使用了jsonpickle的lib,使用json lib也是一样的
  43. logging.debug('create user {0} '.format(user_obj))
  44. if 'default_project_id' in user_obj['user']:
  45. project_id = user_obj['user']['default_project_id']
  46. domain_id = user_obj['user']['domain_id']
  47. user_name = user_obj['user']['name']
  48. user_passwd = user_obj['user']['password']
  49. except Exception as ee:
  50. abort(400)
  51. #raise ee
  52. if domain_id is not None and user_name is not None and user_passwd is not None:
  53. # 笔者使用 keystone 进行用户管理 此处在keystone创建帐号,然后获取id,把id及其它信息会存放在自定义的数据库表中
  54. resp = usermgt.create_user(domain_id, user_name, user_passwd, project_id) # resp返回值是 dict 格式
  55. if 'id' in resp['user']:
  56. try:
  57. # 把前端POST的表单值进行变量赋值 传给后台进行存库
  58. user_id = resp['user']['id']
  59. if 'realname' in user_obj['user']:
  60. real_name = user_obj['user']['realname']
  61. if 'email' in user_obj['user']:
  62. email = user_obj['user']['email']
  63. if 'tel' in user_obj['user']:
  64. tel = user_obj['user']['tel']
  65. if 'phone' in user_obj['user']:
  66. phone = user_obj['user']['phone']
  67. if 'org_id' in user_obj['user']:
  68. org_id = user_obj['user']['org_id']
  69. if 'org_array' in user_obj['user']:
  70. org_array = user_obj['user']['org_array']
  71. if 'comments' in user_obj['user']:
  72. comments = user_obj['user']['comments']
  73. except Exception as e:
  74. # raise e
  75. abort(400)
  76. if user_obj is not None:
  77. try:
  78. # 调用方法进行后台存库
  79. GuardianModelDao._save_update_users_info(user_id, user_name, real_name, email, tel, phone, org_id, org_array, comments)
  80. return wrap_response(SUCCESS_MSG, 200) # 执行成功 返回操作成功信息及状态码 200
  81. except Exception as e:
  82. LOG.debug(e)
  83. abort(500) # 否则 后台500 错误
  84. else:
  85. abort(500)
后台函数

用于实现对接口中传递数据进行处理入库、修改、查询等等。

  1. @classmethod
  2. def _save_update_users_info(cls, user_id, username, real_name, email, tel, phone, org_id, org_array, comments):
  3. LOG.debug('start create users info...')
  4. try:
  5. with TxConn() as conn: # 连接数据库
  6. with conn.cursor() as cursor:
  7. # save user data
  8. now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  9. # 接收变量赋值 user_data
  10. users_data = {
  11. "user_id":user_id,
  12. "username":username,
  13. "realname":real_name,
  14. "email":email,
  15. "tel":tel,
  16. "phone":phone,
  17. "org":org_id,
  18. "org_array":org_array,
  19. "comments":comments,
  20. "now_time":now_time
  21. }
  22. cursor.execute(cls.insert_users_info, users_data) # 插入数据
  23. conn.commit()
  24. except Exception as e:
  25. LOG.exception('error saving users info', e)
  26. raise e
测试脚本(新增用户)

python unittest做单元测试

  1. import unittest, requests
  2. class GuardianTestCase(unittest.TestCase):
  3. guardian_base = 'http://127.0.0.1:7070'
  4. user_token = keystone.user_token('default', 'tsbc', '123456') # 调用keystone生成登录用户的token
  5. def test_create_user_api(self):
  6. # 添加对应headers 及 tonken 用于数据传参和登录认证使用
  7. myheaders = {'Content-Type': 'application/json'}
  8. myheaders['X-Subject-Token'] = self.user_token
  9. # 接口测试数据
  10. user = {
  11. "user": {
  12. "domain_id": "default",
  13. "enabled": True,
  14. "name": "tsbc1",
  15. "password": "123456",
  16. "realname": "Ray",
  17. "email": "tsbc@123.com",
  18. "tel":"+86-029-88880000",
  19. "phone": "13800138000",
  20. "org_id": "7d22d25a-b648-4ad3-a834-2398eb989a9e",
  21. "org_array":None,
  22. "comments": "备注信息"
  23. }
  24. }
  25. # 使用requests的post方法进行请求路由
  26. _resp = requests.post(self.guardian_base + '/guardian/users', json=user, headers=myheaders, verify=True)
  27. resp_json = _resp.content
  28. # 对返回结果及状态进行校验
  29. if _resp.ok:
  30. self.assertIsNotNone(resp_json)
  31. LOG.info('create users, response: {0}'.format(resp_json))
  32. else:
  33. LOG.error('error create users, response: {0}, status: {1}'.format(resp_json, _resp.status_code))
接口:修改用户

修改用户和新增用户传递的参数差不多,使用的是http的patch请求,route要添加user_id的参数 ,其他实现和新增差不多代码不重复贴了

  1. @app.route('/guardian/users/<string:user_id>', methods=['PATCH'])
  2. @require_role('guardian_admin')
  3. @login_required
  4. def update_user(user_id):
  5. """
  6. 此处省略接收请求数据代码
  7. """
  8. try:
  9. resp = usermgt.update_user(domain_id, user_id, username, user_passwd, project_id, enabled) # 更新keystone 用户密码、状态
  10. if resp is not None:
  11. # 更新用户基本信息与新增是同一个接口,执行SQL时使用PostGresql特性,相同user_id数据只更新不会再插入
  12. GuardianModelDao._save_update_users_info(user_id, username, real_name, email, tel, phone, org_id, org_array, comments)
  13. return wrap_response(SUCCESS_MSG, 200) # 更新成功返回 200
  14. except Exception as e:
  15. LOG.exception('error modify user', e)
  16. abort(500) # 更新失败500

测试脚本(修改用户)

  1. def test_update_user_api(self):
  2. myheaders = {'Content-Type': 'application/json'}
  3. myheaders['X-Subject-Token'] = self.user_token
  4. user = {
  5. "user": {
  6. "domain_id": "default",
  7. "enabled": True,
  8. "name": "tsbc1",
  9. "password": "111111",
  10. "realname": "xioohua",
  11. "email": "haoydun@123.com",
  12. "tel": "+86-029-88880000",
  13. "phone": "13800138000",
  14. "org_id": "7d22d25a-b648-4ad3-a834-2398eb989a9e",
  15. "comments": "备注信息"
  16. }
  17. }
  18. _resp = requests.patch(self.guardian_base + '/guardian/users/0d26176579e94d558c4c2d864b003241', # 路由中添加要修改的用户ID requests使用 patch方法
  19. json=user, headers=myheaders, verify=True)
  20. resp_json = _resp.content
  21. # 返回值进行校验
  22. if _resp.ok:
  23. self.assertIsNotNone(resp_json)
  24. LOG.info('update users, response: {0}'.format(resp_json))
  25. else:
  26. LOG.error('error update users, response: {0}, status: {1}'.format(resp_json, _resp.status_code))
接口:查询用户

根据用户名查询用户,使用http的get请求

  1. @app.route('/guardian/users/<string:user_name>', methods=['GET']) # 查询使用 GET 方法
  2. @require_role('guardian_admin')
  3. @login_required
  4. def query_user_by_username(user_name):
  5. try:
  6. user_info = GuardianModelDao._query_users_info_by_name(user_name) # 调用后台查询函数
  7. if len(user_info):
  8. return wrap_response(jsonpickle.dumps(user_info), 200) # 成功返回200 并把返回内容转换成 json格式
  9. else:
  10. return wrap_response("[]", 200) # 否则返回空
  11. except Exception as e:
  12. LOG.exception('error query user by name', e)
  13. abort(500)
后台函数
  1. @classmethod
  2. def _query_users_info_by_id(cls, user_id):
  3. LOG.debug('start list users info...')
  4. users = []
  5. with TxConn() as conn:
  6. try:
  7. with conn.cursor() as cursor:
  8. data = (user_id,)
  9. cursor.execute(cls.query_users_info_by_id, data)
  10. # 查询结构如果是行数据,放进list中进行返回
  11. for (user_id, real_name, email, tel, phone, org_id, org_array, comments, create_time, update_time) in cursor:
  12. user = Users(user_id, real_name, email, tel, phone, org_id, org_array, comments, create_time, update_time)
  13. users.append(user)
  14. except Exception as e:
  15. LOG.exception('error query users !')
  16. raise e
  17. return users

测试脚本(查询用户)

  1. def test_query_user_api(self):
  2. myheaders = {'Content-Type': 'application/json'}
  3. myheaders['X-Subject-Token'] = self.user_token
  4. _resp = requests.get(self.guardian_base + '/guardian/users/tsbc', headers=myheaders, verify=True) # 链接中加入用户名
  5. resp_json = _resp.text
  6. # 验证判断
  7. if _resp.ok:
  8. self.assertIsNotNone(resp_json)
  9. LOG.info('query users, response: {0}'.format(resp_json))
  10. else:
  11. LOG.error('error query users, response: {0}, status: {1}'.format(resp_json, _resp.status_code))
接口:删除用户

根据用户ID进行删除,使用http的delete请求

  1. @app.route('/guardian/users/<string:user_id>', methods=['DELETE']) # 传入用户id 使用 delete请求
  2. @require_role('guardian_admin')
  3. @login_required
  4. def delete_user(user_id):
  5. if user_id is None:
  6. abort(400)
  7. try:
  8. s_code = usermgt.delete_user(user_id)
  9. if s_code == 204:
  10. return wrap_response(SUCCESS_MSG, status=s_code) # 返回状态码
  11. except Exception as e:
  12. LOG.exception('error delete users info', e)
  13. abort(500)

后台函数

  1. def delete_user(user_id):
  2. myheaders = {'Content-Type': 'application/json'}
  3. myheaders['X-Auth-Token'] = settings.KEYSTONE_ADMIN_TOKEN
  4. _resp = requests.delete(settings.KEYSTONE_BASE + '/v3/users/'+user_id,
  5. headers=myheaders, verify=False)
  6. if _resp.status_code == 204:
  7. LOG.debug('delete users -- response {0}'.format(_resp))
  8. return _resp.status_code
  9. else:
  10. LOG.error('error list users, response: {0}'.format(_resp))
  11. raise KeystoneException('error delete user {0} with response status {1}'
  12. .format(user_id, _resp.status_code), _resp.status_code)

测试脚本(删除用户)

  1. def test_delete_users_api(self):
  2. myheaders = {'Content-Type': 'application/json'}
  3. myheaders['X-Subject-Token'] = self.user_token
  4. _resp = requests.delete(self.guardian_base + '/guardian/users/tsbc1', headers=myheaders, # 使用 delete 请求
  5. verify=True)
  6. resp_json = _resp.content
  7. # 根据返回状态进行校验
  8. if _resp.ok:
  9. self.assertIsNotNone(resp_json)
  10. LOG.info('delete users api, response: {0}'.format(resp_json))
  11. else:
  12. LOG.error('error delete users api, response: {0}, status: {1}'.format(resp_json, _resp.status_code))
下面提供给前端API文档
## CREATE USER

1. URL:' /guardian/users'

2. METHOD: POST

3. body:

  1. {
  2. "user": {
  3. "domain_id": "default",
  4. "enabled": True,
  5. "name": "tsbc1",
  6. "password": "111111",
  7. "realname": "Ray",
  8. "email": "haoydun@123.com",
  9. "tel":"+86-029-88880000",
  10. "phone": "13800138000",
  11. "org_id": "7d22d25a-b648-4ad3-a834-2398eb989a9e",
  12. "org_array": null,
  13. "comments": "备注信息"
  14. }
  15. }
##  UPDATE USER

1. URL:' /guardian/users/<string:user_id>'

2. METHOD: PATCH2. body:

  1. {
  2. "user": {
  3. "domain_id": "default",
  4. "enabled": True,
  5. "name": "tsbc1",
  6. "password": "111111",
  7. "realname": "Ray",
  8. "email": "tsbc@vip.qq.com",
  9. "tel":"+86-029-88880000",
  10. "phone": "13800138000",
  11. "org_id": "7d22d25a-b648-4ad3-a834-2398eb989a9e",
  12. "org_array": null,
  13. "comments": "备注信息"
  14. }
  15. }

该接口可以用于修改密码,禁用用户

## QUERY USER BY NAME

1. URL:' /guardian/users/<string:user_name>'

2. METHOD: GET

## DELETE USER

1. URL: '/guardian/users/<string:user_id>'

2. METHOD: DELETE

行动吧,在路上总比一直观望的要好,未来的你肯定会感 谢现在拼搏的自己!如果想学习提升找不到资料,没人答疑解惑时,请及时加入扣群: 320231853,里面有各种软件测试+开发资料和技术可以一起交流学习哦。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/433815
推荐阅读
相关标签
  

闽ICP备14008679号