pytest_plugin.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Fixtures for use with jupyter events."""
  2. from __future__ import annotations
  3. import io
  4. import json
  5. import logging
  6. from typing import Any, Callable
  7. import pytest
  8. from jupyter_events import EventLogger
  9. @pytest.fixture
  10. def jp_event_sink() -> io.StringIO:
  11. """A stream for capture events."""
  12. return io.StringIO()
  13. @pytest.fixture
  14. def jp_event_handler(jp_event_sink: io.StringIO) -> logging.Handler:
  15. """A logging handler that captures any events emitted by the event handler"""
  16. return logging.StreamHandler(jp_event_sink)
  17. @pytest.fixture
  18. def jp_read_emitted_events(
  19. jp_event_handler: logging.Handler, jp_event_sink: io.StringIO
  20. ) -> Callable[..., list[str] | None]:
  21. """Reads list of events since last time it was called."""
  22. def _read() -> list[str] | None:
  23. jp_event_handler.flush()
  24. event_buf = jp_event_sink.getvalue().strip()
  25. output = [json.loads(item) for item in event_buf.split("\n")] if event_buf else None
  26. # Clear the sink.
  27. jp_event_sink.truncate(0)
  28. jp_event_sink.seek(0)
  29. return output
  30. return _read
  31. @pytest.fixture
  32. def jp_event_schemas() -> list[Any]:
  33. """A list of schema references.
  34. Each item should be one of the following:
  35. - string of serialized JSON/YAML content representing a schema
  36. - a pathlib.Path object pointing to a schema file on disk
  37. - a dictionary with the schema data.
  38. """
  39. return []
  40. @pytest.fixture
  41. def jp_event_logger(jp_event_handler: logging.Handler, jp_event_schemas: list[Any]) -> EventLogger:
  42. """A pre-configured event logger for tests."""
  43. logger = EventLogger()
  44. for schema in jp_event_schemas:
  45. logger.register_event_schema(schema)
  46. logger.register_handler(handler=jp_event_handler)
  47. return logger