我希望写两个装饰器:
一个用来装饰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'