| 1 | from .support import HPyTest |
| 2 | |
| 3 | class TestIter(HPyTest): |
| 4 | |
| 5 | def test_Check(self): |
| 6 | mod = self.make_module(""" |
| 7 | HPyDef_METH(f, "f", HPyFunc_O) |
| 8 | static HPy f_impl(HPyContext *ctx, HPy self, HPy arg) |
| 9 | { |
| 10 | if (HPyIter_Check(ctx, arg)) |
| 11 | return HPy_Dup(ctx, ctx->h_True); |
| 12 | return HPy_Dup(ctx, ctx->h_False); |
| 13 | } |
| 14 | @EXPORT(f) |
| 15 | @INIT |
| 16 | """) |
| 17 | |
| 18 | class CustomIterable: |
| 19 | def __init__(self): |
| 20 | self._iter = iter([1, 2, 3]) |
| 21 | |
| 22 | def __iter__(self): |
| 23 | return self._iter |
| 24 | |
| 25 | class CustomIterator: |
| 26 | def __init__(self): |
| 27 | self._iter = iter([1, 2, 3]) |
| 28 | |
| 29 | def __iter__(self): |
| 30 | return self._iter |
| 31 | |
| 32 | def __next__(self): |
| 33 | return next(self._iter) |
| 34 | |
| 35 | assert mod.f(object()) is False |
| 36 | assert mod.f(10) is False |
| 37 | |
| 38 | assert mod.f((1, 2)) is False |
| 39 | assert mod.f(iter((1, 2))) is True |
| 40 | |
| 41 | assert mod.f([]) is False |
| 42 | assert mod.f(iter([])) is True |
| 43 | |
| 44 | assert mod.f('hello') is False |
| 45 | assert mod.f(iter('hello')) is True |
| 46 | |
| 47 | assert mod.f(map(int, ("1", "2"))) is True |
| 48 | assert mod.f(range(1, 10)) is False |
| 49 | |
| 50 | assert mod.f(CustomIterable()) is False |
| 51 | assert mod.f(iter(CustomIterable())) is True |
| 52 | assert mod.f(CustomIterator()) is True |
| 53 | |
| 54 | def test_Next(self): |
| 55 | mod = self.make_module(""" |
| 56 | HPyDef_METH(f, "f", HPyFunc_O) |
| 57 | static HPy f_impl(HPyContext *ctx, HPy self, HPy arg) |
| 58 | { |
| 59 | HPy result = HPyIter_Next(ctx, arg); |
| 60 | int is_null = HPy_IsNull(result); |
| 61 | |
| 62 | if (is_null && HPyErr_Occurred(ctx)) |
| 63 | return HPy_NULL; |
| 64 | if (is_null) |
| 65 | return HPyErr_SetObject(ctx, ctx->h_StopIteration, ctx->h_None); |
| 66 | return result; |
| 67 | } |
| 68 | @EXPORT(f) |
| 69 | @INIT |
| 70 | """) |
| 71 | |
| 72 | import pytest |
| 73 | with pytest.raises(StopIteration): |
| 74 | assert mod.f(iter([])) |
| 75 | |
| 76 | class CustomIterator: |
| 77 | def __init__(self): |
| 78 | self._iter = iter(["a", "b", "c"]) |
| 79 | |
| 80 | def __iter__(self): |
| 81 | return self._iter |
| 82 | |
| 83 | def __next__(self): |
| 84 | return next(self._iter) |
| 85 | |
| 86 | assert mod.f(iter([3, 2, 1])) == 3 |
| 87 | assert mod.f((i for i in range(1, 10))) == 1 |
| 88 | assert mod.f(CustomIterator()) == "a" |