我想我要做的事情很简单。我想初始化测试设置函数中的几个变量,然后在用该设置装饰的测试函数中使用它们。下面这个简单的例子说明了我的意思:
from nose.tools import *
def setup():
foo = 10
def teardown():
foo = None
@with_setup(setup, teardown)
def test_foo_value():
assert_equal(foo, 10)
这将导致:
$ nosetests tests/test_foo.py
E
======================================================================
ERROR: test_foo.test_foo_value
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/mtozzi/.virtualenvs/foo/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/mtozzi/code/foo/tests/test_foo.py", line 12, in test_foo_value
assert_equal(foo, 10)
NameError: global name 'foo' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.006s
FAILED (errors=1)
使用旧的unittest风格,我可以将它们设置为test类上的实例变量,但我认为nosetest不需要使用类。我也考虑过将它们设置为包全局变量,但这似乎不是一个非常好的做法。我希望我在做这件事时明显遗漏了一些东西。
发布于 2012-05-14 01:27:38
正如您的问题的注释所建议的,只需切换到类并使用实例变量,如self.foo
。这就是应该做的事情。
如果您坚持不使用类,可以尝试使用global
变量。不过,你不是从我这听说的。
from nose.tools import *
foo = None
def setup():
global foo # Ugly.
foo = 10
def teardown():
global foo # Ugly.
foo = None
@with_setup(setup, teardown)
def test_foo_value():
assert_equal(foo, 10)
第三个变体可能是使用字典来表示您的值。这稍微不那么难看,但却非常笨拙:
from nose.tools import *
_globals = {'foo': None}
def setup():
_globals['foo'] = 10
def teardown():
_globals['foo'] = None
@with_setup(setup, teardown)
def test_foo_value():
foo = _globals['foo']
assert_equal(foo, 10)
发布于 2014-05-13 03:27:43
我使用了一个定制的with_setup装饰器,它使用了穷人的非本地化:https://gist.github.com/garyvdm/392ae20c673c7ee58d76
def setup():
foo = 10
return [foo], {}
def teardown(foo):
pass
@with_setup_args(setup, teardown)
def test_foo_value(foo):
nose.tools.assert_equal(foo, 10)
对于仅使用Python 3的项目,我使用非本地而不是.tend/.update作为参数,kwargs。
https://stackoverflow.com/questions/10565523
复制相似问题