jeudi 6 août 2020

Python - how to reuse a dataclass with a limited number of fields?

I have a dataclass with many fields and I need to use it in a test. So I decided to extend the class and initialize it with a limited number of fields needed for testing. But this results in an error when creating the test dataclass:

self.metrics_provider = TestMetricsProvider(data)
E       TypeError: __init__() missing 3 required positional arguments: 'class_name', 'type', and 'score'

The base dataclass:

@dataclass
class MetricsProvider:
    name: str
    class_name: str
    type: str
    score: str
    source: str
    location: str = DEFAULT_LOCATION
    algorithm: Optional[str] = None

Dataclass in a test:

@dataclass
class TestMetricsProvider(MetricsProvider):
    pass

data = dict(
    name="test",
    class_name="test_class",
    type="test_type"
    score="test_score",
    source="test_source")

class TestMetrics(unittest.TestCase):
    def setUp(self) -> None:
        self.metrics_provider = TestMetricsProvider(data)

Defining the test dataclass like below resulted in the error: E TypeError: __init__() takes 1 positional argument but 2 were given

@dataclass
class TestMetricsProvider(MetricsProvider):
    def __init__(self):
        super().__init__()

How should I properly create it in this case? Or maybe it has to be mocked somehow?

Aucun commentaire:

Enregistrer un commentaire