どのように私はPythonで複数の関数に同じデコレータを使うのですか?

アシシュ・シン:

私はジャンゴでテストし、オブジェクトのメソッドをあざけるために()デコレータmock.patch.objectを使用しています。私は、そのクラスの別の目的球で同じデコレータを使用します。このために、私は、関数からのクラスにデコレータを移動しました。これは私の問題を解決し、今私は、これらの機能を模擬べきではない別のテスト目的球を、追加したいです。

@mock.patch.object(MyClass, 'class_fun_2')
@mock.patch.object(MyClass, 'class_fun_1')
class TestClass(testcases.TestCase):
    def setUp(self):
    # contains my setup that I want to use in all functions for this test class

    def test_function_1(self, mocked_class_fun_1, mocked_class_fun_2):
    # I want to use those mocked functions here

    def test_function_2(self, mocked_class_fun_1, mocked_class_fun_2):
    # I want to use those mocked functions here too

    def test_function_3(self):
    # I do not want to use those mocked functions here

私はこれを行う場合は、エラーを投げています。

TypeError: test_function_3() takes 1 positional argument but 3 were given

だから私は、私は2つのだけfuntionsにすべての関数と嘲笑funtionsでセットアップを使用することができ、何をすべき?

PS:mock.patchの繰り返しは良い考えではないかもしれませんので、私は唯一の2嘲笑funtionsを示しているが、実際に、私は8つの機能をからかっています。

MatsLindh:

-デコレータのない親のテストクラスを作成TestParent、あなたからのコードが含まれsetUp、その後2つのサブクラスで、このクラスから継承するメソッド、 -飾られています1、および1つはありません。

class TestClassParent(testcases.TestCase):
    def setUp(self):
        # contains my setup that I want to use in all functions for this test class

@mock.patch.object(MyClass, 'class_fun_2')
@mock.patch.object(MyClass, 'class_fun_1')
class TestClassMocked(TestClassParent):
    def test_function_1(self, mocked_class_fun_1, mocked_class_fun_2):
        # I want to use those mocked functions here

    def test_function_2(self, mocked_class_fun_1, mocked_class_fun_2):
        # I want to use those mocked functions here too

class TestClassNotMocked(TestClassParent):
    def test_function_3(self):
        # I do not want to use those mocked functions here

それはあなたがセットアップコードを共有することを可能にする、と嘲笑されるべきでないメソッドを指定します。

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=395842&siteId=1