在python中测试副作用 [英] Testing for side-effects in python
问题描述
我想检查我的函数是否没有副作用,或仅影响精确变量的副作用.是否有一个函数可以检查它是否实际上没有副作用(或仅对某些变量具有副作用)?
I want to check that my function has no side-effects, or only side-effects affecting precise variables. Is there a function to check that it actually has no side-effects (or side-effects on only certain variables)?
如果没有,我该如何编写自己的代码,如下所示:
If not, how can I go about writing my own as follows:
我的想法是这样的,初始化,调用被测函数,然后调用最终方法:
class test_side_effects(parents_scope, exclude_variables=[]):
def __init__():
for variable_name, variable_initial in parents_scope.items():
if variable_name not in exclude_variables:
setattr(self, "test_"+variable_name, variable_initial)
def final(self, final_parents_scope):
for variable_name, variable_final in final_parents_scope.items():
if variable_name[:5] is "test_" and variable_name not in exclude_variables:
assert getattr(self, "test_"+variable_name) is variable_final, "Unexpected side effect of %s from %s to %s" % (variable_name, variable_initial, variable_final)
#here parents_scope should be inputted as dict(globals(),**locals())
I'm unsure if this is precisely the dictionary I want...
最后,我应该这样做吗?如果没有,为什么不呢?
Finally, should I be doing this? If not, why not?
推荐答案
我对编写测试所用的嵌套函数测试库并不熟悉,但似乎您确实应该在此处使用类(例如,在许多框架中都是TestCase).
I'm not familiar with the nested function testing library that you might be writing a test with, but it seems like you should really be using classes here (i.e. TestCase in many frameworks).
如果您的问题与在TestCase中获取父变量有关,则可以得到__dict__
(对我而言,您所指的父"变量不清楚.
If your question then, is relating to getting the parent variables in your TestCase, you could get the __dict__
(It wasn't clear to me what the "Parent" variables you were referring to.
更新:@hayden发布要点以显示父变量的使用:
UPDATE: @hayden posted a gist to show the use of parent variables:
def f():
a = 2
b = 1
def g():
#a = 3
b = 2
c = 1
print dict(globals(), **locals()) #prints a=1, but we want a=2 (from f)
g()
a = 1
f()
如果将其转换为字典,则可以使用以下方法解决该问题:
If this is converted to a dictionary, then the problem is solvable with:
class f(object): # could be unittest TestCase
def setUp(self, a=2, b=1):
self.a = a
self.b = b
def g(self):
#a = 3
b = 2
c = 1
full_scope = globals().copy()
full_scope.update(self.__dict__)
full_scope.update(locals())
full_scope.pop('full_scope')
print full_scope # print a = 1
my_test = f()
my_test.setUp(a=1)
my_test.g()
您应该寻找已经实现了此目的的工具.我希望其他人将有一个已经实施的解决方案.
You are right to look for a tool which has already implemented this. I am hopeful that somebody else will have an already implemented solution.
这篇关于在python中测试副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!