test_helpers.py 2.2 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_when_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. sock.listen(1)
  10. host, port = sock.getsockname()
  11. assert not helpers.is_port_open(host, port), 'after closing the socket, the port should be free'
  12. def test_is_port_open_when_closed():
  13. with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  14. sock.bind(('127.0.0.1', port))
  15. sock.listen(1)
  16. assert helpers.is_port_open(host, port), 'after opening the socket, the port should be detected'
  17. def test_schedule_browser(monkeypatch):
  18. called_with_url = None
  19. def mock_webbrowser_open(url):
  20. nonlocal called_with_url
  21. called_with_url = url
  22. monkeypatch.setattr(webbrowser, "open", mock_webbrowser_open)
  23. with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  24. sock.bind(('127.0.0.1', 0))
  25. host, port = sock.getsockname()
  26. thread, cancel_event = helpers.schedule_browser(host, port)
  27. try:
  28. # port bound, but not opened yet
  29. assert called_with_url is None
  30. sock.listen()
  31. # port opened
  32. time.sleep(1)
  33. assert called_with_url == f"http://{host}:{port}/"
  34. finally:
  35. cancel_event.set()
  36. def test_canceling_schedule_browser(monkeypatch):
  37. called_with_url = None
  38. def mock_webbrowser_open(url):
  39. nonlocal called_with_url
  40. called_with_url = url
  41. monkeypatch.setattr(webbrowser, "open", mock_webbrowser_open)
  42. # find a free port ...
  43. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  44. sock.bind(('127.0.0.1', 0))
  45. sock.listen(1)
  46. host, port = sock.getsockname()
  47. # ... and close it so schedule_browser does not launch the browser
  48. sock.close()
  49. thread, cancel_event = helpers.schedule_browser(host, port)
  50. time.sleep(0.2)
  51. cancel_event.set()
  52. time.sleep(0.2)
  53. assert not thread.is_alive()
  54. assert called_with_url is None