|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +# Track whether we started the bridge ourselves |
| 6 | +_bridge_started_by_tests = False |
| 7 | +_bridge_port = None |
| 8 | + |
| 9 | + |
| 10 | +@pytest.fixture(scope="session", autouse=True) |
| 11 | +def manage_genius_bridge(): |
| 12 | + """ |
| 13 | + Manage Genius bridge for the test session. |
| 14 | +
|
| 15 | + - If bridge is installed and not running, start it |
| 16 | + - Only stop the bridge after tests if we started it ourselves |
| 17 | + """ |
| 18 | + global _bridge_started_by_tests, _bridge_port |
| 19 | + |
| 20 | + try: |
| 21 | + from negmas.genius.bridge import ( |
| 22 | + GeniusBridge, |
| 23 | + genius_bridge_is_installed, |
| 24 | + genius_bridge_is_running, |
| 25 | + ) |
| 26 | + from negmas.genius.common import DEFAULT_JAVA_PORT |
| 27 | + |
| 28 | + _bridge_port = DEFAULT_JAVA_PORT |
| 29 | + |
| 30 | + # Check if bridge is installed |
| 31 | + if not genius_bridge_is_installed(): |
| 32 | + # Bridge not installed, nothing to do |
| 33 | + yield |
| 34 | + return |
| 35 | + |
| 36 | + # Check if bridge is already running |
| 37 | + if genius_bridge_is_running(_bridge_port): |
| 38 | + # Bridge already running, don't touch it |
| 39 | + _bridge_started_by_tests = False |
| 40 | + yield |
| 41 | + return |
| 42 | + |
| 43 | + # Bridge is installed but not running - start it |
| 44 | + try: |
| 45 | + GeniusBridge.start(port=_bridge_port) |
| 46 | + _bridge_started_by_tests = True |
| 47 | + except Exception: |
| 48 | + # Failed to start, continue anyway (tests will be skipped) |
| 49 | + _bridge_started_by_tests = False |
| 50 | + |
| 51 | + yield |
| 52 | + |
| 53 | + # Cleanup: only stop if we started it |
| 54 | + if _bridge_started_by_tests: |
| 55 | + try: |
| 56 | + GeniusBridge.stop(port=_bridge_port) |
| 57 | + except Exception: |
| 58 | + pass |
| 59 | + except ImportError: |
| 60 | + # py4j or other dependencies not available |
| 61 | + yield |
| 62 | + |
| 63 | + |
| 64 | +@pytest.fixture(autouse=True) |
| 65 | +def cleanup_after_each_test(): |
| 66 | + """Clean up agents after each test to prevent resource leaks.""" |
| 67 | + yield |
| 68 | + try: |
| 69 | + from negmas.genius.bridge import GeniusBridge |
| 70 | + |
| 71 | + # Just clean agents, don't stop the bridge |
| 72 | + GeniusBridge.clean_all() |
| 73 | + except Exception: |
| 74 | + pass |
0 commit comments