test_serving_files.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from pathlib import Path
  2. import httpx
  3. import pytest
  4. from nicegui import app, ui
  5. from .screen import PORT, Screen
  6. from .test_helpers import TEST_DIR
  7. IMAGE_FILE = Path(TEST_DIR).parent / 'examples' / 'slideshow' / 'slides' / 'slide1.jpg'
  8. VIDEO_FILE = Path(TEST_DIR) / 'media' / 'test.mp4'
  9. @pytest.fixture(autouse=True)
  10. def provide_media_files():
  11. if not VIDEO_FILE.exists():
  12. VIDEO_FILE.parent.mkdir(exist_ok=True)
  13. url = 'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4'
  14. with httpx.stream('GET', url) as response:
  15. with open(VIDEO_FILE, 'wb') as file:
  16. for chunk in response.iter_raw():
  17. file.write(chunk)
  18. def assert_video_file_streaming(path: str) -> None:
  19. with httpx.Client() as http_client:
  20. r = http_client.get(
  21. path if 'http' in path else f'http://localhost:{PORT}{path}',
  22. headers={'Range': 'bytes=0-1000'},
  23. )
  24. assert r.status_code == 206
  25. assert r.headers['Accept-Ranges'] == 'bytes'
  26. assert r.headers['Content-Range'].startswith('bytes 0-1000/')
  27. assert r.headers['Content-Length'] == '1001'
  28. assert r.headers['Content-Type'] == 'video/mp4'
  29. def test_media_files_can_be_streamed(screen: Screen):
  30. app.add_media_files('/media', Path(TEST_DIR) / 'media')
  31. screen.open('/')
  32. assert_video_file_streaming('/media/test.mp4')
  33. def test_adding_single_media_file(screen: Screen):
  34. url_path = app.add_media_file(local_file=VIDEO_FILE)
  35. screen.open('/')
  36. assert_video_file_streaming(url_path)
  37. def test_adding_single_static_file(screen: Screen):
  38. url_path = app.add_static_file(local_file=IMAGE_FILE)
  39. screen.open('/')
  40. with httpx.Client() as http_client:
  41. r = http_client.get(f'http://localhost:{PORT}{url_path}')
  42. assert r.status_code == 200
  43. assert 'max-age=' in r.headers['Cache-Control']
  44. def test_auto_serving_file_from_image_source(screen: Screen):
  45. ui.image(IMAGE_FILE)
  46. screen.open('/')
  47. img = screen.find_by_tag('img')
  48. assert '/_nicegui/auto/static/' in img.get_attribute('src')
  49. assert screen.selenium.execute_script("""
  50. return arguments[0].complete &&
  51. typeof arguments[0].naturalWidth != "undefined" &&
  52. arguments[0].naturalWidth > 0
  53. """, img), 'image should load successfully'
  54. def test_auto_serving_file_from_video_source(screen: Screen):
  55. ui.video(VIDEO_FILE)
  56. screen.open('/')
  57. video = screen.find_by_tag('video')
  58. assert '/_nicegui/auto/media/' in video.get_attribute('src')
  59. assert_video_file_streaming(video.get_attribute('src'))