Home > Mobile >  How to reference an object in a class using a decorator
How to reference an object in a class using a decorator

Time:09-12

I have a list of dicts defined in setUpClass in a Django TestCase:

class MyTest(TestCase):

    @classmethod
    def setUpClass(cls):

        myobj = MyModel.objects.create()

        cls.MY_LIST = [ 
            ({ 'key1': {'a': myobj.id, 'b': 2}},),
            ({ 'key2': {'a': myobj.id, 'b': 2}},), 
        ]

How do I reference MY_LIST using parameterized? E.g.

@parameterized.expand(MyTest().setUpClass().MYLIST):
def test_mytest(self, dict_item):
    print(dict_item.items())

Results in AttributeError: 'NoneType' object has no attribute 'MYLIST'.

CodePudding user response:

You can do it. In your case:

class MyTest(TestCase):

    @classmethod
    def setUpClass(cls):
        ... # your staff
        cls.MY_LIST = [...]
        super().setUpClass()
        return cls

Use in tests:

@parameterized.expand(MyTest.setUpClass().MYLIST):
def test_mytest(self, dict_item):
    ... # your test staff

Don't forget, classmethod you can call with class. You are not need instance.

CodePudding user response:

I think the problem is that you're calling setUpClass to add the property MY_LIST, but setUpClass doesn't return nothing. So you can do this things:

MyTest.setUpClass()
@parameterized.expand(MyTest.MYLIST):
def test_mytest(self, dict_item):
    ... # your test staff

or:

class MyTest(TestCase):

    @classmethod
    def setUpClass(cls):

        myobj = MyModel.objects.create()

        cls.MY_LIST = [ 
            ({ 'key1': {'a': myobj.id, 'b': 2}},),
            ({ 'key2': {'a': myobj.id, 'b': 2}},), 
        ]
        return cls

@parameterized.expand(MyTest().setUpClass().MYLIST):
def test_mytest(self, dict_item):
    print(dict_item.items())

  • Related