diff --git a/pyrit/ui/app.py b/pyrit/ui/app.py index 9c0b743a07..20beceac7f 100644 --- a/pyrit/ui/app.py +++ b/pyrit/ui/app.py @@ -5,6 +5,8 @@ import subprocess import sys import traceback +import ctypes +import ctypes GLOBAL_MUTEX_NAME = "PyRIT-Gradio" @@ -25,15 +27,18 @@ def launch_app(open_browser: bool = False) -> None: subprocess.Popen([python_path, current_path, str(open_browser)]) -def is_app_running() -> bool: +def create_mutex() -> bool: if sys.platform != "win32": - raise NotImplementedError("This function is only supported on Windows.") + return True + last_error = ctypes.windll.kernel32.GetLastError() + return bool(last_error != 183) # ERROR_ALREADY_EXISTS + - import ctypes.wintypes # noqa: F401 +def is_app_running() -> bool: + if sys.platform != "win32": + return False SYNCHRONIZE = 0x00100000 - mutex = ctypes.windll.kernel32.OpenMutexW(SYNCHRONIZE, False, GLOBAL_MUTEX_NAME) - if not mutex: return False # Close the handle to the mutex @@ -43,17 +48,6 @@ def is_app_running() -> bool: if __name__ == "__main__": - def create_mutex() -> bool: - if sys.platform != "win32": - raise NotImplementedError("This function is only supported on Windows.") - - # TODO make sure to add cross-platform support for this. - import ctypes.wintypes - - ctypes.windll.kernel32.CreateMutexW(None, False, GLOBAL_MUTEX_NAME) - last_error = ctypes.windll.kernel32.GetLastError() - return bool(last_error != 183) # ERROR_ALREADY_EXISTS - if not create_mutex(): print("Gradio UI is already running.") sys.exit(1) diff --git a/tests/unit/ui/test_app.py b/tests/unit/ui/test_app.py new file mode 100644 index 0000000000..94b28fc29e --- /dev/null +++ b/tests/unit/ui/test_app.py @@ -0,0 +1,16 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pyrit.ui import app as ui_app + + +def test_is_app_running_returns_false_on_non_windows(monkeypatch): + monkeypatch.setattr(ui_app.sys, "platform", "linux") + + assert ui_app.is_app_running() is False + + +def test_create_mutex_returns_true_on_non_windows(monkeypatch): + monkeypatch.setattr(ui_app.sys, "platform", "linux") + + assert ui_app.create_mutex() is True