test_helpers.py 2.1 KB

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