test_helpers.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import contextlib
  2. import socket
  3. import time
  4. import webbrowser
  5. from nicegui import helpers
  6. def test_is_port_open():
  7. with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  8. sock.bind(('127.0.0.1', 0)) # port = 0 => the OS chooses a port for us
  9. host, port = sock.getsockname()
  10. # port bound, but not opened yet
  11. assert not helpers.is_port_open(host, port)
  12. sock.listen()
  13. # port opened
  14. assert helpers.is_port_open(host, port)
  15. def test_schedule_browser(monkeypatch):
  16. called_with_url = None
  17. def mock_webbrowser_open(url):
  18. nonlocal called_with_url
  19. called_with_url = url
  20. monkeypatch.setattr(webbrowser, "open", mock_webbrowser_open)
  21. with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  22. sock.bind(('127.0.0.1', 0))
  23. host, port = sock.getsockname()
  24. thread, cancel_event = helpers.schedule_browser(host, port)
  25. try:
  26. # port bound, but not opened yet
  27. assert called_with_url is None
  28. sock.listen()
  29. # port opened
  30. time.sleep(1)
  31. assert called_with_url == f"http://{host}:{port}/"
  32. finally:
  33. cancel_event.set()
  34. def test_schedule_browser_cancel(monkeypatch):
  35. called_with_url = None
  36. def mock_webbrowser_open(url):
  37. nonlocal called_with_url
  38. called_with_url = url
  39. monkeypatch.setattr(webbrowser, "open", mock_webbrowser_open)
  40. # This test doesn't need to open a port, but it binds a socket, s.th. we can be sure
  41. # it is NOT open.
  42. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  43. sock.bind(('127.0.0.1', 0))
  44. host, port = sock.getsockname()
  45. thread, cancel_event = helpers.schedule_browser(host, port)
  46. cancel_event.set()
  47. time.sleep(1)
  48. assert not thread.is_alive()
  49. assert called_with_url is None