• 13
  • 13
分享
  • 【python+unittest 接口自动化测试实战 】——设计测试用
  • 饭团🍙 2021-01-22 11:41:09 字数 15833 阅读 2072 收藏 13

一、unittest自动化测试结构

1.jpg

二、代码实现

1、导入需要的一些前置方法,用以获取cookie,生成测试数据等

# coding=utf-8
import sys
sys.path.append('..')

# 导入前置方法(登录接口获取cookie;通用的方法,如生成随机字符串、手机号;一些常用的参数设置等)
import PreProcessing as p
from PreProcessing import *

2、初始化 接口地址、机构、用户、数据库等

初始化要查询的数据库,参考https://blog.csdn.net/kk_gods/article/details/109054888

class AntibioticDict(p.unittest.TestCase):  # 继承unittest的TestCase类
     """
     新增抗生素字典测试
     """
     @classmethod
     def setUpClass(cls):     
            """        
            必须使用@classmethod装饰器,所有case执行的前置条件,只运行一次
            可以根据系统设计、接口特性等,进行测试前的初始化:机构ID, url, 用户ID,cookie,tooken,header等
            :return:
            """
            cls.header, cls.org_id, cls.user_id = p.header, p.org_id, p.user_id
            cls.url_test = p.base_url + '/api/'        
            # 初始化一个查询sql(根据请求参数,查询数据库是否有新增一条相同得数据),用于断言
            cls.sql = """
                              SELECT COUNT(id) AS counts
                              FROM
                                       `table1`
                              WHERE
                                        org_id = '{}'
                              AND `code` = '{}'
                              AND `name` = '{}'
                              and `is_valid` = '{}'
                              AND create_time LIKE '{}%';
                              """
            cls.db = p.readconfig.lis_db

 3、初始化请求参数

调用公共函数CommonFunc生成随机字符串、数字,参考https://blog.csdn.net/kk_gods/article/details/109053179

def setUp(self):
    """
    准备环境,执行每个测试用例的前置条件
    :return:
    """
    # is_valid = p.USE_FLAG        
    # 初始化请求参数
    self.params_test = {
          "isTrusted": True,
          "isValid": 1,
          "code": 'code' + p.CommonFunc.random_str,
          "name": 'name' + p.CommonFunc.random_strs(10),
          "inputCode": p.CommonFunc.random_strs(10),
          "enName": p.CommonFunc.random_strs(10),
          "kbMin": round(p.random.uniform(1, 10), 2),
          "kbMax": round(p.random.uniform(11, 100), 2),
          "micMin": round(p.random.uniform(1, 10), 2),
          "micMax": round(p.random.uniform(11, 100), 2),
          "remark": p.CommonFunc.random_strs(10),
          "sort": p.random.randint(1, 10),
          "orgId": self.org_id
}

4、编写测试用例

    # 测试用例命名必须以test开头
    def test_antibiotic_dict_001(self):
              """1、【新增字典】新增合法数据;预期:成功"""        
              # 发起请求
              r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test, headers=self.__class__.header)        
              # 将返回信息转换为json
              test_result = p.json.loads(r.text)
              # msg = p.CommonFunc.get_msg(test_result)
              # 调用函数,获取msg# print(r.elapsed.total_seconds())  # 接口响应时间
              
              if r.status_code == 200 and test_result['success']: # 判断http状态码和请求返回状态            
                   # 将请求参数组装到SQL中
                   sql = self.__class__.sql.format(
                   self.params_test['orgId'], self.params_test['code'], self.params_test['name'],
                   self.params_test['isValid'],
                   p.CURRENT_DATE
              )            
              # 执行SQL,获取数据库新增条数,参考https://blog.csdn.net/kk_gods/article/details/109053646
              counts = p.CommonFunc.get_counts(sql, self.db)            
              
              # 判断数据库是否新增一条数据:counts等于1,测试用例执行通过;counts不等于1,执行失败,将接口URL、参数以及查询SQL输出
              self.assertEqual(counts, 1, """
                            接口返回成功,但数据库未查询到数据
                          【URL】: {},
                          【PARAMS】: {},
                          【STATUS】: {},
                          【MSG】: {},
                          【SQL】: {}
                          """.format(r.url, self.params_test, r.status_code, msg, sql))
                          
              else:
                          self.assertTrue(
                          test_result['success'],
                          """
                          测试不通过,ERROR
                          【URL】: {},
                          【PARAMS】: {},
                          【STATUS】: {},
                          【MSG】: {}
                          """.format(r.url, self.params_test, r.status_code, msg))
               # 调用skip()装饰器跳过某个case,
               # @p.unittest.skip("Don't run this case. ") # 无条件跳过
               def test_antibiotic_dict_002(self):
                      """2、【新增字典】编码重复;预期:新增失败"""
                      r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test, headers=self.__class__.header)
                      test_result = p.json.loads(r.text)
                      msg = p.CommonFunc.get_msg(test_result)
                      if r.status_code == 200:
                                 self.assertFalse(
                                           test_result['success'],
                                           """
                                           测试不通过,未校验编码是否重复
                                           【URL】: {},
                                           【PARAMS】: {},
                                           【STATUS】: {},
                                           【MSG】: {}
                                           """.format(r.url, self.params_test, r.status_code, msg))
                       else:
                            self.assertFalse(
                                   test_result['success'],
                                   """
                                   测试不通过,ERROR
                                 【URL】: {},
                                 【PARAMS】: {},
                                 【STATUS】: {},
                                 【MSG】: {}
                                 """.format(r.url, self.params_test, r.status_code, msg))
                                 
                   # @unittest.skipIf(condition,reason) # 如果condition为true,则 skip
                   def test_antibiotic_dict_003(self):
                          """3、【新增字典】max值小于min;预期:新增失败"""
                             self.params_test.update(
                                 {
                                       "code": 'code' + p.CommonFunc.random_strs(10),
                                       "kbMin": round(p.random.uniform(11, 100), 2),
                                       "kbMax": round(p.random.uniform(1, 10), 2),
                                       "micMin": round(p.random.uniform(11, 110), 2),
                                       "micMax": round(p.random.uniform(1, 10), 2),
                                 }
                         )
                         
                         r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test, headers=self.__class__.header)
                         test_result = p.json.loads(r.text)
                         msg = p.CommonFunc.get_msg(test_result)
                         if r.status_code == 200:
                              self.assertFalse(
                                   test_result['success'],
                                        """
                                            测试不通过,未校验KB、MIC值大小关系
                                                  【URL】: {},
                                                  【PARAMS】: {},
                                                  【STATUS】: {},
                                                  【MSG】: {}
                                                  """.format(r.url, self.params_test, r.status_code, msg))
                                    
                                    else:
                                          self.assertFalse(
                                                 test_result['success'],
                                                      """
                                                      测试不通过,ERROR
                                                      【URL】: {},
                                                      【PARAMS】: {},
                                                      【STATUS】: {},
                                                      【MSG】: {}
                                                      """.format(r.url, self.params_test, r.status_code, msg))
                                                      
                    # @unittest.skipUnless(condition,reason) # 如果condition为False,则skip
                    def test_antibiotic_dict_004(self):
                           """4、【新增字典】新增不存在的状态,预期:失败"""
                           self.params_test.update(
                                {
                                         "code": 'code' + p.CommonFunc.random_strs(10),
                                         "isValid": 3
                                 
                                }
                    )
                    r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test, headers=self.__class__.header)
                    test_result = p.json.loads(r.text)
                    msg = p.CommonFunc.get_msg(test_result)
                          if r.status_code == 200:
                                 self.assertFalse(
                                         test_result['success'],
                                             """
                                             测试不通过,未校验停启用状态
                                            【URL】: {},【PARAMS】: {},
                                            【STATUS】: {},
                                            【MSG】: {}
                                            """.format(r.url, self.params_test, r.status_code, msg))
                     else:
                             self.assertFalse(
                                   test_result['success'],
                                               """
                                               测试不通过,ERROR
                                              【URL】: {},
                                              【PARAMS】: {},
                                              【STATUS】: {},
                                              【MSG】: {}
                                              """.format(r.url, self.params_test, r.status_code, msg))
                        def test_antibiotic_dict_005(self):
                               """5、【新增字典】必填字段未填写;预期:新增失败"""
                                   self.params_test.update(
                                          {
                                                "code": None
                                          }
                          )
                         r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test, headers=self.__class__.header)
                         test_result = p.json.loads(r.text)
                          msg = p.CommonFunc.get_msg(test_result)
                          if r.status_code == 200:
                              self.assertFalse(
                                     test_result['success'],
                                               """
                                               测试不通过,未校验必填字段
                                              【URL】: {},
                                              【PARAMS】: {},
                                              【STATUS】: {},
                                              【MSG】: {}
                                              """.format(r.url, self.params_test, r.status_code, msg))
                                     
                        else:
                              self.assertFalse(
                                         test_result['success'],
                                                   """
                                                   测试不通过,ERROR                                         
                                                  【URL】: {},
                                                  【PARAMS】: {},
                                                  【STATUS】: {},
                                                  【MSG】: {}
                                                  """.format(r.url, self.params_test, r.status_code, msg))
                           def test_antibiotic_dict_006(self):
                                     """6、【新增字典】字段长度超长;预期:新增失败"""
                                           self.params_test.update(
                                                  {
                                                         "code": 'code' + p.CommonFunc.random_strs(100),
                                                         "name": 'name' + p.CommonFunc.random_strs(100)
                                                  }                                                                                                                                                                                                       
                                )
                               r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test, headers=self.__class__.header)
                               test_result = p.json.loads(r.text)
                               msg = p.CommonFunc.get_msg(test_result)
                               if r.status_code == 200:
                                       self.assertFalse(
                                            test_result['success'],
                                                      '测试不通过,未校验字段长度;【URL: {}】,【PARAMS: {}】,【MSG: {}】
                                                       '.format(r.url, self.params_test, msg))
                  else:
                         self.assertFalse(
                                      test_result['success'],
                                                    """
                                                     测试不通过,ERROR
                                                      【URL】: {},
                                                      【PARAMS】: {},
                                                       【STATUS】: {},
                                                       【MSG】: {}
                                                         """.format(r.url, self.params_test, r.status_code, msg))
                  def test_antibiotic_dict_007(self):
                             """7、【新增字典】新增停用状态,预期:成功"""
                                    self.params_test.update(
                                        {
                                            "code": 'code' + p.CommonFunc.random_strs(10),
                                            "isValid": 0
                                        }
                                   )
                                   r = p.requests.request("post", url=self.__class__.url_test, json=self.params_test,
                                                           headers=self.__class__.header)
                                  test_result = p.json.loads(r.text)
                                  msg = p.CommonFunc.get_msg(test_result)
                                  if r.status_code == 200:
                                      self.assertTrue(
                                          test_result['success'],
                                          """
                                          测试不通过,未校验停启用状态
                                         【URL】: {},
                                         【PARAMS】: {},
                                         【STATUS】: {},
                                         【MSG】: {}
                                         """.format(r.url, self.params_test, r.status_code, msg))
                       else:
                               self.assertTrue(
                                    test_result['success'],
                                    """测试不通过,ERROR
                                    【URL】: {},
                                    【PARAMS】: {},
                                    【STATUS】: {},
                                    【MSG】: {}
                                    """.format(r.url, self.params_test, r.status_code, msg))    
                    def test_antibiotic_dict_007(self): 
                           """8、【新增字典】"""        
                           pass
                           
  
  • 【留下美好印记】
    赞赏支持
登录 后发表评论
+ 关注

热门文章

    最新讲堂

      • 推荐阅读
      • 换一换
          • 1.什么是接口测试?为什么要做接口测试?接口测试是测试系统组件间接口的一种测试。接口测试主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点。测试的重点是要检查数据的交换,传递和控制管理过程,以及系统间的相互逻辑依赖关系等。由于如今的系统复杂度不断上升,传统的测试方法成本急剧增加且测试效率大幅下降,所以就要做接口测试。同时,接口测试相对容易实现自动化持续集成,且相对UI自动化也比较稳定,可以减少人工回归测试人力成本与时间,缩短测试周期,支持后端快速发版需求。接口持续集成是为什么能低成本高收益的根源。现在很多系统前后端架构是分离的,从安全层面来说,只依赖前端进行限制已经完全不能满足系统的...
            13 13 1090
            分享
          •   在项目开发中,经常遇到根据给定关键字生成系统唯一顺序号的场景,本文整理了两种不同的实现方式。  1. 通过数据库加锁方式生成顺序号  该方案主要通过对数据库中表记录的加锁读写来实现的,该表中的记录对应不同关键字的顺序号生成信息,并且,为了提高生成顺序号的效率,可以一次生成指定步长个数的顺序号并存入本地缓存中。  该方案首先需要在数据库建立用于生成顺序号的表SEQUENCE_NUMBER,表结构如表1所示:表1 表结构  相应的,定义该表对应的Domain:public class SequenceNumberDomain{  private keyN...
            0 0 920
            分享
          • 写在之前Fiddler是一款非常强大的工具,不仅可以抓包,还可以用来发送请求,模拟各种场景的异常测试,精通该工具会让你的测试工作如虎添翼。一般我是在需要抓包的时候采用它,抓包是为了知道我需要往哪个请求发送什么样的参数,这种时候一般你不知道往哪个URL发送哪些参数,什么情况下你不知道呢?--当你没有跟开发人员约定好的时候,他们没有接口文档或者啥也没有。这种时候也说明一个问题:你跟开发前期的工作没有做到位,你应该在需求阶段的时候介入,进入开发阶段后你就要主动的参与到开发的应用程序设计当中,跟他们约定好这个接口应该是什么样的,具备哪些参数,把这些约定好。当然,在约定第一版的时候,这些肯定不是最终版,...
            0 0 1172
            分享
          •   据报道,为了省钱、增加收入,马斯克试图让员工购买Twitter办公室绿植。不愿透露姓名的Twitter工程师称,马斯克关注的重点主要是钱,为了省钱,马斯克已经炒掉了清洁和餐饮员工。  因为管理混乱,Twitter纽约办公室甚至出现蟑螂,马斯克无意与负责清洁卫生的员工续签合约,办公室甚至能闻到恶臭。  去年10月末马斯克收购Twitter,之后大刀阔斧改革,马斯克宣称改革是为了节省成本,防止公司破产。去年11月马斯克曾说Twitter每天亏损400多万美元。刚接管Twitter马斯克便裁员几千人,相当于员工总数的一半,而且公司不再提供免费食品。  因为一些账单未付Twitter被告上法庭,T...
            0 0 1067
            分享
          •   每次需求一出bug,不管最后追责杀到谁的头上,前边一定是产品刚在第一线。为了少出事,就在测试阶段多干活。  建议不管有多忙,产品也要在需求上线前验一遍。这样至少有两个好处:  ·少背锅。需求上线前,什么事情都比较好解决,比上线后扯皮强。  ·多露脸。部门那么大,不一定都认识,行走江湖靠朋友,各部门混个脸熟才是正道。  在不看触代码和接口,仅看功能逻辑的测试,就是黑盒测试。  那末,从产品的角度,黑盒测试该如何编写用例,才显得比较专业呢?  STEP1 改造测试的测试用例  找测试要一份测试用例文档,有些公司还会要求开测试用例评审会。  假如要不到,网上也能百度搜下来一份,然后删掉一些测试部...
            0 0 2422
            分享
      • 51testing软件测试圈微信