Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest: assert a list contains n instances of a class / object

@dataclass
class Component:
    name: str

class Assembly:
    def __init__():
        names = ["Able", "Baker", "Charlie"]
        self.components = [Component(name) for name in names]

def test_assembly():
    """Assembly should be initialised with three Components"""
    assembly = Assembly()
    assert assembly.components == [Component] * 3 # doesn't work

The assert doesn't work because it's comparing a list of class instances (assembly.components) to a list of class types. Is there a good way to write this test?

like image 790
Jack Deeth Avatar asked Nov 17 '25 19:11

Jack Deeth


1 Answers

You could iterate through the list and use isinstance():

def count_instance(lst, cls):
    count = 0
    for i in lst:
        if isinstance(i, cls):
            count += 1
    return count
assert count_instance(assembly.components, Component) == 3
like image 73
2pichar Avatar answered Nov 19 '25 08:11

2pichar