test_readability.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """
  2. Integration tests for readability plugin
  3. Tests verify:
  4. pass
  5. 1. Validate hook checks for readability-extractor binary
  6. 2. Verify deps with abx-pkg
  7. 3. Plugin reports missing dependency correctly
  8. 4. Extraction works against real example.com content
  9. """
  10. import json
  11. import shutil
  12. import subprocess
  13. import sys
  14. import tempfile
  15. from pathlib import Path
  16. import pytest
  17. PLUGIN_DIR = Path(__file__).parent.parent
  18. PLUGINS_ROOT = PLUGIN_DIR.parent
  19. READABILITY_HOOK = next(PLUGIN_DIR.glob('on_Snapshot__*_readability.*'))
  20. TEST_URL = 'https://example.com'
  21. def create_example_html(tmpdir: Path) -> Path:
  22. """Create sample HTML that looks like example.com with enough content for Readability."""
  23. singlefile_dir = tmpdir / 'singlefile'
  24. singlefile_dir.mkdir()
  25. html_file = singlefile_dir / 'singlefile.html'
  26. html_file.write_text('''
  27. <!DOCTYPE html>
  28. <html>
  29. <head>
  30. <meta charset="utf-8">
  31. <title>Example Domain</title>
  32. <meta name="viewport" content="width=device-width, initial-scale=1">
  33. </head>
  34. <body>
  35. <article>
  36. <header>
  37. <h1>Example Domain</h1>
  38. </header>
  39. <div class="content">
  40. <p>This domain is for use in illustrative examples in documents. You may use this
  41. domain in literature without prior coordination or asking for permission.</p>
  42. <p>Example domains are maintained by the Internet Assigned Numbers Authority (IANA)
  43. to provide a well-known address for documentation purposes. This helps authors create
  44. examples that readers can understand without confusion about actual domain ownership.</p>
  45. <p>The practice of using example domains dates back to the early days of the internet.
  46. These reserved domains ensure that example code and documentation doesn't accidentally
  47. point to real, active websites that might change or disappear over time.</p>
  48. <p>For more information about example domains and their history, you can visit the
  49. IANA website. They maintain several example domains including example.com, example.net,
  50. and example.org, all specifically reserved for this purpose.</p>
  51. <p><a href="https://www.iana.org/domains/example">More information about example domains...</a></p>
  52. </div>
  53. </article>
  54. </body>
  55. </html>
  56. ''')
  57. return html_file
  58. def test_hook_script_exists():
  59. """Verify hook script exists."""
  60. assert READABILITY_HOOK.exists(), f"Hook script not found: {READABILITY_HOOK}"
  61. def test_reports_missing_dependency_when_not_installed():
  62. """Test that script reports DEPENDENCY_NEEDED when readability-extractor is not found."""
  63. with tempfile.TemporaryDirectory() as tmpdir:
  64. tmpdir = Path(tmpdir)
  65. # Create HTML source so it doesn't fail on missing HTML
  66. create_example_html(tmpdir)
  67. # Run with empty PATH so binary won't be found
  68. env = {'PATH': '/nonexistent', 'HOME': str(tmpdir)}
  69. result = subprocess.run(
  70. [sys.executable, str(READABILITY_HOOK), '--url', TEST_URL, '--snapshot-id', 'test123'],
  71. cwd=tmpdir,
  72. capture_output=True,
  73. text=True,
  74. env=env
  75. )
  76. # Missing binary is a transient error - should exit 1 with no JSONL
  77. assert result.returncode == 1, "Should exit 1 when dependency missing"
  78. # Should NOT emit JSONL (transient error - will be retried)
  79. jsonl_lines = [line for line in result.stdout.strip().split('\n')
  80. if line.strip().startswith('{')]
  81. assert len(jsonl_lines) == 0, "Should not emit JSONL for transient error (missing binary)"
  82. # Should log error to stderr
  83. assert 'readability-extractor' in result.stderr.lower() or 'error' in result.stderr.lower(), \
  84. "Should report error in stderr"
  85. def test_verify_deps_with_abx_pkg():
  86. """Verify readability-extractor is available via abx-pkg."""
  87. from abx_pkg import Binary, NpmProvider, EnvProvider, BinProviderOverrides
  88. readability_binary = Binary(
  89. name='readability-extractor',
  90. binproviders=[NpmProvider(), EnvProvider()],
  91. overrides={'npm': {'packages': ['github:ArchiveBox/readability-extractor']}}
  92. )
  93. readability_loaded = readability_binary.load()
  94. if readability_loaded and readability_loaded.abspath:
  95. assert True, "readability-extractor is available"
  96. else:
  97. pass
  98. def test_extracts_article_after_installation():
  99. """Test full workflow: extract article using readability-extractor from real HTML."""
  100. # Prerequisites checked by earlier test (install hook should have run)
  101. with tempfile.TemporaryDirectory() as tmpdir:
  102. tmpdir = Path(tmpdir)
  103. # Create example.com HTML for readability to process
  104. create_example_html(tmpdir)
  105. # Run readability extraction (should find the binary)
  106. result = subprocess.run(
  107. [sys.executable, str(READABILITY_HOOK), '--url', TEST_URL, '--snapshot-id', 'test789'],
  108. cwd=tmpdir,
  109. capture_output=True,
  110. text=True,
  111. timeout=30
  112. )
  113. assert result.returncode == 0, f"Extraction failed: {result.stderr}"
  114. # Parse clean JSONL output
  115. result_json = None
  116. for line in result.stdout.strip().split('\n'):
  117. line = line.strip()
  118. if line.startswith('{'):
  119. pass
  120. try:
  121. record = json.loads(line)
  122. if record.get('type') == 'ArchiveResult':
  123. result_json = record
  124. break
  125. except json.JSONDecodeError:
  126. pass
  127. assert result_json, "Should have ArchiveResult JSONL output"
  128. assert result_json['status'] == 'succeeded', f"Should succeed: {result_json}"
  129. # Verify output files exist (hook writes to current directory)
  130. html_file = tmpdir / 'content.html'
  131. txt_file = tmpdir / 'content.txt'
  132. json_file = tmpdir / 'article.json'
  133. assert html_file.exists(), "content.html not created"
  134. assert txt_file.exists(), "content.txt not created"
  135. assert json_file.exists(), "article.json not created"
  136. # Verify HTML content contains REAL example.com text
  137. html_content = html_file.read_text()
  138. assert len(html_content) > 100, f"HTML content too short: {len(html_content)} bytes"
  139. assert 'example domain' in html_content.lower(), "Missing 'Example Domain' in HTML"
  140. assert ('illustrative examples' in html_content.lower() or
  141. 'use in' in html_content.lower() or
  142. 'literature' in html_content.lower()), \
  143. "Missing example.com description in HTML"
  144. # Verify text content contains REAL example.com text
  145. txt_content = txt_file.read_text()
  146. assert len(txt_content) > 50, f"Text content too short: {len(txt_content)} bytes"
  147. assert 'example' in txt_content.lower(), "Missing 'example' in text"
  148. # Verify JSON metadata
  149. json_data = json.loads(json_file.read_text())
  150. assert isinstance(json_data, dict), "article.json should be a dict"
  151. def test_fails_gracefully_without_html_source():
  152. """Test that extraction fails gracefully when no HTML source is available."""
  153. # Prerequisites checked by earlier test (install hook should have run)
  154. with tempfile.TemporaryDirectory() as tmpdir:
  155. tmpdir = Path(tmpdir)
  156. # Don't create any HTML source files
  157. result = subprocess.run(
  158. [sys.executable, str(READABILITY_HOOK), '--url', TEST_URL, '--snapshot-id', 'test999'],
  159. cwd=tmpdir,
  160. capture_output=True,
  161. text=True,
  162. timeout=30
  163. )
  164. assert result.returncode != 0, "Should fail without HTML source"
  165. combined_output = result.stdout + result.stderr
  166. assert ('no html source' in combined_output.lower() or
  167. 'not found' in combined_output.lower() or
  168. 'ERROR=' in combined_output), \
  169. "Should report missing HTML source"
  170. if __name__ == '__main__':
  171. pytest.main([__file__, '-v'])