zoukankan      html  css  js  c++  java
  • python学习笔记(异常处理)

    上次提到正则表达式

    当未匹配到数据返回值 None

    再使用 match.group 会出现异常 AttributeError

    为了避免异常我改成“ match != None”

    这次加入异常处理

     1 #!/usr/bin/env python
     2 # -*- coding: utf_8 -*-
     3 
     4 import requests
     5 import unittest
     6 import re
     7 
     8 class Testswcw_back(unittest.TestCase):
     9     def setUp(self):
    10         print "接口测试开始"
    11 
    12     def tearDown(self):
    13         print "接口测试结束"
    14 
    15     def testlogin_1(self): #登录测试用例
    16         url = 'http://localhost:8081/swcw/back/sysLogin.action'
    17         postparams = {'username':'admin','password':'123456'}
    18         results = requests.post(url,postparams)
    19         pattern = re.compile(r'toMain')
    20         match = pattern.search(results.url)
    21         try:
    22             if results.status_code == 200:
    23                 if match.group() == 'toMain':
    24                     print '用例测试结果:测试通过'
    25             else:
    26                 print '用例测试结果:请求失败'
    27         except AttributeError: 
    28             print '用例测试结果:测试失败'
    29 
    30     def testlogin_2(self): #登录测试用例
    31         url = 'http://localhost:8081/swcw/back/sysLogin.action'
    32         postparams = {'username':'admin','password':'123457'} #密码错误
    33         results = requests.post(url,postparams)
    34         pattern = re.compile(r'toMain')
    35         match = pattern.search(results.url)
    36         try:
    37             if results.status_code == 200:
    38                 if match.group() == 'toMain':
    39                     print '用例测试结果:测试通过'
    40             else:
    41                 print '用例测试结果:请求失败'
    42         except AttributeError:
    43             print '用例测试结果:测试失败'
    44 
    45     def testlogin_3(self): #登录测试用例
    46         url = 'http://localhost:8081/swcw/back/sysLogin.action'
    47         postparams = {'username':'admin1','password':'123456'} #登录名错误
    48         results = requests.post(url,postparams)
    49         pattern = re.compile(r'toMain')
    50         match = pattern.search(results.url)
    51         try:
    52             if results.status_code == 200:
    53                 if match.group() == 'toMain':
    54                     print '用例测试结果:测试通过'
    55             else:
    56                 print '用例测试结果:请求失败'
    57         except AttributeError:
    58             print '用例测试结果:测试失败'
    59 
    60 if __name__ == "__main__":
    61     unittest.main()

    异常处理的格式:

    try:

      【代码】

    except 【异常名称】:

      【代码】

    如果想屏蔽所有异常 如下即可

    try:

      【代码】

    except:

      【代码】

  • 相关阅读:
    归并排序
    堆排序
    数组数据生成器
    冒泡排序
    快速排序
    希尔排序
    排序接口与抽象类(java)
    Pycharm下HTMLTestRunner不生成测试报告
    抓包工具使用记录
    接口学习笔记
  • 原文地址:https://www.cnblogs.com/cllovewxq/p/5362429.html
Copyright © 2011-2022 走看看