• 13
  • 13
分享
  • 【python+unittest 接口自动化测试实战 】——设计测试用
  • 饭团🍙 2021-01-22 11:41:09 字数 15833 阅读 2002 收藏 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
                           
  
  • 【留下美好印记】
    赞赏支持
登录 后发表评论
+ 关注

热门文章

    最新讲堂

      • 推荐阅读
      • 换一换
          •   填测试行业问卷,不仅能获得价值398元的测试资料,还可以参与我们的抽奖活动,赶快参与一下吧。链接:http://vote.51testing.com/  测试过程  在逻辑上。测试活动是按顺序进行的.但是实际测试过程中,这些活动是可以重叠或同时进行的。(比如支付宝的加好友,登录,转账等。对于加好友模块的测试,还是需要先登录这个模块的操作的。)  1、测试策划过程  测试策划分为以下三个部分:  测试策划步骤:  1)进行测试需求的分析,确定需要测试的内容或质量特征,明确测试的充分性要求。  2)提出测试的基本方法。  测试策划需要进行:  1)确定测试的资源和技术需求。  2)进行风险分析...
            0 0 1691
            分享
          •   据彭博社报道,美国两党参议院都打消了推进TikTok“不卖就禁”法案的念头,从而降低了相关提案成为法律的可能性。  来自康涅狄格州的民主党参议员Richard Blumenthal声称,他并不是反对消除TikTok的影响力,但告诫说提案给出的六个月出售时间太过仓促。  皮尤研究中心去年12月的一项民调显示,38%的美国人支持禁止TikTok,比例低于3月的50%。  在特朗普站出来反对这项禁令后,他的共和党同僚的态度就更加微妙了。  此前,美国前财政部长姆努钦在接受CNBC采访时说:“这是一家伟大的公司,应该由一家美国企业所有。作者:佚名原文链接:国际财闻汇(finance.ifeng.c...
            0 0 607
            分享
          •   笔者从08年开始做软件测试,到现在有10多年的时间了,以功能测试为主,做过将近两年的自动化测试,目前在家里做电商。  大家都知道今年的行情不太好,前段时间在各大网站上投了几百份简历,只收到了一个面试通知,公司在宝安的一个工业园,坐车过去需要一个多小时。  笔试  约好的面试时间是上午10点,为了不迟到,我8点就出发了,大概9点45分到达公司。然后前台让我填了一下表,接着给了我一份面试题,让我做完以后交给她。  我看了一下题目并不难,基本上都是问答题,主要是关于逻辑思维能力以及如何设计测试用例方面的。由于我有一年多的时间没做测试了,所以很多东西都荒废了,导致有几道题没答好,卷子做完之后就交给...
            0 0 877
            分享
          • 读者提问:如何区分前后端 BUG?阿常回答:这个问题我从三方面回答:1、为何要区分前后端 BUG;2、前后端 BUG 各有的特点;3、如何区分前后端 BUG。一、为何要区分前后端 BUG如果是大规模团队、多人开发的系统,测试不能明确到底是谁的 BUG,将 BUG 提交给了错误的开发人员,再加上人都有依赖心理,这个 BUG 就会被当皮球一样踢来踢去,极大增加了沟通成本,影响 BUG 修复时效。二、前后端 BUG 各有的特点前端 BUG:界面相关、布局相关、兼容性相关、交互相关。后端 BUG:业务逻辑相关、性能相关、数据相关、安全性相关。三、如何区分前后端 BUG一)经验法平时工作中多注意积累总结...
            0 0 1148
            分享
          •   很多人可能都还不明白需求分析和需求管理之间的区别,通常我们说起来最多的都是需求沟通和需求分析,开会都是讨论需求如何如何做,这其实是需求分析的过程如何如何,而与需求有关的其他活动提及的比较少。其实需求沟通和需求分析都只是需求管理过程中的两个环节。   一个项目做了很久,人力投入越来越多,大家都像打了鸡血一样天天加班,但是感觉总是做不完,就像一个“无底洞”。想尽快完成这个项目的时候,总有新的需求要做。实际上,这里涉及到一个需求管理的概念。项目中哪些该做,哪些应该先做,做到什么程度,都是由需求管理的过程来决定的。   通常需求管理是对需求生命周期的管理,从需求的产生到需求的结...
            0 0 287
            分享
      • 51testing软件测试圈微信