Python的装饰器实践

我希望写两个装饰器:

一个用来装饰class,另一个用来装饰method


装饰method的方法如下:

def methodrunning(func):
    """Be used to decorate method."""
    def wrapper(*args, **kwargs):
        print "%s is running" % func.__name__
        u = func(*args, **kwargs)
        return u
    return wrapper

这个方法写完以后,我在普通方法上进行测试,如下:

# -*- coding:utf-8 -*-
"""The module includes some testcases that test special situation of HTTP."""

from decorators import methodrunning


@methodrunning
def test1():
    """To test decorator of normal function."""
    print "This is test1."
test1()

结果如下:

test1 is running
This is test1.


然后,我在类级别的方法上进行测试:

# -*- coding:utf-8 -*-
"""The module includes some testcases that test special situation of HTTP."""

from decorators import methodrunning

class TestClass():
    """The class is to test decorator on the level of class method."""
    @methodrunning
    def testclass(self):
        """The mothod of class,used to test decorator of class level."""
        print "This is the testclass."



b = TestClass()
b.testclass()

结果如下:

testclass is running
This is the testclass.


综上所述,方法可用;



现在我将上述思维方法运用到nose框架上,做自动化接口测试:发现如下现象:


# -*- coding:utf-8 -*-
"""The module includes some testcases that test special situation of HTTP."""
import requests
from nose.tools import istest, nottest
import xml.dom.minidom
from TestBase import TestBase
from decorators import methodrunning





class TestSpecial(TestBase):
    """This is a class to test all function of get method."""
    @istest
    @methodrunning
    def test_from_post(self):
        """To test form post."""
        self.endpoint = "forms/post"
        self.url = ''.join([self.host, self.endpoint])
        print self.url
        r = requests.get(self.url)
        print r.text

结果如下:

ERROR: Failure: AttributeError (TestSpecial instance has no attribute 'wrapper')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/wdy/interfacetest/testvir/lib/python2.7/site-packages/nose/loader.py", line 523, in makeTest
    return self._makeTest(obj, parent)
  File "/Users/wdy/interfacetest/testvir/lib/python2.7/site-packages/nose/loader.py", line 582, in _makeTest
    return MethodTestCase(obj)
  File "/Users/wdy/interfacetest/testvir/lib/python2.7/site-packages/nose/case.py", line 348, in __init__
    self.test = getattr(self.inst, method_name)
AttributeError: TestSpecial instance has no attribute 'wrapper'



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值