Skip to content

Commit

Permalink
improve coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
Joshix-1 committed Feb 27, 2023
1 parent c1e9258 commit c8ba217
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 20 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Currently only mypy is fully supported, because I couldn't get the others to wor
I'm too lazy. I don't know of anybody using this (except me) and I don't need to write changelogs for myself.
If you need changelogs, please create an issue.

### Why EUPLv1.2?
### Why EUPL-1.2-or-later?

- 🇪🇺
- [Google EUPL Policy](https://opensource.google/documentation/reference/thirdparty/licenses#european_union_public_licence_eupl_not_allowed)
Expand Down
72 changes: 71 additions & 1 deletion test/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
StreamFinishedError,
StreamIndexError,
)
from typed_stream.iteration_utils import IndexValueTuple
from typed_stream.functions import is_even, is_odd
from typed_stream.iteration_utils import IndexValueTuple, IterWithCleanUp
from typed_stream.lazy_file_iterators import LazyFileIteratorRemovingEndsBytes

from .test_functions import (
is_bool,
Expand Down Expand Up @@ -218,6 +220,10 @@ def create_int_stream() -> Stream[int]:
)
assert not hasattr(fs, "_file_iterator")

with FileStream(INPUT_TXT) as fs:
assert isinstance(next(iter(fs)), str)
assert not hasattr(fs, "_file_iterator")

fs = FileStream(INPUT_TXT)
assert fs.take_while(len).count() == 4
assert not hasattr(fs, "_file_iterator")
Expand Down Expand Up @@ -251,6 +257,24 @@ def create_int_stream() -> Stream[int]:
assert bfs.take_while(len).count() == 4
assert not hasattr(bfs, "_file_iterator")

bfs = BinaryFileStream(INPUT_TXT)
first = bfs.first()
assert not hasattr(bfs, "_file_iterator")

with BinaryFileStream(INPUT_TXT) as bfs:
assert first == next(iter(bfs))
assert not hasattr(bfs, "_file_iterator")

with LazyFileIteratorRemovingEndsBytes(INPUT_TXT) as lfireb:
assert first == next(lfireb)
assert not lfireb._file_object # pylint: disable=protected-access
lfireb.close()
assert not lfireb._file_object # pylint: disable=protected-access
lfireb = LazyFileIteratorRemovingEndsBytes(INPUT_TXT)
assert next(lfireb) == first
assert lfireb._file_object # pylint: disable=protected-access
lfireb.close()
assert not lfireb._file_object # pylint: disable=protected-access

bfs = BinaryFileStream(INPUT_TXT)
fs = FileStream(INPUT_TXT)
Expand Down Expand Up @@ -460,3 +484,49 @@ def create_int_stream() -> Stream[int]:
assert_raises(StreamFinishedError, str_stream.collect)
str_stream = Stream(())
assert_raises(StreamEmptyError, str_stream.first)

assert (
Stream("abc").map(str.upper).sum()
== Stream("abc").concurrent_map(str.upper).sum()
== "ABC"
)
int_list = []
assert (
Stream.counting(-100)
.drop(100)
.drop_while((1000).__gt__)
.take_while((100_000).__gt__)
.filter(is_odd)
.map(operator.pow, 3)
.peek(int_list.append)
.enumerate()
.flat_map(operator.mul, 2)
.exclude(is_even)
.limit(10_000)
.distinct()
.chunk(30)
.concurrent_map(sum)
.sum()
== 432028881523605
)
assert sum(int_list) == 432028878744716
assert len(int_list) - 1 == 3333

assert Stream("abc").starcollect(lambda *args: args) == ("a", "b", "c")

int_list = []
it_w_cl: IterWithCleanUp[int] = IterWithCleanUp(
Stream.counting(1), lambda: int_list.append(1)
)
assert next(it_w_cl) == 1
assert not int_list
with it_w_cl as _it:
assert next(_it) == 2
assert not int_list
assert int_list == [1]

with it_w_cl as _it:
assert not next(_it, None)
assert int_list == [1]

assert int_list == [1]
16 changes: 4 additions & 12 deletions typed_stream/common_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
PathLikeType = bytes | PathLike[bytes] | PathLike[str] | str


T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)


Expand All @@ -45,37 +46,28 @@ def __call__(self, *args: SC_IN_contra) -> SC_OUT_co:
"""Handle the arguments."""


SLT = TypeVar("SLT", bound="SupportsLessThan")


class SupportsLessThan(Protocol):
"""A class that supports comparison with less than."""

@abstractmethod
def __lt__(self: SLT, other: SLT) -> bool:
def __lt__(self: T, other: T) -> bool:
"""Compare to another instance of the same type."""


SGT = TypeVar("SGT", bound="SupportsGreaterThan")


class SupportsGreaterThan(Protocol):
"""A class that supports comparison with less than."""

@abstractmethod
def __gt__(self: SGT, other: SGT) -> bool:
def __gt__(self: T, other: T) -> bool:
"""Compare to another instance of the same type."""


SupportsComparison: TypeAlias = SupportsGreaterThan | SupportsLessThan


SA = TypeVar("SA", bound="SupportsAdd")


class SupportsAdd(Protocol):
"""A class that supports addition."""

@abstractmethod
def __add__(self: SA, other: SA) -> SA:
def __add__(self: T, other: T) -> T:
"""Add another instance of the same type to self."""
8 changes: 6 additions & 2 deletions typed_stream/iteration_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"ValueIterator",
)

T = TypeVar("T", bound=object)
T = TypeVar("T")
V = TypeVar("V")


class ValueIterator(Iterator[T], Streamable[T], Generic[T]):
Expand Down Expand Up @@ -148,6 +149,9 @@ def __init__(

def __next__(self) -> T:
"""Return the next element if available else run clean-up."""
if not hasattr(self, "iterator"):
self.close()
raise StopIteration
try:
return next(self.iterator)
except BaseException:
Expand All @@ -167,7 +171,7 @@ def __del__(self) -> None:
"""Run close."""
self.close()

def __enter__(self) -> Iterator[T]:
def __enter__(self: V) -> V:
"""Return self."""
return self

Expand Down
8 changes: 4 additions & 4 deletions typed_stream/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
Prim = TypeVar("Prim", int, str, bool, complex, Number, Real)

SA = TypeVar("SA", bound=SupportsAdd)
SLT = TypeVar("SLT", bound=SupportsComparison)
SC = TypeVar("SC", bound=SupportsComparison)


add: Callable[[SA, SA], SA] = operator.add
Expand Down Expand Up @@ -681,11 +681,11 @@ def map(
Stream(map(fun, self._data, *(ValueIterator(arg) for arg in args)))
)

def max(self: "Stream[SLT]") -> SLT:
def max(self: "Stream[SC]") -> SC:
"""Return the biggest element of the stream."""
return max(self)

def min(self: "Stream[SLT]") -> SLT:
def min(self: "Stream[SC]") -> SC:
"""Return the smallest element of the stream."""
return min(self)

Expand Down Expand Up @@ -789,7 +789,7 @@ class FileStreamBase(Stream[AnyStr]):
_file_iterator: LazyFileIterator[AnyStr]
__slots__ = ("_file_iterator",)

def __enter__(self) -> Stream[AnyStr]:
def __enter__(self: K) -> K:
"""Enter the matrix."""
return self

Expand Down

0 comments on commit c8ba217

Please sign in to comment.