Skip to content

Commit b0df5d5

Browse files
committed
tests: Add utility to compare sequences
This is useful if you want to check if some function was called with a sequence, without caring about the concrete underlying type, so the implementation can change and tests don't need to be updated as long as the interface stays the same. For example: mock.assert_called_once_with(a_sequence(1, 2, 3)) Signed-off-by: Leandro Lucarella <[email protected]>
1 parent cba1b7e commit b0df5d5

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

tests/utils/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,9 @@
22
# Copyright © 2022 Frequenz Energy-as-a-Service GmbH
33

44
"""Utilities for testing purposes."""
5+
6+
from ._a_sequence import a_sequence
7+
8+
__all__ = [
9+
"a_sequence",
10+
]

tests/utils/_a_sequence.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# tests/timeseries/test_resampling.py:93: License: MIT
2+
# Copyright © 2022 Frequenz Energy-as-a-Service GmbH
3+
4+
"""Helper class to compare two sequences without caring about the underlying type."""
5+
6+
from __future__ import annotations
7+
8+
from collections.abc import Sequence
9+
from typing import Any
10+
11+
12+
# Disabling the lint because it reads easier in tests like this
13+
class a_sequence: # pylint: disable=invalid-name
14+
"""Helper class to compare two sequences without caring about the underlying type.
15+
16+
Examples:
17+
>>> from collections import deque
18+
>>> (1, 2) == a_sequence(1, 2)
19+
>>> True
20+
>>> deque([1, 2]) == a_sequence(1, 2)
21+
>>> True
22+
>>> deque([2, 1]) == a_sequence(1, 2)
23+
>>> False
24+
>>> 1 == a_sequence(1, 2)
25+
>>> False
26+
"""
27+
28+
def __init__(self, *sequence: Any) -> None:
29+
"""Create an instance."""
30+
self.sequence: Sequence[Any] = sequence
31+
32+
def __eq__(self, other: Any) -> bool:
33+
"""# noqa D105 (Missing docstring in magic method)."""
34+
if not isinstance(other, Sequence):
35+
return False
36+
return list(self.sequence) == list(other)
37+
38+
def __str__(self) -> str:
39+
"""# noqa D105 (Missing docstring in magic method)."""
40+
return f"{self.__class__.__name__}({', '.join(str(s) for s in self.sequence)})"
41+
42+
def __repr__(self) -> str:
43+
"""# noqa D105 (Missing docstring in magic method)."""
44+
return f"{self.__class__.__name__}({', '.join(repr(s) for s in self.sequence)})"

0 commit comments

Comments
 (0)