Lee
Lee

Reputation: 8744

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

I am trying to make a mixin for a shared set of tests. I want to be able to inherit from the mixin whenever I want those generic tests to run.

Here is some of my mixin:

class CommonRuleWhenTestsMixin(TestCase):

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

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

Here is when I use the 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)

I keep getting this message:

_________ 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'   

How can my mixin access the variables set on self by the child class?

Upvotes: 1

Views: 789

Answers (1)

The Compiler
The Compiler

Reputation: 11989

Your mixin inerhits from unittest.TestCase, so its test gets picked up by pytest (and would probably get picked up by unittest as well).

Instead, don't inherit your mixin from anything (or from object on Python 2), and make your TestWhen class inherit from both unittest.TestCase and CommonRuleWhenTestsMixin.

Upvotes: 3

Related Questions