test_gallerydl.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """
  2. Integration tests for gallerydl plugin
  3. Tests verify:
  4. pass
  5. 1. Hook script exists
  6. 2. Dependencies installed via validation hooks
  7. 3. Verify deps with abx-pkg
  8. 4. Gallery extraction works on gallery URLs
  9. 5. JSONL output is correct
  10. 6. Config options work
  11. 7. Handles non-gallery URLs gracefully
  12. """
  13. import json
  14. import subprocess
  15. import sys
  16. import tempfile
  17. import time
  18. from pathlib import Path
  19. import pytest
  20. PLUGIN_DIR = Path(__file__).parent.parent
  21. PLUGINS_ROOT = PLUGIN_DIR.parent
  22. GALLERYDL_HOOK = next(PLUGIN_DIR.glob('on_Snapshot__*_gallerydl.*'), None)
  23. TEST_URL = 'https://example.com'
  24. def test_hook_script_exists():
  25. """Verify on_Snapshot hook exists."""
  26. assert GALLERYDL_HOOK.exists(), f"Hook not found: {GALLERYDL_HOOK}"
  27. def test_verify_deps_with_abx_pkg():
  28. """Verify gallery-dl is available via abx-pkg."""
  29. from abx_pkg import Binary, PipProvider, EnvProvider, BinProviderOverrides
  30. missing_binaries = []
  31. # Verify gallery-dl is available
  32. gallerydl_binary = Binary(name='gallery-dl', binproviders=[PipProvider(), EnvProvider()])
  33. gallerydl_loaded = gallerydl_binary.load()
  34. if not (gallerydl_loaded and gallerydl_loaded.abspath):
  35. missing_binaries.append('gallery-dl')
  36. if missing_binaries:
  37. pass
  38. def test_handles_non_gallery_url():
  39. """Test that gallery-dl extractor handles non-gallery URLs gracefully via hook."""
  40. # Prerequisites checked by earlier test
  41. with tempfile.TemporaryDirectory() as tmpdir:
  42. tmpdir = Path(tmpdir)
  43. # Run gallery-dl extraction hook on non-gallery URL
  44. result = subprocess.run(
  45. [sys.executable, str(GALLERYDL_HOOK), '--url', 'https://example.com', '--snapshot-id', 'test789'],
  46. cwd=tmpdir,
  47. capture_output=True,
  48. text=True,
  49. timeout=60
  50. )
  51. # Should exit 0 even for non-gallery URL
  52. assert result.returncode == 0, f"Should handle non-gallery URL gracefully: {result.stderr}"
  53. # Parse clean JSONL output
  54. result_json = None
  55. for line in result.stdout.strip().split('\n'):
  56. line = line.strip()
  57. if line.startswith('{'):
  58. pass
  59. try:
  60. record = json.loads(line)
  61. if record.get('type') == 'ArchiveResult':
  62. result_json = record
  63. break
  64. except json.JSONDecodeError:
  65. pass
  66. assert result_json, "Should have ArchiveResult JSONL output"
  67. assert result_json['status'] == 'succeeded', f"Should succeed: {result_json}"
  68. def test_config_save_gallery_dl_false_skips():
  69. """Test that GALLERYDL_ENABLED=False exits without emitting JSONL."""
  70. import os
  71. with tempfile.TemporaryDirectory() as tmpdir:
  72. env = os.environ.copy()
  73. env['GALLERYDL_ENABLED'] = 'False'
  74. result = subprocess.run(
  75. [sys.executable, str(GALLERYDL_HOOK), '--url', TEST_URL, '--snapshot-id', 'test999'],
  76. cwd=tmpdir,
  77. capture_output=True,
  78. text=True,
  79. env=env,
  80. timeout=30
  81. )
  82. assert result.returncode == 0, f"Should exit 0 when feature disabled: {result.stderr}"
  83. # Feature disabled - temporary failure, should NOT emit JSONL
  84. assert 'Skipping' in result.stderr or 'False' in result.stderr, "Should log skip reason to stderr"
  85. # Should NOT emit any JSONL
  86. jsonl_lines = [line for line in result.stdout.strip().split('\n') if line.strip().startswith('{')]
  87. assert len(jsonl_lines) == 0, f"Should not emit JSONL when feature disabled, but got: {jsonl_lines}"
  88. def test_config_timeout():
  89. """Test that GALLERY_DL_TIMEOUT config is respected."""
  90. import os
  91. with tempfile.TemporaryDirectory() as tmpdir:
  92. env = os.environ.copy()
  93. env['GALLERY_DL_TIMEOUT'] = '5'
  94. start_time = time.time()
  95. result = subprocess.run(
  96. [sys.executable, str(GALLERYDL_HOOK), '--url', 'https://example.com', '--snapshot-id', 'testtimeout'],
  97. cwd=tmpdir,
  98. capture_output=True,
  99. text=True,
  100. env=env,
  101. timeout=10 # Should complete in 5s, use 10s as safety margin
  102. )
  103. elapsed_time = time.time() - start_time
  104. assert result.returncode == 0, f"Should complete without hanging: {result.stderr}"
  105. # Allow 1 second overhead for subprocess startup and Python interpreter
  106. assert elapsed_time <= 6.0, f"Should complete within 6 seconds (5s timeout + 1s overhead), took {elapsed_time:.2f}s"
  107. def test_real_gallery_url():
  108. """Test that gallery-dl can extract images from a real Flickr gallery URL."""
  109. import os
  110. with tempfile.TemporaryDirectory() as tmpdir:
  111. tmpdir = Path(tmpdir)
  112. # Use a real Flickr photo page
  113. gallery_url = 'https://www.flickr.com/photos/gregorydolivet/55002388567/in/explore-2025-12-25/'
  114. env = os.environ.copy()
  115. env['GALLERY_DL_TIMEOUT'] = '60' # Give it time to download
  116. start_time = time.time()
  117. result = subprocess.run(
  118. [sys.executable, str(GALLERYDL_HOOK), '--url', gallery_url, '--snapshot-id', 'testflickr'],
  119. cwd=tmpdir,
  120. capture_output=True,
  121. text=True,
  122. env=env,
  123. timeout=90
  124. )
  125. elapsed_time = time.time() - start_time
  126. # Should succeed
  127. assert result.returncode == 0, f"Should extract gallery successfully: {result.stderr}"
  128. # Parse JSONL output
  129. result_json = None
  130. for line in result.stdout.strip().split('\n'):
  131. line = line.strip()
  132. if line.startswith('{'):
  133. try:
  134. record = json.loads(line)
  135. if record.get('type') == 'ArchiveResult':
  136. result_json = record
  137. break
  138. except json.JSONDecodeError:
  139. pass
  140. assert result_json, f"Should have ArchiveResult JSONL output. stdout: {result.stdout}"
  141. assert result_json['status'] == 'succeeded', f"Should succeed: {result_json}"
  142. # Check that some files were downloaded
  143. output_files = list(tmpdir.glob('**/*'))
  144. image_files = [f for f in output_files if f.is_file() and f.suffix.lower() in ('.jpg', '.jpeg', '.png', '.gif', '.webp')]
  145. assert len(image_files) > 0, f"Should have downloaded at least one image. Files: {output_files}"
  146. print(f"Successfully extracted {len(image_files)} image(s) in {elapsed_time:.2f}s")
  147. if __name__ == '__main__':
  148. pytest.main([__file__, '-v'])