test_papersdl.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """
  2. Integration tests for papersdl plugin
  3. Tests verify:
  4. 1. Hook script exists
  5. 2. Dependencies installed via validation hooks
  6. 3. Verify deps with abx-pkg
  7. 4. Paper extraction works on paper URLs
  8. 5. JSONL output is correct
  9. 6. Config options work
  10. 7. Handles non-paper URLs gracefully
  11. """
  12. import json
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import uuid
  17. from pathlib import Path
  18. import pytest
  19. PLUGIN_DIR = Path(__file__).parent.parent
  20. PLUGINS_ROOT = PLUGIN_DIR.parent
  21. PAPERSDL_HOOK = next(PLUGIN_DIR.glob('on_Snapshot__*_papersdl.*'), None)
  22. TEST_URL = 'https://example.com'
  23. # Module-level cache for binary path
  24. _papersdl_binary_path = None
  25. def get_papersdl_binary_path():
  26. """Get the installed papers-dl binary path from cache or by running installation."""
  27. global _papersdl_binary_path
  28. if _papersdl_binary_path:
  29. return _papersdl_binary_path
  30. # Try to find papers-dl binary using abx-pkg
  31. from abx_pkg import Binary, PipProvider, EnvProvider, BinProviderOverrides
  32. try:
  33. binary = Binary(
  34. name='papers-dl',
  35. binproviders=[PipProvider(), EnvProvider()]
  36. ).load()
  37. if binary and binary.abspath:
  38. _papersdl_binary_path = str(binary.abspath)
  39. return _papersdl_binary_path
  40. except Exception:
  41. pass
  42. # If not found, try to install via pip
  43. pip_hook = PLUGINS_ROOT / 'pip' / 'on_Binary__install_using_pip_provider.py'
  44. if pip_hook.exists():
  45. binary_id = str(uuid.uuid4())
  46. machine_id = str(uuid.uuid4())
  47. cmd = [
  48. sys.executable, str(pip_hook),
  49. '--binary-id', binary_id,
  50. '--machine-id', machine_id,
  51. '--name', 'papers-dl'
  52. ]
  53. install_result = subprocess.run(
  54. cmd,
  55. capture_output=True,
  56. text=True,
  57. timeout=300
  58. )
  59. # Parse Binary from pip installation
  60. for install_line in install_result.stdout.strip().split('\n'):
  61. if install_line.strip():
  62. try:
  63. install_record = json.loads(install_line)
  64. if install_record.get('type') == 'Binary' and install_record.get('name') == 'papers-dl':
  65. _papersdl_binary_path = install_record.get('abspath')
  66. return _papersdl_binary_path
  67. except json.JSONDecodeError:
  68. pass
  69. return None
  70. def test_hook_script_exists():
  71. """Verify on_Snapshot hook exists."""
  72. assert PAPERSDL_HOOK.exists(), f"Hook not found: {PAPERSDL_HOOK}"
  73. def test_verify_deps_with_abx_pkg():
  74. """Verify papers-dl is installed by calling the REAL installation hooks."""
  75. binary_path = get_papersdl_binary_path()
  76. assert binary_path, "papers-dl must be installed successfully via install hook and pip provider"
  77. assert Path(binary_path).is_file(), f"Binary path must be a valid file: {binary_path}"
  78. def test_handles_non_paper_url():
  79. """Test that papers-dl extractor handles non-paper URLs gracefully via hook."""
  80. import os
  81. binary_path = get_papersdl_binary_path()
  82. assert binary_path, "Binary must be installed for this test"
  83. with tempfile.TemporaryDirectory() as tmpdir:
  84. tmpdir = Path(tmpdir)
  85. env = os.environ.copy()
  86. env['PAPERSDL_BINARY'] = binary_path
  87. # Run papers-dl extraction hook on non-paper URL
  88. result = subprocess.run(
  89. [sys.executable, str(PAPERSDL_HOOK), '--url', 'https://example.com', '--snapshot-id', 'test789'],
  90. cwd=tmpdir,
  91. capture_output=True,
  92. text=True,
  93. env=env,
  94. timeout=60
  95. )
  96. # Should exit 0 even for non-paper URL
  97. assert result.returncode == 0, f"Should handle non-paper URL gracefully: {result.stderr}"
  98. # Parse clean JSONL output
  99. result_json = None
  100. for line in result.stdout.strip().split('\n'):
  101. line = line.strip()
  102. if line.startswith('{'):
  103. try:
  104. record = json.loads(line)
  105. if record.get('type') == 'ArchiveResult':
  106. result_json = record
  107. break
  108. except json.JSONDecodeError:
  109. pass
  110. assert result_json, "Should have ArchiveResult JSONL output"
  111. assert result_json['status'] == 'succeeded', f"Should succeed: {result_json}"
  112. def test_config_save_papersdl_false_skips():
  113. """Test that PAPERSDL_ENABLED=False exits without emitting JSONL."""
  114. import os
  115. with tempfile.TemporaryDirectory() as tmpdir:
  116. env = os.environ.copy()
  117. env['PAPERSDL_ENABLED'] = 'False'
  118. result = subprocess.run(
  119. [sys.executable, str(PAPERSDL_HOOK), '--url', TEST_URL, '--snapshot-id', 'test999'],
  120. cwd=tmpdir,
  121. capture_output=True,
  122. text=True,
  123. env=env,
  124. timeout=30
  125. )
  126. assert result.returncode == 0, f"Should exit 0 when feature disabled: {result.stderr}"
  127. # Feature disabled - temporary failure, should NOT emit JSONL
  128. assert 'Skipping' in result.stderr or 'False' in result.stderr, "Should log skip reason to stderr"
  129. # Should NOT emit any JSONL
  130. jsonl_lines = [line for line in result.stdout.strip().split('\n') if line.strip().startswith('{')]
  131. assert len(jsonl_lines) == 0, f"Should not emit JSONL when feature disabled, but got: {jsonl_lines}"
  132. def test_config_timeout():
  133. """Test that PAPERSDL_TIMEOUT config is respected."""
  134. import os
  135. binary_path = get_papersdl_binary_path()
  136. assert binary_path, "Binary must be installed for this test"
  137. with tempfile.TemporaryDirectory() as tmpdir:
  138. env = os.environ.copy()
  139. env['PAPERSDL_BINARY'] = binary_path
  140. env['PAPERSDL_TIMEOUT'] = '5'
  141. result = subprocess.run(
  142. [sys.executable, str(PAPERSDL_HOOK), '--url', 'https://example.com', '--snapshot-id', 'testtimeout'],
  143. cwd=tmpdir,
  144. capture_output=True,
  145. text=True,
  146. env=env,
  147. timeout=30
  148. )
  149. assert result.returncode == 0, "Should complete without hanging"
  150. if __name__ == '__main__':
  151. pytest.main([__file__, '-v'])