conftest.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """
  2. Integration test fixtures - Hardware detection and setup.
  3. These fixtures help determine if real hardware is available
  4. and provide setup/teardown for hardware-dependent tests.
  5. """
  6. import pytest
  7. import serial.tools.list_ports
  8. def pytest_addoption(parser):
  9. """Add --run-hardware option to pytest CLI."""
  10. parser.addoption(
  11. "--run-hardware",
  12. action="store_true",
  13. default=False,
  14. help="Run tests that require real hardware connection"
  15. )
  16. @pytest.fixture
  17. def run_hardware(request):
  18. """Check if hardware tests should run."""
  19. return request.config.getoption("--run-hardware")
  20. @pytest.fixture
  21. def available_serial_ports():
  22. """Return list of available serial ports on this machine.
  23. Filters out known non-hardware ports like debug consoles.
  24. """
  25. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  26. ports = serial.tools.list_ports.comports()
  27. return [port.device for port in ports if port.device not in IGNORE_PORTS]
  28. @pytest.fixture
  29. def hardware_port(available_serial_ports, run_hardware):
  30. """Get a hardware port for testing, or skip if not available.
  31. This fixture:
  32. 1. Checks if --run-hardware flag was passed
  33. 2. Checks if any serial ports are available
  34. 3. Returns the first available port or skips the test
  35. """
  36. if not run_hardware:
  37. pytest.skip("Hardware tests disabled (use --run-hardware to enable)")
  38. if not available_serial_ports:
  39. pytest.skip("No serial ports available for hardware testing")
  40. # Prefer USB ports over built-in ports
  41. usb_ports = [p for p in available_serial_ports if 'usb' in p.lower() or 'USB' in p]
  42. if usb_ports:
  43. return usb_ports[0]
  44. return available_serial_ports[0]
  45. @pytest.fixture
  46. def serial_connection(hardware_port):
  47. """Create a real serial connection for testing.
  48. This fixture establishes an actual serial connection to the hardware.
  49. The connection is automatically closed after the test.
  50. """
  51. import serial
  52. conn = serial.Serial(hardware_port, baudrate=115200, timeout=2)
  53. yield conn
  54. conn.close()