Py.test mixin class 无法访问 `self`

Py.test mixin class can't access `self`

我正在尝试为一组共享测试创建一个 mixin。每当我希望那些通用测试 运行.

时,我都希望能够从 mixin 继承

这是我的一些混音:

class CommonRuleWhenTestsMixin(TestCase):

    def test_returns_false_if_rule_inactive(self):
        self.rule.active = False

        assert not self.rule.when(self.sim)

这是我使用 mixin 的时候:

class TestWhen(CommonRuleWhenTestsMixin):

        def setUp(self):
            self.customer = mommy.make(Customer)
            self.rule = mommy.make(
                UsageRule,
                customer=self.customer,
                max_recharges_per_month=2
            )
            self.sim = mommy.make(
                Sim,
                msisdn='0821234567',
                customer=self.customer
            )

            assert self.rule.when(self.sim)

        def test_returns_false_if_airtime_max_recharges_exceeded(self):
            self.rule.recharge_type = AIRTIME
            mommy.make(
                SimRechargeHistory,
                sim=self.sim,
                product_type=AIRTIME,
                _quantity=3
            )

            assert not self.rule.when(self.sim)

我不断收到这条消息:

_________ CommonRuleWhenTestsMixin.test_returns_false_if_rule_inactive _________                                                                                                                                  
simcontrol/rules/tests/test_models.py:14: in test_returns_false_if_rule_inactive                                                                                                                                  
    self.rule.active = False                                                                                                                                                                                      
E   AttributeError: 'CommonRuleWhenTestsMixin' object has no attribute 'rule'   

我的 mixin 如何访问 child class 在 self 上设置的变量?

你的 mixin inerhits 来自 unittest.TestCase,所以它的测试被 pytest 选中(并且可能也会被 unittest 选中)。

相反,不要从任何东西(或从 Python 2 上的 object 继承你的 mixin,并让你的 TestWhen class 从两个 unittest.TestCaseCommonRuleWhenTestsMixin.