前言:

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

上一篇讲到用装饰器解决异常后自动截图,不过并没有与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. 在ubuntu下 使用Jetty 和 Maven 开发 HelloWorld

    1 安装JDK 我以前安装过,这里就不说了. 2 安装maven 去官网下载 解压 添加环境变量   gedit ~/.bashrc export JETTY_HOME=/home/roc/libs/ ...

  2. Flink之状态之savepoint

    1.总览 savepoints是外部存储的自包含的checkpoints,可以用来stop and resume,或者程序升级.savepoints利用checkpointing机制来创建流式作业的状 ...

  3. SSH整合主要XML代码

    web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2 ...

  4. hibernate对单表的增删改查

    ORM: 对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping) 实现对单表的增删改查 向区域表中增加数据: 第一步: 新建一个Da ...

  5. Reabble.com-KindleRSS新闻杂志订阅

    Reabble.com-KindleRSS新闻杂志订阅 TreeInsertions Tomcat部署war包后,运行时出现如下错误 RectangularCovering Reabble.com-K ...

  6. 【NOIP2017 D1 T1 小凯的疑惑】

    题目描述 小凯手中有两种面值的金币,两种面值均为正整数且彼此互素.每种金币小凯都有 无数个.在不找零的情况下,仅凭这两种金币,有些物品他是无法准确支付的.现在小 凯想知道在无法准确支付的物品中,最贵的 ...

  7. JAVA List 一边遍历一边删除元素

    JAVA List 一边遍历一边删除元素,报java.util.ConcurrentModificationException异常 2015年02月10日 14:42:49 zhanzkw 阅读数:3 ...

  8. 2015年网易校招Java开发工程师(技术架构)在线笔试题

    1.  程序和进程的本质区别是? A.在外存和内存存储 B.非顺序和顺序执行机器指令 C.独占使用和分时使用计算机资源 D.静态和动态特征 参考答案分析: 进程与应用程序的区别: 进程(Process ...

  9. Java多线程1:Java中sleep,wait,yield,join的区别

    1.sleep()方法 在指定时间内让当前正在执行的线程暂停执行,但不会释放“锁标志”.不推荐使用. sleep()使当前线程进入阻塞状态,在指定时间内不会执行. 2.wait()方法 在其他线程调用 ...

  10. WebKit阅读起步

    转摘自:http://my.oschina.net/myemptybottle/blog/42683 部分转摘,全文请查看原文! 我第一次看到WebKit代码中did,will前缀有点困惑,看多了才熟 ...