前言:

装饰器其实就是一个以函数作为参数并返回一个替换函数的可执行函数

上一篇讲到用装饰器解决异常后自动截图,不过并没有与unittest结合,这篇把截图的装饰器改良了下,可以实现用例执行失败自动截图。

一、不带变量的装饰器

1.参考资料:http://www.artima.com/weblogs/viewpost.jsp?thread=240845,这里这篇讲的很好,可以看下原文

2.这个是不带变量的装饰器__init__里是初始化参数,__call__里面是原函数参数

Decorators without Arguments

If we create a decorator without arguments, the function to be decorated is passed to the constructor, and the __call__() method is called whenever the decorated function is invoked:

class decoratorWithoutArguments(object):

def __init__(self, f):
        """
        If there are no decorator arguments, the function
        to be decorated is passed to the constructor.
        """
        print "Inside __init__()"
        self.f = f

def __call__(self, *args):
        """
        The __call__ method is not called until the
        decorated function is called.
        """
        print "Inside __call__()"
        self.f(*args)
        print "After self.f(*args)"

@decoratorWithoutArguments
def sayHello(a1, a2, a3, a4):
    print 'sayHello arguments:', a1, a2, a3, a4

二、带变量的装饰器

1.这个是带变量的参数,参数写到__init__里

Decorators with Arguments

Now let's modify the above example to see what happens when we add arguments to the decorator:

class decoratorWithArguments(object):

def __init__(self, arg1, arg2, arg3):
        """
        If there are decorator arguments, the function
        to be decorated is not passed to the constructor!
        """
        print "Inside __init__()"
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

def __call__(self, f):
        """
        If there are decorator arguments, __call__() is only called
        once, as part of the decoration process! You can only give
        it a single argument, which is the function object.
        """
        print "Inside __call__()"
        def wrapped_f(*args):
            print "Inside wrapped_f()"
            print "Decorator arguments:", self.arg1, self.arg2, self.arg3
            f(*args)
            print "After f(*args)"
        return wrapped_f

@decoratorWithArguments("hello", "world", 42)
def sayHello(a1, a2, a3, a4):
    print 'sayHello arguments:', a1, a2, a3, a4

三、截图装饰器

1.有了上面的参考文档,依着葫芦画瓢就行,最大的麻烦就是driver参数处理,这里放到__init__里就可以了

四、参考案例

# coding:utf-8
from selenium import webdriver

class Screen(object):
    u'''这个应该截图功能的装饰器'''
    def __init__(self, driver):
        self.driver = driver

def __call__(self, f):
        def inner(*args):
            try:
                return f(*args)
            except:
                import time
                nowTime = time.strftime("%Y_%m_%d_%H_%M_%S")
                self.driver.get_screenshot_as_file('%s.jpg' % nowTime)
                raise
        return inner

# 以下是装饰器与unittest结合的案例
import unittest
class Test(unittest.TestCase):

driver = webdriver.Firefox()  # 全局参数driver

def setUp(self):
        self.driver.get("https://www.baidu.com")

@Screen(driver)
    def test01(self):
        u'''这个是失败的案例'''
        self.driver.find_element_by_id("11kw").send_keys("python")
        self.driver.find_element_by_id("su").click()

@Screen(driver)
    def test_02(self):
        u'''这个是通过的案例'''
        self.driver.find_element_by_id("kw").send_keys("yoyo")
        self.driver.find_element_by_id("su").click()

def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

Selenium2+python自动化67-用例失败自动截图【转载】的更多相关文章

  1. Selenium2+python自动化61-Chrome浏览器(chromedriver)【转载】

    前言 selenium2启动Chrome浏览器是需要安装驱动包的,但是不同的Chrome浏览器版本号,对应的驱动文件版本号又不一样,如果版本号不匹配,是没法启动起来的. 一.Chrome遇到问题 1. ...

  2. Selenium2+python自动化39-关于面试的题【转载】

    前言 最近看到群里有小伙伴贴出一组面试题,最近又是跳槽黄金季节,小编忍不住抽出一点时间总结了下, 回答不妥的地方欢迎各位高手拍砖指点.   一.selenium中如何判断元素是否存在? 首先selen ...

  3. QTP场景恢复之用例失败自动截图

    以下代码是在QC里运行QTP来执行脚本过程,当执行过程中发现用例失败后就会自动截图,然后把用例返回到最初始的状态,模拟了场景恢复的机制 Class QCImageErrorCapture Dim qt ...

  4. Selenium2+python自动化5-操作浏览器基本方法【转载】

    前言前面已经把环境搭建好了,这从这篇开始,正式学习selenium的webdriver框架.我们平常说的 selenium自动化,其实它并不是类似于QTP之类的有GUI界面的可视化工具,我们要学的是w ...

  5. Selenium2+python自动化62-jenkins持续集成环境搭建【转载】

    前言 selenium脚本写完之后,一般是集成到jenkins环境了,方便一键执行. 一.环境准备 小编环境: 1.win10 64位 2.JDK 1.8.0_66 3.tomcat 9.0.0.M4 ...

  6. Selenium2+python自动化46-js解决click失效问题【转载】

    前言 有时候元素明明已经找到了,运行也没报错,点击后页面没任何反应.这种问题遇到了,是比较头疼的,因为没任何报错,只是click事件失效了. 本篇用2种方法解决这种诡异的点击事件失效问题 一.遇到的问 ...

  7. Selenium2+python自动化11-定位一组元素find_elements【转载】

    前言 前面的几篇都是讲如何定位一个元素,有时候一个页面上有多个对象需要操作,如果一个个去定位的话,比较繁琐,这时候就可以定位一组对象. webdriver 提供了定位一组元素的方法,跟前面八种定位方式 ...

  8. Selenium2+python自动化-窗口多标签处理方法总结(转载)

    本篇转自博客:上海-小T 原文地址:https://i.cnblogs.com/EditArticles.aspx?opt=1 我们在用Selenium遇到多个浏览器窗口或单个浏览器多个标签(Tab) ...

  9. Selenium2+python自动化3-解决pip使用异常【转载】

    一.pip出现异常 有一小部分童鞋在打开cmd输入pip后出现下面情况:Did not provide a commandDid not provide a command?这是什么鬼?正常情况应该是 ...

随机推荐

  1. 持久化ORM框架——Hibernate与mybatis

    最初SUN公司推出了JavaEE服务器端组件模型(EJB),但是由于EJB配置复杂,且适用范围较小,于是很快就被淘汰了.与EJB的失败伴随而来的是另外一个框架的应运而生.他就是至今也比较流行的Hibe ...

  2. 《SQL入门经典》总结

    <SQL入门经典>这本书从考试前就开了个头,一直到前两天才看完,拉的战线也够长的.放假来了,基本上什么内容都不记得了.好不容易看完了,就赶紧总结一下吧! 该书分为两大部分,第一部分是第1~ ...

  3. tomcat8 管理页面403 Access Denied的解决方法

      安装tomcat,配置好tomcat环境变量以后,访问manager app页面,出现403 Access Denied错误,解决的方法如下: 首先在conf/tomcat-users.xml文件 ...

  4. 页面加载时给的子元素的第一个元素加class

    HTML代码: <div id="xiao"> <ul> <li></li> </ul> </div> js ...

  5. Python数据分析(二)pandas缺失值处理

    import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e' ...

  6. [bzoj1052] [HAOI2007]覆盖问题

    Description 某人在山上种了N棵小树苗.冬天来了,温度急速下降,小树苗脆弱得不堪一击,于是树主人想用一些塑料薄膜把这些小树遮盖起来,经过一番长久的思考,他决定用3个L * L的正方形塑料薄膜 ...

  7. POJ 3801/HDU 3157 Crazy Circuits | 有下界的最小流

    题目: POJ最近总是炸 所以还是用HDU吧http://acm.hdu.edu.cn/showproblem.php?pid=3157 题解: 题很长,但其实就是给个有源汇带下界网络流(+是源,-是 ...

  8. [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素

    Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For exampl ...

  9. Ubuntu下安装LNMP之nginx的卸载

    我在安装Nginx时,是采用自己从网上down下自己需要的nginx版本进行编译安装的,如果使用过apt库来进行安装的话可以参考这篇文章:ubuntu中彻底删除nginx 假如是编译安装的童鞋,可以按 ...

  10. NOIP2003 神经网络(bfs)

    NOIP2003 神经网络 题目背景: 人工神经网络(Artificial Neural Network)是一种新兴的具有自我学习能力的计算系统,在模式识别.函数逼近及贷款风险评估等诸多领域有广泛的应 ...