1

関数に副作用がないこと、または正確な変数に影響を与える副作用のみがあることを確認したいと思います。実際に副作用(または特定の変数のみの副作用)がないことを確認する機能はありますか?

そうでない場合は、どうすれば次のように自分で書くことができますか?

私の考えは、初期化して、テスト対象の関数を呼び出してから、finalメソッドを呼び出すようなものです。

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())

これがまさに私が欲しい辞書かどうかはわかりませ ん...

最後に、私はこれを行うべきですか?そうでない場合は、なぜですか?

4

1 に答える 1

3

私はあなたがテストを書いているかもしれないネストされた関数テストライブラリに慣れていませんが、ここでは本当にクラスを使うべきだと思われます (つまり、多くのフレームワークでは TestCase です)。

あなたの質問が TestCase で親変数を取得することに関連している場合は、取得できます__dict__(「親」変数が何を参照しているのかわかりませんでした。

更新: @hayden は、親変数の使用を示す要点を投稿しました:

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()

これが辞書に変換される場合、問題は次の方法で解決できます。

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()

これをすでに実装しているツールを探すのは正しいことです。他の誰かがすでに実装されているソリューションを持っていることを願っています。

于 2012-07-19T11:43:17.187 に答える