test_serving_files.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import os
  2. from pathlib import Path
  3. import httpx
  4. import pytest
  5. from nicegui import app, ui
  6. from .screen import PORT, Screen
  7. from .test_helpers import TEST_DIR
  8. @pytest.fixture(autouse=True)
  9. def provide_media_files():
  10. mp4 = Path(TEST_DIR / 'media' / 'test.mp4')
  11. if not mp4.exists():
  12. mp4.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(mp4, '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(f'http://localhost:{PORT}{path}', headers={'Range': 'bytes=0-1000'})
  21. assert r.status_code == 206
  22. assert r.headers['Accept-Ranges'] == 'bytes'
  23. assert r.headers['Content-Range'].startswith('bytes 0-1000/')
  24. assert r.headers['Content-Length'] == '1001'
  25. assert r.headers['Content-Type'] == 'video/mp4'
  26. def test_media_files_can_be_streamed(screen: Screen):
  27. app.add_media_files('/media', Path(TEST_DIR) / 'media')
  28. screen.open('/')
  29. assert_video_file_streaming('/media/test.mp4')
  30. def test_adding_single_media_file(screen: Screen):
  31. url_path = app.add_media_file(Path(TEST_DIR) / 'media' / 'test.mp4')
  32. screen.open('/')
  33. assert_video_file_streaming(url_path)