test_helpers.py 2.2 KB

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