0

I have a list of dicts:

MY_LIST = [ 
    { 'key1': {'a': 1, 'b':2 } },
    { 'key2': {'a': 1, 'b':2 } } 
]

How do I pass the dict to a django unit test using parameterized? E.g.

@parameterized.expand(MY_LIST):
def test_mytest(self, dict_item):
    print(dict_item.items())

Results in AttributeError: 'str' object has no attribute 'items' because the dict is being converted to a string.

alias51
  • 8,178
  • 22
  • 94
  • 166

3 Answers3

2

As stated in the docs:

The @parameterized and @parameterized.expand decorators accept a list or iterable of tuples or param(...), or a callable which returns a list or iterable

So I would try to convert MY_LIST to:

MY_LIST = [ 
    ({ 'key1': {'a': 1, 'b': 2}},),
    ({ 'key2': {'a': 1, 'b': 2}},), 
]

Which makes it a list of tuples that contain a single parameter to apply to the method you are testing.

Gtzzy
  • 519
  • 4
  • 18
1

You can create a NamedTuple instead to give your parameters keys

from typing import NamedTuple

class TestParameters(NamedTuple):
  firstParam: str
  secondParam: int
  
@parameterized.expand([TestParameters(
  firstParam="firstParam",
  secondParam="secondParam"
  )
]
def test(self, firstParam, secondParam):
  ...

if you need it as a dict for a differect reason, you can also do this

@parameterized.expand([TestParameters(
  firstParam="firstParam",
  secondParam="secondParam"
  )
]
def test(self, *args):
  test_params = TestParams(*args)._asdict()
Sharon
  • 11
  • 2
0

What worked for me was just packaging the dicts into a list (with just the one dict inside). Like:

MY_LIST = [[d] for d in MY_LIST]

Afterwards you might expect to unpack it (like: dict_item[0]), but that's not the case

jochenater
  • 33
  • 5