私はノーズテスト ジェネレーター機能を使用して、異なるコンテキストで同じテストを実行しています。テストごとに次のボイラープレートが必要になるため:
class TestSample(TestBase):
def test_sample(self):
for context in contexts:
yield self.check_sample, context
def check_sample(self, context):
"""The real test logic is implemented here"""
pass
次のデコレータを作成することにしました。
def with_contexts(contexts=None):
if contexts is None:
contexts = ['twitter', 'linkedin', 'facebook']
def decorator(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
for context in contexts:
yield f, self, context # The line which causes the error
return wrapper
return decorator
デコレータは次のように使用されます。
class TestSample(TestBase):
@with_contexts()
def test_sample(self, context):
"""The real test logic is implemented here"""
var1 = self.some_valid_attribute
テストが実行されると、アクセスされている属性が使用できないことを示すエラーがスローされます。ただし、メソッドを呼び出す行を次のように変更すると、正常に動作します。
yield getattr(self, f.__name__), service
上記のスニペットはバインドされたメソッドを作成し、最初の 1 つの自己が関数に手動で渡されることを理解しています。ただし、私の理解では、最初のスニペットも問題なく動作するはずです。誰かが問題を明確にしていただければ幸いです。
質問のタイトルは、一般的にデコレーターでのインスタンス メソッドの呼び出しに関連していますが、私のコンテキストに固有の説明を保持しています。