51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 3608|回复: 0
打印 上一主题 下一主题

[原创] Python 接口测试实践之用例封装及测试报告生成

[复制链接]
  • TA的每日心情
    无聊
    昨天 09:07
  • 签到天数: 1020 天

    连续签到: 1 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2020-11-11 09:31:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    今天以天气API接口为例,使用python语言实现用例编写、封装及报告生成功能  API信息:
      天气API:http://www.51testing.com/html/88/n-4465288.html
      URL:http://t.weather.sojson.com/api/weather/city/101030100
      请求方式:get
      参数:city 城市名称
      一 、代码实现查询北京的天气信息
      步骤:
      1、新建 weather_api_test.py文件
      代码实现
    1. #-*-coding:GBK -*-

    2.   import requests

    3.   from pip._vendor.requests.models import Response

    4.   url='http://t.weather.sojson.com/api/weather/city/101030100'

    5.   r=requests.get(url)

    6.   response_data=r.json()

    7.   print(r.text)
    复制代码
    二、用例集成到Unittest
      1、针对不同的参数场景进行测试
      2、设置断言判断执行结果是否符合预期
      实现原理:
      首先导入requests 库、unitest 、时间库
      其次,创建天气class类
      然后,分别创建4个函数,分别实现存放路径、正常传参、异常传参、缺省参数功能
      3、用例设计

    代码实现:
       新建 weather_api_unitest.py文件

    1. #-*-coding:GBK -*-

    2. import unittest

    3. import requests

    4. from time import sleep

    5. class weathertest(unittest.TestCase):

    6.     def setUp(self):

    7.         self.url='http://t.weather.sojson.com/api/weather/city/101030100'

    8.         self.url_error='http://t.weather.sojson.com/api/weather/city/101030101'

    9.         self.url_no='http://t.weather.sojson.com/api/weather/city'

    10.     #参数正常

    11.     def test_weather_tianjing(self):

    12.         r=requests.get(self.url)

    13.         result=r.json()

    14.         self.assertEqual(result['status'],200)

    15.         self.assertEqual(result['message'],'success感谢又拍云(upyun.com)提供CDN赞助')

    16.         sleep(3)

    17.     #参数异常

    18.     def test_weather_param_error(self):

    19.         r=requests.get(self.url_error)

    20.         result=r.json()

    21.         self.assertEqual(result['status'],400)

    22.         self.assertEqual(result['message'],'获取失败')

    23.         sleep(3)

    24.     #参数缺省

    25.     def test_weather_no_param(self):

    26.         r=requests.get(self.url_no)

    27.         result=r.json()

    28.         self.assertEqual(result['status'],404)

    29.         self.assertEqual(result['message'],'Request resource not found.')

    30.         sleep(3)              

    31.     if __name__=='_main_':

    32.         unittest.main()
    复制代码




    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-9-19 06:31 , Processed in 0.060365 second(s), 25 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表