jeudi 8 novembre 2018

Python "match" objects for testing data structures

Consider this example class Approximate:

class Approximate:
    """Takes a floating point number and implements approximate equality."""

    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return abs(self.value - other) / (abs(self.value) + abs(other)) < 1e-6

    def __repr__(self):
        return f"Approximate({self.value})"

This class can be very handy when testing data structures like dict:

data = {
    "foo": {
        "key1": "OK",
        "value2": 1.2000000001
    }
}

assert data ==  {
    "foo": {
        "key1": "OK",
        "value2": Approximate(1.2)
    }
}

This is so useful so that one is tempted to defined Matches, Contains, etc. But surely someone has already done this? Is there a good Python library with objects like these for testing?

Aucun commentaire:

Enregistrer un commentaire