Skip to content

Documentation

Base Compare

CompareBase

Bases: ABC

Base class for all comparison classes.

Source code in pytest_compare/base.py
class CompareBase(ABC):
    """Base class for all comparison classes."""

    EXPECTED_TYPE: Type = Any
    ACTUAL_TYPE: Type = Any

    def __init__(self, expected: EXPECTED_TYPE):
        self._check_type("expected", expected, self.EXPECTED_TYPE)
        self.expected = expected

    def __eq__(self, actual: ACTUAL_TYPE) -> bool:
        self._check_type("actual", actual, self.ACTUAL_TYPE)
        return self.compare(actual)

    def _check_type(self, argname: str, value, expected_type):
        if TYPEGUARD_VERSION_MAJOR >= 3:
            check_type(value, expected_type)
        else:
            check_type(argname, value, expected_type)

    @abstractmethod
    def compare(self, actual: ACTUAL_TYPE) -> bool:
        """
        Compare two objects.

        Args:
            actual Any: The other object to compare to.

        Returns:
            bool: True if the objects are equal, False otherwise.
        """
        pass

compare(actual) abstractmethod

Compare two objects.

Parameters:

Name Type Description Default
actual Any

The other object to compare to.

required

Returns:

Name Type Description
bool bool

True if the objects are equal, False otherwise.

Source code in pytest_compare/base.py
@abstractmethod
def compare(self, actual: ACTUAL_TYPE) -> bool:
    """
    Compare two objects.

    Args:
        actual Any: The other object to compare to.

    Returns:
        bool: True if the objects are equal, False otherwise.
    """
    pass

Native Compares

CompareIn

Bases: CompareBase

Compare in.

Source code in pytest_compare/native/native.py
@typechecked
class CompareIn(CompareBase):
    """Compare in."""

    EXPECTED_TYPE = Any
    ACTUAL_TYPE = Any

    def __init__(self, expected: EXPECTED_TYPE, reverse: bool = False):
        """Initialize the class.

        Args:
            expected (str): The expected value.
            reverse (bool): If True, the actual value is expected to be a
                substring of the expected value. If False, the expected value is
                expected to be a substring of the actual value.
        """
        super().__init__(expected)
        self.reverse = reverse

    def compare(self, actual: ACTUAL_TYPE) -> bool:
        """Compare if the actual value is in the expected value.

        Args:
            actual (Any): The actual value.

        Returns:
            True if the expected value is in the actual value.
        """
        if self.reverse:
            return self.expected in actual
        return actual in self.expected

__init__(expected, reverse=False)

Initialize the class.

Parameters:

Name Type Description Default
expected str

The expected value.

required
reverse bool

If True, the actual value is expected to be a substring of the expected value. If False, the expected value is expected to be a substring of the actual value.

False
Source code in pytest_compare/native/native.py
def __init__(self, expected: EXPECTED_TYPE, reverse: bool = False):
    """Initialize the class.

    Args:
        expected (str): The expected value.
        reverse (bool): If True, the actual value is expected to be a
            substring of the expected value. If False, the expected value is
            expected to be a substring of the actual value.
    """
    super().__init__(expected)
    self.reverse = reverse

compare(actual)

Compare if the actual value is in the expected value.

Parameters:

Name Type Description Default
actual Any

The actual value.

required

Returns:

Type Description
bool

True if the expected value is in the actual value.

Source code in pytest_compare/native/native.py
def compare(self, actual: ACTUAL_TYPE) -> bool:
    """Compare if the actual value is in the expected value.

    Args:
        actual (Any): The actual value.

    Returns:
        True if the expected value is in the actual value.
    """
    if self.reverse:
        return self.expected in actual
    return actual in self.expected

CompareIsInstanceOf

Bases: CompareBase

Compare instanceof.

Source code in pytest_compare/native/native.py
@typechecked
class CompareIsInstanceOf(CompareBase):
    """Compare instanceof."""

    EXPECTED_TYPE = Type

    def compare(self, actual: Any) -> bool:
        """Compare if the actual value is an instance of the expected type.

        Args:
            actual (Any): The actual instance.

        Returns:
            True if the actual instance is an instance of the expected type.
        """
        return isinstance(actual, self.expected)

compare(actual)

Compare if the actual value is an instance of the expected type.

Parameters:

Name Type Description Default
actual Any

The actual instance.

required

Returns:

Type Description
bool

True if the actual instance is an instance of the expected type.

Source code in pytest_compare/native/native.py
def compare(self, actual: Any) -> bool:
    """Compare if the actual value is an instance of the expected type.

    Args:
        actual (Any): The actual instance.

    Returns:
        True if the actual instance is an instance of the expected type.
    """
    return isinstance(actual, self.expected)

CompareIsSubclassOf

Bases: CompareBase

Compare issubclass.

Source code in pytest_compare/native/native.py
@typechecked
class CompareIsSubclassOf(CompareBase):
    """Compare issubclass."""

    EXPECTED_TYPE = Type

    def compare(self, actual: Any) -> bool:
        """Compare if the actual value is a subclass of the expected type.

        Args:
            actual (Any): The actual instance.

        Returns:
            True if the actual instance is a subclass of the expected type.
        """
        return issubclass(actual, self.expected)

compare(actual)

Compare if the actual value is a subclass of the expected type.

Parameters:

Name Type Description Default
actual Any

The actual instance.

required

Returns:

Type Description
bool

True if the actual instance is a subclass of the expected type.

Source code in pytest_compare/native/native.py
def compare(self, actual: Any) -> bool:
    """Compare if the actual value is a subclass of the expected type.

    Args:
        actual (Any): The actual instance.

    Returns:
        True if the actual instance is a subclass of the expected type.
    """
    return issubclass(actual, self.expected)

CompareLength

Bases: CompareBase

Compare length.

Source code in pytest_compare/native/native.py
@typechecked
class CompareLength(CompareBase):
    """Compare length."""

    def compare(self, actual: Any) -> bool:
        """Compare the actual length to the expected length.

        Args:
            actual (Any): The actual value.

        Returns:
            True if the actual instance has the expected length.
        """
        return len(actual) == self.expected

compare(actual)

Compare the actual length to the expected length.

Parameters:

Name Type Description Default
actual Any

The actual value.

required

Returns:

Type Description
bool

True if the actual instance has the expected length.

Source code in pytest_compare/native/native.py
def compare(self, actual: Any) -> bool:
    """Compare the actual length to the expected length.

    Args:
        actual (Any): The actual value.

    Returns:
        True if the actual instance has the expected length.
    """
    return len(actual) == self.expected

CompareSubString

Bases: CompareBase

Compare substring.

To test if the actual value is a substring of the expected value, use CompareSubString(expected).

For example:

with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
    thing = ProductionClass()
    thing.method("actual_string")

# test if mock_method was called with "string" as a substring of the actual value
mock_method.assert_called_once_with(CompareSubString("string"))

# test if the called value is a substring of the expected value
mock_method.assert_called_once_with(CompareSubString("expected_string_containing_actual_string", reverse=True))

# test that the called value is not a substring of the expected value
mock_method.assert_called_once_with(CompareSubString("not_called_value", contains=False))
Source code in pytest_compare/native/native.py
@typechecked
class CompareSubString(CompareBase):
    """Compare substring.

    To test if the actual value is a substring of the expected value, use CompareSubString(expected).

    For example:

    ```python
    with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
        thing = ProductionClass()
        thing.method("actual_string")

    # test if mock_method was called with "string" as a substring of the actual value
    mock_method.assert_called_once_with(CompareSubString("string"))

    # test if the called value is a substring of the expected value
    mock_method.assert_called_once_with(CompareSubString("expected_string_containing_actual_string", reverse=True))

    # test that the called value is not a substring of the expected value
    mock_method.assert_called_once_with(CompareSubString("not_called_value", contains=False))
    ```
    """

    EXPECTED_TYPE = str
    ACTUAL_TYPE = str

    def __init__(
        self, expected: EXPECTED_TYPE, reverse: bool = False, contains: bool = True
    ):
        """Initialize the class.

        Args:
            expected (str): The expected value.
            reverse (bool): If True, the actual value is expected to be a
                substring of the expected value. If False, the expected value is
                expected to be a substring of the actual value.
            contains (bool): If True, the expected value is expected to be a
                substring of the actual value. If False, the expected value is
                expected to not be a substring of the actual value.
        """
        super().__init__(expected)
        self.reverse = reverse
        self.contains = contains

    def compare(self, actual: ACTUAL_TYPE) -> bool:
        """Compare if the actual value is a substring of the expected value.

        Args:
            actual (str): The actual value.

        Returns:
            True if the expected value is a substring of the actual value.
        """
        if self.reverse:
            return not ((self.expected in actual) ^ self.contains)
        return not ((actual in self.expected) ^ self.contains)

__init__(expected, reverse=False, contains=True)

Initialize the class.

Parameters:

Name Type Description Default
expected str

The expected value.

required
reverse bool

If True, the actual value is expected to be a substring of the expected value. If False, the expected value is expected to be a substring of the actual value.

False
contains bool

If True, the expected value is expected to be a substring of the actual value. If False, the expected value is expected to not be a substring of the actual value.

True
Source code in pytest_compare/native/native.py
def __init__(
    self, expected: EXPECTED_TYPE, reverse: bool = False, contains: bool = True
):
    """Initialize the class.

    Args:
        expected (str): The expected value.
        reverse (bool): If True, the actual value is expected to be a
            substring of the expected value. If False, the expected value is
            expected to be a substring of the actual value.
        contains (bool): If True, the expected value is expected to be a
            substring of the actual value. If False, the expected value is
            expected to not be a substring of the actual value.
    """
    super().__init__(expected)
    self.reverse = reverse
    self.contains = contains

compare(actual)

Compare if the actual value is a substring of the expected value.

Parameters:

Name Type Description Default
actual str

The actual value.

required

Returns:

Type Description
bool

True if the expected value is a substring of the actual value.

Source code in pytest_compare/native/native.py
def compare(self, actual: ACTUAL_TYPE) -> bool:
    """Compare if the actual value is a substring of the expected value.

    Args:
        actual (str): The actual value.

    Returns:
        True if the expected value is a substring of the actual value.
    """
    if self.reverse:
        return not ((self.expected in actual) ^ self.contains)
    return not ((actual in self.expected) ^ self.contains)

CompareType

Bases: CompareBase

Compare types.

Source code in pytest_compare/native/native.py
@typechecked
class CompareType(CompareBase):
    """Compare types."""

    EXPECTED_TYPE = Type

    def compare(self, actual: Any) -> bool:
        """Compare the actual type to the expected type.

        Args:
            actual (Any): The actual value.

        Returns:
            True if the actual value matches the expected value.
        """
        return type(actual) == self.expected

compare(actual)

Compare the actual type to the expected type.

Parameters:

Name Type Description Default
actual Any

The actual value.

required

Returns:

Type Description
bool

True if the actual value matches the expected value.

Source code in pytest_compare/native/native.py
def compare(self, actual: Any) -> bool:
    """Compare the actual type to the expected type.

    Args:
        actual (Any): The actual value.

    Returns:
        True if the actual value matches the expected value.
    """
    return type(actual) == self.expected

Dict Compares

CompareDictContains

Bases: CompareDictBase

Check if the actual dictionary is a subset of the expected dictionary.

Source code in pytest_compare/dict/dict.py
@typechecked
class CompareDictContains(CompareDictBase):
    """Check if the actual dictionary is a subset of the expected dictionary."""

    def __init__(self, expected: Dict, reverse_contains: bool = False):
        """Initialize the class.

        Args:
            expected (Dict): Expected dictionary.
            reverse_contains (bool): If True, the comparison is reversed.
        """
        super().__init__(expected)
        self._reverse_contains = reverse_contains

    def compare(self, actual: Dict) -> bool:
        """Check if the actual dictionary is a subset of the expected dictionary.
        If reverse_contains is True, the comparison is reversed.

        Args:
            actual (Dict): Actual dictionary.

        Returns:
            bool: True if the first dictionary is a subset of the second dictionary, False otherwise.
        """
        if self._reverse_contains:
            return actual.items() <= self.expected.items()
        else:
            return self.expected.items() <= actual.items()

__init__(expected, reverse_contains=False)

Initialize the class.

Parameters:

Name Type Description Default
expected Dict

Expected dictionary.

required
reverse_contains bool

If True, the comparison is reversed.

False
Source code in pytest_compare/dict/dict.py
def __init__(self, expected: Dict, reverse_contains: bool = False):
    """Initialize the class.

    Args:
        expected (Dict): Expected dictionary.
        reverse_contains (bool): If True, the comparison is reversed.
    """
    super().__init__(expected)
    self._reverse_contains = reverse_contains

compare(actual)

Check if the actual dictionary is a subset of the expected dictionary. If reverse_contains is True, the comparison is reversed.

Parameters:

Name Type Description Default
actual Dict

Actual dictionary.

required

Returns:

Name Type Description
bool bool

True if the first dictionary is a subset of the second dictionary, False otherwise.

Source code in pytest_compare/dict/dict.py
def compare(self, actual: Dict) -> bool:
    """Check if the actual dictionary is a subset of the expected dictionary.
    If reverse_contains is True, the comparison is reversed.

    Args:
        actual (Dict): Actual dictionary.

    Returns:
        bool: True if the first dictionary is a subset of the second dictionary, False otherwise.
    """
    if self._reverse_contains:
        return actual.items() <= self.expected.items()
    else:
        return self.expected.items() <= actual.items()

CompareDictKeys

Bases: CompareDictBase

Compare if the actual dictionary has the expected keys.

Source code in pytest_compare/dict/dict.py
@typechecked
class CompareDictKeys(CompareDictBase):
    """Compare if the actual dictionary has the expected keys."""

    EXPECTED_TYPE = Union[Dict, List[str]]

    def compare(self, actual: Dict) -> bool:
        """Compare if the actual dictionary has the expected keys.

        Args:
            actual (Dict, List[str]): Actual dictionary or list of expected keys.

        Returns:
            bool: True if the actual dictionary has the expected keys, False otherwise.
        """
        expected_keys = (
            self.expected.keys() if isinstance(self.expected, dict) else self.expected
        )
        return set(actual.keys()) == set(expected_keys)

compare(actual)

Compare if the actual dictionary has the expected keys.

Parameters:

Name Type Description Default
actual Dict, List[str]

Actual dictionary or list of expected keys.

required

Returns:

Name Type Description
bool bool

True if the actual dictionary has the expected keys, False otherwise.

Source code in pytest_compare/dict/dict.py
def compare(self, actual: Dict) -> bool:
    """Compare if the actual dictionary has the expected keys.

    Args:
        actual (Dict, List[str]): Actual dictionary or list of expected keys.

    Returns:
        bool: True if the actual dictionary has the expected keys, False otherwise.
    """
    expected_keys = (
        self.expected.keys() if isinstance(self.expected, dict) else self.expected
    )
    return set(actual.keys()) == set(expected_keys)

Pandas Compares

CompareDataFrame

Bases: CompareDataFrameBase

Compare two dataframes.

Source code in pytest_compare/pandas/pandas.py
@typechecked
class CompareDataFrame(CompareDataFrameBase):
    """Compare two dataframes."""

    EXPECTED_TYPE = pd.DataFrame
    ACTUAL_TYPE = pd.DataFrame

    def __init__(self, expected: EXPECTED_TYPE, columns: Optional[List[str]] = None):
        """Initialize the class.

        Args:
            expected (pd.DataFrame): Expected Dataframe.
            columns (List[str], optional): Columns to compare. If None, all columns are compared. Defaults to None.
        """
        super().__init__(expected)
        self._columns = columns

    def compare(self, actual: ACTUAL_TYPE) -> bool:
        """Compare two dataframes.

        Args:
            actual (pd.DataFrame): Actual Dataframe.

        Returns:
            bool: True if the dataframes are equal, False otherwise.
        """
        if not self._columns:
            return actual.equals(self.expected)
        else:
            return actual[self._columns].equals(self.expected[self._columns])

__init__(expected, columns=None)

Initialize the class.

Parameters:

Name Type Description Default
expected pd.DataFrame

Expected Dataframe.

required
columns List[str]

Columns to compare. If None, all columns are compared. Defaults to None.

None
Source code in pytest_compare/pandas/pandas.py
def __init__(self, expected: EXPECTED_TYPE, columns: Optional[List[str]] = None):
    """Initialize the class.

    Args:
        expected (pd.DataFrame): Expected Dataframe.
        columns (List[str], optional): Columns to compare. If None, all columns are compared. Defaults to None.
    """
    super().__init__(expected)
    self._columns = columns

compare(actual)

Compare two dataframes.

Parameters:

Name Type Description Default
actual pd.DataFrame

Actual Dataframe.

required

Returns:

Name Type Description
bool bool

True if the dataframes are equal, False otherwise.

Source code in pytest_compare/pandas/pandas.py
def compare(self, actual: ACTUAL_TYPE) -> bool:
    """Compare two dataframes.

    Args:
        actual (pd.DataFrame): Actual Dataframe.

    Returns:
        bool: True if the dataframes are equal, False otherwise.
    """
    if not self._columns:
        return actual.equals(self.expected)
    else:
        return actual[self._columns].equals(self.expected[self._columns])

CompareDataFrameColumns

Bases: CompareDataFrameBase

Compare two dataframe columns.

Source code in pytest_compare/pandas/pandas.py
@typechecked
class CompareDataFrameColumns(CompareDataFrameBase):
    """Compare two dataframe columns."""

    EXPECTED_TYPE = Union[pd.DataFrame, List[str]]
    ACTUAL_TYPE = pd.DataFrame

    def compare(self, actual: ACTUAL_TYPE) -> bool:
        """Compare two dataframe columns.

        Args:
            actual (pd.DataFrame): Actual Dataframe.

        Returns:
            bool: True if columns are identical, False otherwise.
        """
        expected_columns = (
            self.expected.columns
            if isinstance(self.expected, pd.DataFrame)
            else self.expected
        )
        return set(actual.columns) == set(expected_columns)

compare(actual)

Compare two dataframe columns.

Parameters:

Name Type Description Default
actual pd.DataFrame

Actual Dataframe.

required

Returns:

Name Type Description
bool bool

True if columns are identical, False otherwise.

Source code in pytest_compare/pandas/pandas.py
def compare(self, actual: ACTUAL_TYPE) -> bool:
    """Compare two dataframe columns.

    Args:
        actual (pd.DataFrame): Actual Dataframe.

    Returns:
        bool: True if columns are identical, False otherwise.
    """
    expected_columns = (
        self.expected.columns
        if isinstance(self.expected, pd.DataFrame)
        else self.expected
    )
    return set(actual.columns) == set(expected_columns)

CompareSeries

Bases: CompareDataFrameBase

Compare two series.

Source code in pytest_compare/pandas/pandas.py
@typechecked
class CompareSeries(CompareDataFrameBase):
    """Compare two series."""

    EXPECTED_TYPE = pd.Series
    ACTUAL_TYPE = pd.Series

    def compare(self, actual: ACTUAL_TYPE) -> bool:
        """Compare two series.

        Args:
            actual (pd.Series): Actual Series.

        Returns:
            bool: True if the series are equal, False otherwise.
        """
        return actual.equals(self.expected)

compare(actual)

Compare two series.

Parameters:

Name Type Description Default
actual pd.Series

Actual Series.

required

Returns:

Name Type Description
bool bool

True if the series are equal, False otherwise.

Source code in pytest_compare/pandas/pandas.py
def compare(self, actual: ACTUAL_TYPE) -> bool:
    """Compare two series.

    Args:
        actual (pd.Series): Actual Series.

    Returns:
        bool: True if the series are equal, False otherwise.
    """
    return actual.equals(self.expected)