diff --git a/packages/service/ni_measurement_plugin_sdk_service/discovery/_support.py b/packages/service/ni_measurement_plugin_sdk_service/discovery/_support.py index 355a7a2b6..92db546f0 100644 --- a/packages/service/ni_measurement_plugin_sdk_service/discovery/_support.py +++ b/packages/service/ni_measurement_plugin_sdk_service/discovery/_support.py @@ -22,6 +22,7 @@ import win32con import win32file + from win32com.shell import shell, shellcon _logger = logging.getLogger(__name__) # Save Popen object to avoid "ResourceWarning: subprocess N is still running" @@ -30,24 +31,154 @@ _START_SERVICE_TIMEOUT = 30.0 _START_SERVICE_POLLING_INTERVAL = 100e-3 +_DISCOVERY_SERVICE_ADDRESS_ENV_VAR = "DISCOVERY_SERVICE_ADDRESS" +_DISCOVERY_SERVICE_ENV_VAR_PREFIX = "NIDiscovery_" +_DISCOVERY_SERVICE_CLUSTER_ID_ENV_VAR = "ClusterId" + +# Discovery Service versions that run a per-user instance record the publishing process in every key +# file they write, including the machine-wide compatibility key file. +_KEY_FILE_PROCESS_ID_PROPERTY = "ProcessId" + def _get_discovery_service_address() -> str: - key_file_path = _get_key_file_path() - _ensure_discovery_service_started(key_file_path) + """Gets the address of the Discovery Service, starting it if necessary. + + The Discovery Service is resolved in this order: + + 1. The ``DISCOVERY_SERVICE_ADDRESS`` environment variable, which the Discovery Service sets + for the services it launches. + 2. The key file for the cluster selected by the ``NIDiscovery_ClusterId`` or ``ClusterId`` + environment variable, if any. + 3. The current user's key file. On Windows, each user runs their own Discovery Service and + publishes its key file under ``%LOCALAPPDATA%``. + 4. The machine-wide key file under ``%ProgramData%``, which older Discovery Service versions + publish and newer versions publish only in compatibility mode. A compatibility-mode key file + may belong to another user's instance, so it is used only if this user's own instance does + not start. + + If no Discovery Service is running, this starts one and waits for it to publish a key file. + """ + address = _get_discovery_service_address_from_environment() + if address is not None: + _logger.debug( + "Discovery service address from %s: %s", _DISCOVERY_SERVICE_ADDRESS_ENV_VAR, address + ) + return address + + key_file_path = _ensure_discovery_service_started(_get_cluster_id()) _logger.debug("Discovery service key file path: %s", key_file_path) + return _read_discovery_service_address(key_file_path) + + +def _get_discovery_service_address_from_environment() -> str | None: + address = os.environ.get(_DISCOVERY_SERVICE_ADDRESS_ENV_VAR, "").strip() + if not address: + return None + host, separator, port = address.rpartition(":") + if not separator or not host or not port.isdigit() or not 0 < int(port) <= 65535: + raise ValueError( + f"The {_DISCOVERY_SERVICE_ADDRESS_ENV_VAR} environment variable must be a host:port " + f"address, not {address!r}." + ) + return address + + +def _get_cluster_id() -> str | None: + # To support operating systems other than Windows (and match Discovery Service behavior), + # we would likely want to make this check case-insensitive. + cluster_id = os.environ.get( + _DISCOVERY_SERVICE_ENV_VAR_PREFIX + _DISCOVERY_SERVICE_CLUSTER_ID_ENV_VAR + ) + if not cluster_id: + cluster_id = os.environ.get(_DISCOVERY_SERVICE_CLUSTER_ID_ENV_VAR) + # Like the Discovery Service, treat an empty cluster ID as the default instance. + return cluster_id or None + + +def _read_discovery_service_address(key_file_path: pathlib.Path) -> str: with _open_key_file(str(key_file_path)) as key_file: key_json = json.load(key_file) - return "localhost:" + key_json["InsecurePort"] + return "localhost:" + str(key_json["InsecurePort"]) -def _ensure_discovery_service_started(key_file_path: pathlib.Path) -> None: - """Check whether discovery service already running, if not start the discovery service.""" - if _service_already_running(key_file_path): - return +def _ensure_discovery_service_started(cluster_id: str | None = None) -> pathlib.Path: + """Finds the key file of a running Discovery Service, starting the service if necessary.""" + key_file_path = _find_running_key_file(cluster_id) + if key_file_path is not None: + return key_file_path exe_file_path = _get_discovery_service_location() global _discovery_service_subprocess # save Popen object to avoid ResourceWarning - _discovery_service_subprocess = _start_service(exe_file_path, key_file_path) + _discovery_service_subprocess = _launch_service(exe_file_path) + return _wait_for_started_key_file(cluster_id) + + +def _find_running_key_file(cluster_id: str | None) -> pathlib.Path | None: + key_file_path = _get_key_file_path(cluster_id) + if _service_already_running(key_file_path): + return key_file_path + + # A machine-wide key file written by a per-user Discovery Service belongs to whichever user's + # instance claimed compatibility mode, which may be another user's. Prefer starting this + # user's own instance, and use that key file only as a last resort. + legacy_key_file_path = _get_legacy_key_file_path(cluster_id) + if ( + legacy_key_file_path is not None + and _service_already_running(legacy_key_file_path) + and not _is_written_by_per_user_service(legacy_key_file_path) + ): + return legacy_key_file_path + return None + + +def _wait_for_started_key_file(cluster_id: str | None) -> pathlib.Path: + """Waits for a newly started Discovery Service to publish its key file.""" + return _wait_for_key_file(_get_key_file_path(cluster_id), _get_legacy_key_file_path(cluster_id)) + + +def _wait_for_key_file( + key_file_path: pathlib.Path, legacy_key_file_path: pathlib.Path | None +) -> pathlib.Path: + timeout_time = time.time() + _START_SERVICE_TIMEOUT + while True: + if _can_open_key_file(key_file_path): + return key_file_path + # An older Discovery Service publishes only the machine-wide key file. + if ( + legacy_key_file_path is not None + and _can_open_key_file(legacy_key_file_path) + and not _is_written_by_per_user_service(legacy_key_file_path) + ): + return legacy_key_file_path + if time.time() >= timeout_time: + break + time.sleep(_START_SERVICE_POLLING_INTERVAL) + + if legacy_key_file_path is not None and _can_open_key_file(legacy_key_file_path): + _logger.warning( + "Timed out waiting for this user's discovery service to start. Using the " + "compatibility-mode discovery service from %s, which may belong to another user.", + legacy_key_file_path, + ) + return legacy_key_file_path + raise TimeoutError("Timed out waiting for discovery service to start") + + +def _can_open_key_file(key_file_path: pathlib.Path) -> bool: + try: + with _open_key_file(str(key_file_path)) as _: + return True + except OSError: + return False + + +def _is_written_by_per_user_service(key_file_path: pathlib.Path) -> bool: + try: + with _open_key_file(str(key_file_path)) as key_file: + key_json = json.load(key_file) + except (OSError, ValueError): + return False + return isinstance(key_json, dict) and _KEY_FILE_PROCESS_ID_PROPERTY in key_json def _get_discovery_service_location() -> pathlib.PurePath: @@ -77,13 +208,30 @@ def _start_service( exe_file_path: pathlib.PurePath, key_file_path: pathlib.Path ) -> subprocess.Popen: """Starts the service at the specified path and wait for the service to get up and running.""" + discovery_service_subprocess = _launch_service(exe_file_path) + _wait_for_key_file(key_file_path, _get_legacy_counterpart(key_file_path)) + return discovery_service_subprocess + + +def _get_legacy_counterpart(key_file_path: pathlib.Path) -> pathlib.Path | None: + """Gets the machine-wide key file that an older Discovery Service publishes instead.""" + try: + if key_file_path.parent != _get_key_file_directory(): + return None + return _get_legacy_key_file_directory() / key_file_path.name + except (NotImplementedError, OSError): + return None + + +def _launch_service(exe_file_path: pathlib.PurePath) -> subprocess.Popen: + """Starts the service at the specified path without waiting for it to publish a key file.""" kwargs: dict[str, Any] = {} if sys.platform == "win32": # Terminating the measurement service should not terminate the discovery service. kwargs["creationflags"] = subprocess.CREATE_BREAKAWAY_FROM_JOB | subprocess.DETACHED_PROCESS # The EXE file path comes from the registration JSON, which is installed in # a trusted location (e.g. NISHAREDDIR64). - discovery_service_subprocess = subprocess.Popen( # nosec: B603 + return subprocess.Popen( # nosec: B603 [exe_file_path], cwd=exe_file_path.parent, stdin=subprocess.DEVNULL, @@ -91,18 +239,6 @@ def _start_service( stderr=subprocess.DEVNULL, **kwargs, ) - # After the execution of process, check for key file existence in the path - # stop checking after 30 seconds have elapsed and throw error - timeout_time = time.time() + _START_SERVICE_TIMEOUT - while True: - try: - with _open_key_file(str(key_file_path)) as _: - return discovery_service_subprocess - except OSError: - pass - if time.time() >= timeout_time: - raise TimeoutError("Timed out waiting for discovery service to start") - time.sleep(_START_SERVICE_POLLING_INTERVAL) def _service_already_running(key_file_path: pathlib.Path) -> bool: @@ -121,19 +257,57 @@ def _delete_existing_key_file(key_file_path: pathlib.Path) -> None: def _get_key_file_path(cluster_id: str | None = None) -> pathlib.Path: - if cluster_id is not None: - return _get_key_file_directory() / f"DiscoveryService_{cluster_id}.json" - return _get_key_file_directory() / "DiscoveryService.json" + """Gets the path of the key file that the current user's Discovery Service publishes.""" + return _get_key_file_directory() / _get_key_file_name(cluster_id) + + +def _get_legacy_key_file_path(cluster_id: str | None = None) -> pathlib.Path | None: + """Gets the path of the machine-wide key file, or None if there isn't one.""" + try: + return _get_legacy_key_file_directory() / _get_key_file_name(cluster_id) + except (NotImplementedError, OSError): + # The machine-wide key file exists only on Windows, and NIPUBAPPDATADIR may be missing, + # for example when no NI installer has run. + return None + + +def _get_key_file_name(cluster_id: str | None) -> str: + if cluster_id: + return f"DiscoveryService_{cluster_id}.json" + return "DiscoveryService.json" def _get_key_file_directory() -> pathlib.Path: - version = discovery_service_pb2.DESCRIPTOR.package.split(".")[-1] + """Gets the current user's key file directory. + + On Windows, each user runs their own Discovery Service, which publishes its key files under + %LOCALAPPDATA% rather than the machine-wide %ProgramData% directory that every user can write. + """ + if sys.platform == "win32": + local_app_data = pathlib.Path(shell.SHGetKnownFolderPath(shellcon.FOLDERID_LocalAppData)) + return ( + local_app_data + / "National Instruments" + / "MeasurementLink" + / "Discovery" + / _get_version() + ) + else: + raise NotImplementedError("Platform not supported") + + +def _get_legacy_key_file_directory() -> pathlib.Path: + """Gets the machine-wide key file directory used by older Discovery Service versions.""" if sys.platform == "win32": - return _get_nipath("NIPUBAPPDATADIR") / "MeasurementLink" / "Discovery" / version + return _get_nipath("NIPUBAPPDATADIR") / "MeasurementLink" / "Discovery" / _get_version() else: raise NotImplementedError("Platform not supported") +def _get_version() -> str: + return discovery_service_pb2.DESCRIPTOR.package.split(".")[-1] + + def _open_key_file(path: str) -> typing.TextIO: if sys.platform == "win32": # Use the Win32 API to specify the share mode. Otherwise, opening the file throws diff --git a/packages/service/tests/unit/test_discovery_client.py b/packages/service/tests/unit/test_discovery_client.py index 81ed4de70..27531da5c 100644 --- a/packages/service/tests/unit/test_discovery_client.py +++ b/packages/service/tests/unit/test_discovery_client.py @@ -37,6 +37,7 @@ from ni_measurement_plugin_sdk_service.discovery import DiscoveryClient, ServiceLocation from ni_measurement_plugin_sdk_service.discovery._support import ( _get_discovery_service_address, + _get_legacy_key_file_path, _open_key_file, _start_service, ) @@ -309,6 +310,17 @@ def test___key_file_not_exist___open_key_file___raises_file_not_found_error( _open_key_file(str(temp_discovery_key_file_path)) +def test___platform_without_machine_wide_key_file___get_legacy_key_file_path___returns_none( + mocker: MockerFixture, +) -> None: + mocker.patch( + "ni_measurement_plugin_sdk_service.discovery._support._get_legacy_key_file_directory", + side_effect=NotImplementedError("Platform not supported"), + ) + + assert _get_legacy_key_file_path() is None + + def test___key_file_exist_after_poll___start_discovery_service___discovery_service_started( mocker: MockerFixture, temp_directory: pathlib.Path, diff --git a/packages/service/tests/unit/test_discovery_service_resolution.py b/packages/service/tests/unit/test_discovery_service_resolution.py new file mode 100644 index 000000000..41a0267d6 --- /dev/null +++ b/packages/service/tests/unit/test_discovery_service_resolution.py @@ -0,0 +1,399 @@ +"""Tests for resolving the Discovery Service address.""" + +from __future__ import annotations + +import json +import os +import pathlib +import sys +from collections.abc import Generator +from typing import Any +from unittest.mock import Mock + +import pytest +from pytest_mock import MockerFixture + +from ni_measurement_plugin_sdk_service.discovery._support import ( + _get_discovery_service_address, + _get_key_file_directory, + _get_key_file_path, + _get_legacy_key_file_directory, + _start_service, +) + +if sys.platform == "win32": + import win32con + import win32file + +pytestmark = pytest.mark.skipif( + sys.platform != "win32", reason="Discovery Service key files are only supported on Windows." +) + +_SUPPORT_MODULE = "ni_measurement_plugin_sdk_service.discovery._support" +_UTF8_BOM = b"\xef\xbb\xbf" +_REGISTRATION_FILE_CONTENT = {"discovery": {"path": "Discovery/NI.Discovery.V1.Service.exe"}} + + +class _KeyFilePublisher: + """Publishes key files the way the Discovery Service does. + + The Discovery Service writes key files with a UTF-8 byte order mark and keeps them open without + write sharing, which is how clients tell a running instance from a stale key file. + """ + + def __init__(self) -> None: + self._handles: list[Any] = [] + + def publish( + self, + path: pathlib.Path, + insecure_port: str, + *, + per_user_service: bool = True, + bom: bool = True, + ) -> None: + content: dict[str, Any] = { + "InsecurePort": insecure_port, + "SecurePort": "", + "Http1ProxyPort": "1", + } + if per_user_service: + content.update({"ProcessId": 1234, "StartTime": "2026-11-17T18:00:00.0000000Z"}) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes((_UTF8_BOM if bom else b"") + json.dumps(content).encode()) + if sys.platform == "win32": + self._handles.append( + win32file.CreateFile( + str(path), + win32file.GENERIC_READ, + win32file.FILE_SHARE_READ | win32file.FILE_SHARE_DELETE, + None, + win32con.OPEN_EXISTING, + 0, + None, + ) + ) + else: + pytest.skip("Windows-only test") + + def close(self) -> None: + for handle in self._handles: + handle.Close() + self._handles.clear() + + +@pytest.fixture +def key_files() -> Generator[_KeyFilePublisher, None, None]: + publisher = _KeyFilePublisher() + yield publisher + publisher.close() + + +@pytest.fixture +def per_user_directory(tmp_path: pathlib.Path, mocker: MockerFixture) -> pathlib.Path: + directory = tmp_path / "LocalAppData" / "Discovery" / "v1" + mocker.patch(f"{_SUPPORT_MODULE}._get_key_file_directory", return_value=directory) + return directory + + +@pytest.fixture +def legacy_directory(tmp_path: pathlib.Path, mocker: MockerFixture) -> pathlib.Path: + directory = tmp_path / "ProgramData" / "Discovery" / "v1" + mocker.patch(f"{_SUPPORT_MODULE}._get_legacy_key_file_directory", return_value=directory) + return directory + + +@pytest.fixture(autouse=True) +def discovery_environment(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch: + for name in ("DISCOVERY_SERVICE_ADDRESS", "NIDiscovery_ClusterId", "ClusterId"): + monkeypatch.delenv(name, raising=False) + return monkeypatch + + +@pytest.fixture +def mock_popen(mocker: MockerFixture, tmp_path: pathlib.Path) -> Mock: + registration_json_path = tmp_path / "NIServices.json" + registration_json_path.write_text(json.dumps(_REGISTRATION_FILE_CONTENT)) + mocker.patch( + f"{_SUPPORT_MODULE}._get_registration_json_file_path", + return_value=registration_json_path, + ) + return mocker.patch("subprocess.Popen") + + +def test___address_environment_variable_set___get_discovery_service_address___returns_environment_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + discovery_environment: pytest.MonkeyPatch, + mock_popen: Mock, +) -> None: + discovery_environment.setenv("DISCOVERY_SERVICE_ADDRESS", "localhost:50000") + discovery_environment.setenv("NIDiscovery_ClusterId", "cluster") + key_files.publish(per_user_directory / "DiscoveryService_cluster.json", "50001") + key_files.publish(per_user_directory / "DiscoveryService.json", "50002") + key_files.publish(legacy_directory / "DiscoveryService.json", "42000", per_user_service=False) + + address = _get_discovery_service_address() + + assert address == "localhost:50000" + mock_popen.assert_not_called() + + +@pytest.mark.parametrize("address", ["localhost", "localhost:", ":42000", "localhost:port"]) +def test___invalid_address_environment_variable___get_discovery_service_address___raises_value_error( + discovery_environment: pytest.MonkeyPatch, address: str +) -> None: + discovery_environment.setenv("DISCOVERY_SERVICE_ADDRESS", address) + + with pytest.raises(ValueError, match="DISCOVERY_SERVICE_ADDRESS"): + _get_discovery_service_address() + + +@pytest.mark.parametrize("cluster_id_env_var", ["NIDiscovery_ClusterId", "ClusterId"]) +def test___cluster_selected___get_discovery_service_address___returns_cluster_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + discovery_environment: pytest.MonkeyPatch, + mock_popen: Mock, + cluster_id_env_var: str, +) -> None: + discovery_environment.setenv(cluster_id_env_var, "cluster") + key_files.publish(per_user_directory / "DiscoveryService_cluster.json", "50001") + key_files.publish(per_user_directory / "DiscoveryService.json", "50002") + key_files.publish(legacy_directory / "DiscoveryService.json", "42000", per_user_service=False) + + address = _get_discovery_service_address() + + assert address == "localhost:50001" + mock_popen.assert_not_called() + + +def test___cluster_selected_with_older_discovery_service___get_discovery_service_address___returns_legacy_cluster_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + discovery_environment: pytest.MonkeyPatch, + mock_popen: Mock, +) -> None: + discovery_environment.setenv("NIDiscovery_ClusterId", "cluster") + key_files.publish(per_user_directory / "DiscoveryService.json", "50002") + key_files.publish( + legacy_directory / "DiscoveryService_cluster.json", "50003", per_user_service=False + ) + + address = _get_discovery_service_address() + + assert address == "localhost:50003" + mock_popen.assert_not_called() + + +def test___empty_cluster_id___get_discovery_service_address___returns_per_user_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + discovery_environment: pytest.MonkeyPatch, + mock_popen: Mock, +) -> None: + discovery_environment.setenv("ClusterId", "") + key_files.publish(per_user_directory / "DiscoveryService.json", "50002") + + address = _get_discovery_service_address() + + assert address == "localhost:50002" + mock_popen.assert_not_called() + + +def test___per_user_and_legacy_key_files___get_discovery_service_address___returns_per_user_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, +) -> None: + key_files.publish(per_user_directory / "DiscoveryService.json", "50002") + key_files.publish(legacy_directory / "DiscoveryService.json", "42000") + + address = _get_discovery_service_address() + + assert address == "localhost:50002" + mock_popen.assert_not_called() + + +@pytest.mark.parametrize("bom", [True, False]) +def test___older_discovery_service_running___get_discovery_service_address___returns_legacy_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, + bom: bool, +) -> None: + key_files.publish( + legacy_directory / "DiscoveryService.json", "42000", per_user_service=False, bom=bom + ) + + address = _get_discovery_service_address() + + assert address == "localhost:42000" + mock_popen.assert_not_called() + + +def test___key_file_with_bom_and_extra_fields___get_discovery_service_address___returns_insecure_port( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + mocker: MockerFixture, +) -> None: + per_user_directory.mkdir(parents=True) + key_file_path = per_user_directory / "DiscoveryService.json" + key_file_path.write_bytes( + _UTF8_BOM + + b'{"InsecurePort":"50002","SecurePort":"50004","Http1ProxyPort":"50005",' + + b'"ProcessId":1234,"StartTime":"2026-11-17T18:00:00.0000000Z","Unknown":{"a":[1]}}' + ) + mocker.patch(f"{_SUPPORT_MODULE}._service_already_running", return_value=True) + + address = _get_discovery_service_address() + + assert address == "localhost:50002" + + +def test___only_another_users_compatibility_key_file___get_discovery_service_address___starts_and_returns_per_user_service( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, +) -> None: + key_files.publish(legacy_directory / "DiscoveryService.json", "42000") + mock_popen.side_effect = lambda *args, **kwargs: key_files.publish( + per_user_directory / "DiscoveryService.json", "50002" + ) + + address = _get_discovery_service_address() + + assert address == "localhost:50002" + mock_popen.assert_called_once() + + +def test___no_key_files_and_older_discovery_service_installed___get_discovery_service_address___starts_and_returns_legacy_service( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, +) -> None: + mock_popen.side_effect = lambda *args, **kwargs: key_files.publish( + legacy_directory / "DiscoveryService.json", "42000", per_user_service=False + ) + + address = _get_discovery_service_address() + + assert address == "localhost:42000" + mock_popen.assert_called_once() + + +def test___per_user_service_never_starts_with_compatibility_key_file___get_discovery_service_address___returns_compatibility_address( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, + mocker: MockerFixture, + caplog: pytest.LogCaptureFixture, +) -> None: + mocker.patch(f"{_SUPPORT_MODULE}._START_SERVICE_TIMEOUT", 0.3) + key_files.publish(legacy_directory / "DiscoveryService.json", "42000") + + address = _get_discovery_service_address() + + assert address == "localhost:42000" + mock_popen.assert_called_once() + assert "compatibility-mode discovery service" in caplog.text + + +def test___stale_key_files___get_discovery_service_address___deletes_them_and_starts_service( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, +) -> None: + per_user_directory.mkdir(parents=True) + legacy_directory.mkdir(parents=True) + stale_per_user_key_file = per_user_directory / "DiscoveryService.json" + stale_legacy_key_file = legacy_directory / "DiscoveryService.json" + stale_per_user_key_file.write_text('{"InsecurePort": "1"}') + stale_legacy_key_file.write_text('{"InsecurePort": "2"}') + + def start_service(*args: Any, **kwargs: Any) -> None: + # Publishing fails if the client left the stale key file in place. + assert not stale_per_user_key_file.exists() + assert not stale_legacy_key_file.exists() + key_files.publish(stale_per_user_key_file, "50002") + + mock_popen.side_effect = start_service + + address = _get_discovery_service_address() + + assert address == "localhost:50002" + mock_popen.assert_called_once() + + +def test___legacy_directory_unavailable___get_discovery_service_address___starts_and_returns_per_user_service( + per_user_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, + mocker: MockerFixture, +) -> None: + mocker.patch(f"{_SUPPORT_MODULE}._get_nipath", side_effect=FileNotFoundError) + mock_popen.side_effect = lambda *args, **kwargs: key_files.publish( + per_user_directory / "DiscoveryService.json", "50002" + ) + + address = _get_discovery_service_address() + + assert address == "localhost:50002" + + +def test___older_discovery_service___start_service_with_per_user_key_file_path___waits_for_legacy_key_file( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + key_files: _KeyFilePublisher, + mock_popen: Mock, + tmp_path: pathlib.Path, +) -> None: + # Test utilities in dependent packages pair _get_key_file_path() with _start_service(). + mock_popen.side_effect = lambda *args, **kwargs: key_files.publish( + legacy_directory / "DiscoveryService.json", "42000", per_user_service=False + ) + + _start_service(tmp_path / "Discovery" / "NI.Discovery.V1.Service.exe", _get_key_file_path()) + + mock_popen.assert_called_once() + + +def test___windows___get_key_file_directories___returns_per_user_and_machine_wide_directories( + mocker: MockerFixture, +) -> None: + mocker.patch( + f"{_SUPPORT_MODULE}._get_nipath", + return_value=pathlib.Path(r"C:\ProgramData\National Instruments"), + ) + + per_user_directory = _get_key_file_directory() + legacy_directory = _get_legacy_key_file_directory() + + assert per_user_directory == pathlib.Path( + os.environ["LOCALAPPDATA"], "National Instruments", "MeasurementLink", "Discovery", "v1" + ) + assert legacy_directory == pathlib.Path( + r"C:\ProgramData\National Instruments\MeasurementLink\Discovery\v1" + ) + + +def test___no_discovery_service_starts___get_discovery_service_address___raises_timeout_error( + per_user_directory: pathlib.Path, + legacy_directory: pathlib.Path, + mock_popen: Mock, + mocker: MockerFixture, +) -> None: + mocker.patch(f"{_SUPPORT_MODULE}._START_SERVICE_TIMEOUT", 0.3) + + with pytest.raises(TimeoutError): + _get_discovery_service_address()