Pytest assertion fails using generator expression, but passes when run without Pytest

Viewed 22

I'm using Python 3.10.6, and have checked that Pytest (version 7.1.3) is also using Python 3.10.6. I have a function that returns a generator expression, and a function for testing:


def powers(*, base, limit) -> int:
    """
    Given a base and a limit, return a generator that yields all powers of the base where the exponent has a range of [0, limit).
    """
    return (base ** exponent for exponent in range(limit))

def test_powers():
    p = powers(base=2, limit=10)
    assert next(p) == 1
    assert next(p) == 2
    assert next(p) == 4
    assert next(p) == 8

When I call powers running python3 and run the assert statements from test_powers, everything passes. But when I run pytest powers_test.py::test_powers, I get this output:

================================================================ FAILURES =================================================================
_______________________________________________________________ test_powers _______________________________________________________________

    def test_powers():
        p = powers(base=2, limit=10)
>       assert next(p) == 1
E       StopIteration: <generator object powers.<locals>.<genexpr> at 0x10ae0ba00>

python/tests/exercises_test.py:48: StopIteration
========================================================= short test summary info =========================================================
FAILED python/tests/exercises_test.py::test_powers - StopIteration: <generator object powers.<locals>.<genexpr> at 0x10ae0ba00>
============================================================ 1 failed in 0.17s ============================================================

0 Answers
Related