/_python_utils_tests/test_generators.py

https://github.com/WoLpH/python-utils · Python · 67 lines · 43 code · 20 blank · 4 comment · 7 complexity · e3831c5c54fc4b10c4e16ccd52c5b360 MD5 · raw file

  1. import asyncio
  2. import pytest
  3. import python_utils
  4. @pytest.mark.asyncio
  5. async def test_abatcher():
  6. async for batch in python_utils.abatcher(python_utils.acount(stop=9), 3):
  7. assert len(batch) == 3
  8. async for batch in python_utils.abatcher(python_utils.acount(stop=2), 3):
  9. assert len(batch) == 2
  10. @pytest.mark.asyncio
  11. async def test_abatcher_timed():
  12. batches = []
  13. async for batch in python_utils.abatcher(
  14. python_utils.acount(stop=10, delay=0.08), interval=0.1
  15. ):
  16. batches.append(batch)
  17. assert batches == [[0, 1, 2], [3, 4], [5, 6], [7, 8], [9]]
  18. assert len(batches) == 5
  19. @pytest.mark.asyncio
  20. async def test_abatcher_timed_with_timeout():
  21. async def generator():
  22. # Test if the timeout is respected
  23. yield 0
  24. yield 1
  25. await asyncio.sleep(0.11)
  26. # Test if the timeout is respected
  27. yield 2
  28. yield 3
  29. await asyncio.sleep(0.11)
  30. # Test if exceptions are handled correctly
  31. await asyncio.wait_for(asyncio.sleep(1), timeout=0.05)
  32. # Test if StopAsyncIteration is handled correctly
  33. yield 4
  34. batcher = python_utils.abatcher(generator(), interval=0.1)
  35. assert await batcher.__anext__() == [0, 1]
  36. assert await batcher.__anext__() == [2, 3]
  37. with pytest.raises(asyncio.TimeoutError):
  38. await batcher.__anext__()
  39. with pytest.raises(StopAsyncIteration):
  40. await batcher.__anext__()
  41. def test_batcher():
  42. batch = []
  43. for batch in python_utils.batcher(range(9), 3):
  44. assert len(batch) == 3
  45. for batch in python_utils.batcher(range(4), 3):
  46. pass
  47. assert len(batch) == 1