wp2txt 2.3.4 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/.dockerignore +0 -4
  3. data/.github/workflows/ci.yml +16 -1
  4. data/.github/workflows/publish-image.yml +8 -4
  5. data/.gitignore +3 -6
  6. data/CHANGELOG.md +32 -0
  7. data/DEVELOPMENT.md +63 -93
  8. data/DEVELOPMENT_ja.md +61 -93
  9. data/Dockerfile +1 -1
  10. data/README.md +93 -8
  11. data/README_ja.md +84 -8
  12. data/Rakefile +10 -21
  13. data/bin/wp2txt +84 -15
  14. data/bin/wp2txt-mcp +1 -1
  15. data/docs/INDEXES.md +61 -1
  16. data/lib/wp2txt/article.rb +2 -3
  17. data/lib/wp2txt/bz2_stream.rb +63 -0
  18. data/lib/wp2txt/cli.rb +90 -26
  19. data/lib/wp2txt/config.rb +2 -11
  20. data/lib/wp2txt/constants.rb +13 -1
  21. data/lib/wp2txt/corpus.rb +10 -23
  22. data/lib/wp2txt/data/template_aliases.json +4 -1
  23. data/lib/wp2txt/data/template_patterns.json +61643 -0
  24. data/lib/wp2txt/dump_snapshot.rb +99 -0
  25. data/lib/wp2txt/extraction_run.rb +272 -0
  26. data/lib/wp2txt/extractor.rb +481 -327
  27. data/lib/wp2txt/formatter.rb +14 -12
  28. data/lib/wp2txt/fts_index.rb +1 -1
  29. data/lib/wp2txt/index_cache.rb +144 -55
  30. data/lib/wp2txt/index_commands.rb +109 -18
  31. data/lib/wp2txt/langlinks_importer.rb +19 -35
  32. data/lib/wp2txt/lead_terms.rb +228 -0
  33. data/lib/wp2txt/link_counter.rb +171 -0
  34. data/lib/wp2txt/magic_words.rb +44 -28
  35. data/lib/wp2txt/metadata_index.rb +82 -13
  36. data/lib/wp2txt/multistream.rb +911 -824
  37. data/lib/wp2txt/output_writer.rb +3 -1
  38. data/lib/wp2txt/page_props_importer.rb +170 -0
  39. data/lib/wp2txt/parser_functions.rb +23 -5
  40. data/lib/wp2txt/ractor_worker.rb +6 -4
  41. data/lib/wp2txt/regex.rb +24 -4
  42. data/lib/wp2txt/site_info.rb +123 -0
  43. data/lib/wp2txt/sql_dump_reader.rb +57 -0
  44. data/lib/wp2txt/stream_processor.rb +9 -2
  45. data/lib/wp2txt/stream_store.rb +91 -0
  46. data/lib/wp2txt/template_args.rb +111 -0
  47. data/lib/wp2txt/template_expander.rb +110 -124
  48. data/lib/wp2txt/template_patterns.rb +182 -0
  49. data/lib/wp2txt/utils.rb +164 -127
  50. data/lib/wp2txt/version.rb +1 -1
  51. data/lib/wp2txt/wikitext_regions.rb +66 -0
  52. data/spec/auto_download_spec.rb +9 -6
  53. data/spec/category_fetcher_spec.rb +135 -463
  54. data/spec/cli_targeted_spec.rb +60 -0
  55. data/spec/config_spec.rb +2 -15
  56. data/spec/constants_spec.rb +0 -4
  57. data/spec/docs_sync_spec.rb +3 -3
  58. data/spec/dump_fetch_spec.rb +293 -0
  59. data/spec/extraction_run_spec.rb +520 -0
  60. data/spec/index_build_spec.rb +113 -0
  61. data/spec/index_commands_version_spec.rb +17 -0
  62. data/spec/langlinks_importer_spec.rb +27 -0
  63. data/spec/lead_terms_edge_cases_spec.rb +194 -0
  64. data/spec/lead_terms_links_qids_spec.rb +204 -0
  65. data/spec/multistream_reader_spec.rb +140 -0
  66. data/spec/multistream_spec.rb +8 -214
  67. data/spec/output_integrity_spec.rb +45 -2
  68. data/spec/p1_correctness_spec.rb +12 -9
  69. data/spec/page_properties_spec.rb +161 -0
  70. data/spec/regex_spec.rb +30 -0
  71. data/spec/region_semantics_spec.rb +71 -0
  72. data/spec/spec_helper.rb +3 -3
  73. data/spec/support/dump_status.rb +34 -0
  74. data/spec/support/multistream_fixture.rb +26 -8
  75. data/spec/template_args_spec.rb +133 -0
  76. data/spec/template_expander_spec.rb +29 -111
  77. data/spec/template_passthrough_spec.rb +58 -0
  78. data/spec/template_patterns_spec.rb +253 -0
  79. data/spec/tracked_paths_spec.rb +168 -0
  80. data/spec/utils_spec.rb +7 -1
  81. metadata +45 -5
  82. data/lib/wp2txt/category_cache.rb +0 -313
  83. data/spec/category_cache_spec.rb +0 -226
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "spec_helper"
4
+ require_relative "../lib/wp2txt/cli"
5
+ require "tmpdir"
6
+
7
+ # Options of the targeted extraction modes (--articles, --articles-file, --from-category)
8
+ RSpec.describe Wp2txt::CLI do
9
+ around do |example|
10
+ Dir.mktmpdir("wp2txt-cli-") do |dir|
11
+ @dir = dir
12
+ example.run
13
+ end
14
+ end
15
+
16
+ def parse(*args)
17
+ described_class.parse_options([*args, "-o", @dir])
18
+ end
19
+
20
+ def rejected(*args)
21
+ suppress_stderr { expect { parse(*args) }.to raise_error(SystemExit) }
22
+ end
23
+
24
+ let(:titles_file) { File.join(@dir, "titles.txt").tap { |p| File.write(p, "Tokyo\nWashington, D.C.\n") } }
25
+
26
+ it "accepts a file of titles with --lang" do
27
+ expect(parse("--lang=en", "--articles-file=#{titles_file}")[:articles_file]).to eq(titles_file)
28
+ end
29
+
30
+ it "rejects a file of titles that does not exist, or without --lang" do
31
+ rejected("--lang=en", "--articles-file=#{File.join(@dir, 'missing.txt')}")
32
+ rejected("--articles-file=#{titles_file}")
33
+ end
34
+
35
+ it "takes one targeted mode at a time" do
36
+ rejected("--lang=en", "--articles=Tokyo", "--articles-file=#{titles_file}")
37
+ rejected("--lang=en", "--articles=Tokyo", "--from-category=Cities")
38
+ end
39
+
40
+ it "takes the redirect option only with a targeted mode" do
41
+ expect(parse("--lang=en", "--articles=Tokyo", "--no-follow-redirects")[:no_follow_redirects]).to be(true)
42
+ rejected("--lang=en", "--no-follow-redirects")
43
+ end
44
+
45
+ it "takes the incomplete-listing option only with --from-category" do
46
+ expect(parse("--lang=en", "--from-category=Cities", "--allow-incomplete-category")[:allow_incomplete_category]).to be(true)
47
+ rejected("--lang=en", "--articles=Tokyo", "--allow-incomplete-category")
48
+ end
49
+
50
+ %w[--section-stats --build-index --no-turbo].each do |option|
51
+ it "rejects #{option}, which works on a whole dump, with a targeted mode" do
52
+ rejected("--lang=en", "--articles=Tokyo", option)
53
+ end
54
+ end
55
+
56
+ it "takes a dump date only as YYYYMMDD" do
57
+ expect(parse("--lang=en", "--articles=Tokyo", "--dump-date=20261101")[:dump_date]).to eq("20261101")
58
+ rejected("--lang=en", "--articles=Tokyo", "--dump-date=2026-11-01")
59
+ end
60
+ end
data/spec/config_spec.rb CHANGED
@@ -26,7 +26,6 @@ RSpec.describe Wp2txt::Config do
26
26
  config = described_class.load(config_path)
27
27
 
28
28
  expect(config.dump_expiry_days).to eq 30
29
- expect(config.category_expiry_days).to eq 7
30
29
  expect(config.cache_directory).to eq Wp2txt::Config::DEFAULT_CACHE_DIR
31
30
  expect(config.default_format).to eq "text"
32
31
  expect(config.default_depth).to eq 0
@@ -38,7 +37,7 @@ RSpec.describe Wp2txt::Config do
38
37
  File.write(config_path, <<~YAML)
39
38
  cache:
40
39
  dump_expiry_days: 60
41
- category_expiry_days: 14
40
+ category_expiry_days: 14 # a setting this version does not know is ignored
42
41
  directory: /custom/cache
43
42
  defaults:
44
43
  format: json
@@ -48,7 +47,6 @@ RSpec.describe Wp2txt::Config do
48
47
  config = described_class.load(config_path)
49
48
 
50
49
  expect(config.dump_expiry_days).to eq 60
51
- expect(config.category_expiry_days).to eq 14
52
50
  expect(config.cache_directory).to eq "/custom/cache"
53
51
  expect(config.default_format).to eq "json"
54
52
  expect(config.default_depth).to eq 2
@@ -63,7 +61,6 @@ RSpec.describe Wp2txt::Config do
63
61
  config = described_class.load(config_path)
64
62
 
65
63
  expect(config.dump_expiry_days).to eq 45
66
- expect(config.category_expiry_days).to eq 7 # default
67
64
  expect(config.default_format).to eq "text" # default
68
65
  end
69
66
 
@@ -90,7 +87,6 @@ RSpec.describe Wp2txt::Config do
90
87
  it "writes configuration to file" do
91
88
  config = described_class.new(
92
89
  dump_expiry_days: 45,
93
- category_expiry_days: 10,
94
90
  cache_directory: "/my/cache",
95
91
  default_format: "json",
96
92
  default_depth: 1
@@ -101,7 +97,6 @@ RSpec.describe Wp2txt::Config do
101
97
  expect(File.exist?(config_path)).to be true
102
98
  loaded = described_class.load(config_path)
103
99
  expect(loaded.dump_expiry_days).to eq 45
104
- expect(loaded.category_expiry_days).to eq 10
105
100
  expect(loaded.cache_directory).to eq "/my/cache"
106
101
  expect(loaded.default_format).to eq "json"
107
102
  expect(loaded.default_depth).to eq 1
@@ -124,7 +119,7 @@ RSpec.describe Wp2txt::Config do
124
119
  expect(File.exist?(config_path)).to be true
125
120
  content = File.read(config_path)
126
121
  expect(content).to include("dump_expiry_days: 30")
127
- expect(content).to include("category_expiry_days: 7")
122
+ expect(content).not_to include("category_expiry_days")
128
123
  end
129
124
 
130
125
  it "does not overwrite existing file" do
@@ -167,14 +162,6 @@ RSpec.describe Wp2txt::Config do
167
162
  expect(config.dump_expiry_days).to eq 365
168
163
  end
169
164
 
170
- it "clamps category_expiry_days to valid range" do
171
- config = described_class.new(category_expiry_days: 0)
172
- expect(config.category_expiry_days).to eq 1
173
-
174
- config = described_class.new(category_expiry_days: 100)
175
- expect(config.category_expiry_days).to eq 90
176
- end
177
-
178
165
  it "clamps default_depth to valid range" do
179
166
  config = described_class.new(default_depth: -1)
180
167
  expect(config.default_depth).to eq 0
@@ -23,10 +23,6 @@ RSpec.describe "Wp2txt Constants" do
23
23
  expect(Wp2txt::DEFAULT_DUMP_EXPIRY_DAYS).to eq(30)
24
24
  end
25
25
 
26
- it "defines DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS" do
27
- expect(Wp2txt::DEFAULT_CATEGORY_CACHE_EXPIRY_DAYS).to eq(7)
28
- end
29
-
30
26
  end
31
27
 
32
28
  describe "Network Settings" do
@@ -37,14 +37,14 @@ RSpec.describe "documentation surface sync" do
37
37
  expect(phantom).to be_empty, "documented tools that do not exist: #{phantom.join(', ')}"
38
38
  end
39
39
 
40
- # Tripwire: tracked files must not contain tokens listed in .private-doc-tokens,
40
+ # Tripwire: tracked files must not contain tokens listed in .local/doc-tokens,
41
41
  # an untracked, machine-local file (one substring per line; # starts a comment).
42
42
  # The file exists only on machines that maintain such a list; everywhere else
43
43
  # (CI, other contributors) this example skips — loudly, so a silently dead
44
44
  # check cannot be mistaken for a passing one.
45
45
  it "keeps machine-local private tokens out of tracked files" do
46
- token_file = File.join(repo_root, ".private-doc-tokens")
47
- skip "SKIPPED: no .private-doc-tokens on this machine — tripwire not checked" unless File.exist?(token_file)
46
+ token_file = File.join(repo_root, ".local", "doc-tokens")
47
+ skip "SKIPPED: no .local/doc-tokens on this machine — tripwire not checked" unless File.exist?(token_file)
48
48
 
49
49
  tokens = File.readlines(token_file, encoding: "UTF-8")
50
50
  .map(&:strip).reject { |t| t.empty? || t.start_with?("#") }
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "tmpdir"
5
+ require "webmock/rspec"
6
+ require_relative "support/multistream_fixture"
7
+ require_relative "support/dump_status"
8
+ require "wp2txt/multistream"
9
+
10
+ # Fetching from a dump server that serves the synthetic fixture dump
11
+ RSpec.describe "fetching dump versions and ranges" do
12
+ include MultistreamFixture
13
+ include DumpStatusFixture
14
+
15
+ BASE = "https://dumps.wikimedia.org/testwiki"
16
+ DATE = "20260101"
17
+
18
+ around do |example|
19
+ Dir.mktmpdir("wp2txt-fetch-") do |dir|
20
+ @dir = dir
21
+ WebMock.enable!
22
+ WebMock.disable_net_connect!
23
+ example.run
24
+ ensure
25
+ WebMock.reset!
26
+ WebMock.allow_net_connect!
27
+ end
28
+ end
29
+
30
+ let(:source_dir) { File.join(@dir, "source").tap { |d| FileUtils.mkdir_p(d) } }
31
+ let(:cache_dir) { File.join(@dir, "cache") }
32
+ let(:fixture) { create_fixture(source_dir) }
33
+ let(:dump_bytes) { File.binread(fixture[0]) }
34
+ let(:index_bytes) { bzip2(File.read(fixture[1])).b }
35
+ let(:prefix) { "testwiki-#{DATE}-pages-articles-multistream" }
36
+ let(:dump_url) { "#{BASE}/#{DATE}/#{prefix}.xml.bz2" }
37
+ let(:index_url) { "#{BASE}/#{DATE}/#{prefix}-index.txt.bz2" }
38
+
39
+ def serve_listing(*dates)
40
+ stub_request(:get, "#{BASE}/").to_return(body: dates.map { |d| %(<a href="#{d}/">#{d}/</a>) }.join("\n"))
41
+ end
42
+
43
+ def serve_status(date, status: "done")
44
+ stub_request(:get, "#{BASE}/#{date}/dumpstatus.json")
45
+ .to_return(body: dump_status_json("test", date, index: index_bytes, dump: dump_bytes, status: status))
46
+ end
47
+
48
+ def serve_index
49
+ stub_request(:head, index_url).to_return(headers: { "Content-Length" => index_bytes.bytesize.to_s,
50
+ "Accept-Ranges" => "bytes" })
51
+ stub_request(:get, index_url).to_return(body: index_bytes)
52
+ end
53
+
54
+ # Serve byte ranges of the dump; the block may alter each response
55
+ def serve_ranges(&alter)
56
+ stub_request(:get, dump_url).to_return do |request|
57
+ first, last = request.headers["Range"].to_s.match(/bytes=(\d+)-(\d+)/).captures.map(&:to_i)
58
+ response = { status: 206, body: dump_bytes.byteslice(first..last),
59
+ headers: { "Content-Range" => "bytes #{first}-#{last}/#{dump_bytes.bytesize}" } }
60
+ alter ? alter.call(response, first, last) : response
61
+ end
62
+ end
63
+
64
+ def manager(**opts)
65
+ Wp2txt::DumpManager.new(:test, cache_dir: cache_dir, **opts).tap { |m| allow(m).to receive(:sleep) }
66
+ end
67
+
68
+ def serve_version
69
+ serve_listing(DATE)
70
+ serve_status(DATE)
71
+ serve_index
72
+ end
73
+
74
+ def extract(mgr, titles)
75
+ index = Wp2txt::MultistreamIndex.new(mgr.download_index, use_cache: false, show_progress: false)
76
+ entries = titles.map { |t| index.find_by_title(t) }
77
+ offsets = index.stream_offsets
78
+ ranges = entries.map { |e| [e[:offset], offsets[offsets.index(e[:offset]) + 1] || mgr.snapshot.dump_file.size] }
79
+ reader = Wp2txt::MultistreamReader.new(mgr.fetch_streams(ranges), index)
80
+ reader.each_entry_result(entries).to_h { |e, page, error| [e[:title], page ? page[:text] : error[:reason]] }
81
+ end
82
+
83
+ describe "choosing the dump version" do
84
+ it "uses the newest finished version and skips one still in progress" do
85
+ serve_listing("20260201", DATE)
86
+ serve_status("20260201", status: "in-progress")
87
+ serve_status(DATE)
88
+ expect(manager.snapshot.date).to eq(DATE)
89
+ end
90
+
91
+ it "refuses a requested date whose dump is not finished" do
92
+ serve_status(DATE, status: "in-progress")
93
+ expect { manager(dump_date: DATE).snapshot }.to raise_error(Wp2txt::SnapshotError, /in-progress/)
94
+ end
95
+
96
+ it "uses the version checked recently without asking the server again" do
97
+ serve_listing(DATE)
98
+ serve_status(DATE)
99
+ first = manager.snapshot
100
+ WebMock.reset!
101
+ expect(manager.snapshot.id).to eq(first.id)
102
+ end
103
+
104
+ it "asks the server again with update, even after a recent check" do
105
+ serve_listing(DATE)
106
+ serve_status(DATE)
107
+ manager.snapshot
108
+ manager(update: true).snapshot
109
+ expect(a_request(:get, "#{BASE}/")).to have_been_made.twice
110
+ end
111
+
112
+ it "falls back to the newest cached version when the server cannot be reached" do
113
+ serve_listing(DATE)
114
+ serve_status(DATE)
115
+ cached = manager(dump_expiry_days: 0).snapshot
116
+ WebMock.reset!
117
+ stub_request(:get, "#{BASE}/").to_raise(SocketError.new("offline"))
118
+ fallback = manager(dump_expiry_days: 0)
119
+ expect { fallback.snapshot }.to output(/using the cached dump of #{DATE}/).to_stderr
120
+ expect(fallback.snapshot.id).to eq(cached.id)
121
+ end
122
+
123
+ it "uses a cached version of a requested date offline" do
124
+ serve_listing(DATE)
125
+ serve_status(DATE)
126
+ manager.snapshot
127
+ WebMock.reset!
128
+ expect(manager(dump_date: DATE).snapshot.date).to eq(DATE)
129
+ end
130
+ end
131
+
132
+ describe "the index file" do
133
+ it "is checked against the version's SHA-1 and replaced, not reused, when it differs" do
134
+ serve_version
135
+ FileUtils.mkdir_p(cache_dir)
136
+ stale = File.join(cache_dir, "testwiki-#{DATE}-multistream-index.txt.bz2")
137
+ File.binwrite(stale, "x" * index_bytes.bytesize)
138
+
139
+ mgr = manager
140
+ expect { mgr.download_index }.to output(/set aside/).to_stderr.and output(/Downloading index/).to_stdout
141
+ expect(File.binread(stale)).to eq(index_bytes)
142
+ expect(Dir.children(cache_dir)).to include(a_string_matching(/index\.txt\.bz2\.bad-/))
143
+ expect { manager.download_index }.to output(/Using cached index/).to_stdout
144
+ end
145
+
146
+ it "keeps giving the checked file when another file of the same size and time takes its name" do
147
+ serve_version
148
+ mgr = manager
149
+ pinned = nil
150
+ expect { pinned = mgr.download_index }.to output.to_stdout
151
+ path = mgr.cached_index_path
152
+ stat = File.stat(path)
153
+ replacement = "#{path}.new"
154
+ File.binwrite(replacement, "z" * stat.size)
155
+ File.utime(stat.atime, stat.mtime, replacement)
156
+ File.rename(replacement, path)
157
+ again = nil
158
+ expect { again = manager.download_index }.to output(/Using cached index/).to_stdout
159
+ expect(again).to eq(pinned)
160
+ expect(File.binread(again)).to eq(index_bytes)
161
+ end
162
+
163
+ it "is not pinned when another file takes its name while it is being checked" do
164
+ serve_version
165
+ FileUtils.mkdir_p(cache_dir)
166
+ path = File.join(cache_dir, "testwiki-#{DATE}-multistream-index.txt.bz2")
167
+ File.binwrite(path, index_bytes)
168
+ other = "#{path}.other"
169
+ File.binwrite(other, index_bytes)
170
+ allow(File).to receive(:link).and_wrap_original do |original, source, target|
171
+ File.rename(other, source)
172
+ original.call(source, target)
173
+ end
174
+ expect { manager.download_index }.to raise_error(Wp2txt::SnapshotError, /changed while/)
175
+ end
176
+
177
+ it "is not used when the cache cannot keep it for the version, whether cached or fetched" do
178
+ serve_version
179
+ allow(File).to receive(:link).and_raise(Errno::EXDEV)
180
+ expect { manager.download_index }.to raise_error(Wp2txt::SnapshotError, /hard links/).and output.to_stdout
181
+ FileUtils.mkdir_p(cache_dir)
182
+ File.binwrite(File.join(cache_dir, "testwiki-#{DATE}-multistream-index.txt.bz2"), index_bytes)
183
+ expect { manager.download_index }.to raise_error(Wp2txt::SnapshotError, /hard links/)
184
+ end
185
+
186
+ it "is checked again when its kept file no longer has the version's size" do
187
+ serve_version
188
+ pinned = nil
189
+ expect { pinned = manager.download_index }.to output.to_stdout
190
+ File.truncate(pinned, 0)
191
+ expect { manager.download_index }.to output(/set aside/).to_stderr.and output(/index/).to_stdout
192
+ expect(File.binread(pinned)).to eq(index_bytes)
193
+ end
194
+
195
+ it "lets tools that read the shared name use it only while it names the version's file" do
196
+ serve_version
197
+ mgr = manager
198
+ expect { mgr.download_index }.to output.to_stdout
199
+ shared = mgr.cached_index_path
200
+ File.binwrite("#{shared}.other", "another version")
201
+ File.rename("#{shared}.other", shared)
202
+ expect(mgr.mismatched_cached_files).to include(File.basename(shared))
203
+ mgr.align_cached_names!
204
+ expect(File.binread(shared)).to eq(index_bytes)
205
+ expect(mgr.mismatched_cached_files).not_to include(File.basename(shared))
206
+ end
207
+
208
+ it "is not put in place when the download does not match the version" do
209
+ serve_listing(DATE)
210
+ serve_status(DATE)
211
+ stub_request(:head, index_url).to_return(headers: { "Content-Length" => index_bytes.bytesize.to_s })
212
+ stub_request(:get, index_url).to_return(body: "y" * index_bytes.bytesize)
213
+ mgr = manager
214
+ expect { mgr.download_index }.to raise_error(Wp2txt::NetworkError, /SHA-1/).and output.to_stdout
215
+ expect(File.exist?(mgr.cached_index_path)).to be(false)
216
+ end
217
+ end
218
+
219
+ describe "fetching ranges" do
220
+ it "reads articles from the first and the last range without the rest of the dump" do
221
+ serve_version
222
+ serve_ranges
223
+ result = nil
224
+ expect { result = extract(manager, ["Film A", "Category:Films"]) }.to output(/Fetching 2 range/).to_stdout
225
+ expect(result).to include("Film A" => a_string_including("Story here."), "Category:Films" => "Top category.\n")
226
+ end
227
+
228
+ it "keeps a fetched range for the next run" do
229
+ serve_version
230
+ serve_ranges
231
+ expect { extract(manager, ["Film A"]) }.to output.to_stdout
232
+ WebMock.reset!
233
+ serve_version
234
+ result = nil
235
+ expect { result = extract(manager, ["Film A"]) }.to output(/\AUsing cached index[^\n]*\n\z/).to_stdout
236
+ expect(result["Film A"]).to include("Story here.")
237
+ expect(a_request(:get, dump_url)).not_to have_been_made
238
+ end
239
+
240
+ it "sets aside a damaged cached range and fetches it again" do
241
+ serve_version
242
+ serve_ranges
243
+ expect { extract(manager, ["Film A"]) }.to output.to_stdout
244
+ stored = Dir.glob(File.join(cache_dir, "*", "streams", "*.bz2")).first
245
+ File.binwrite(stored, "\0" * File.size(stored))
246
+ result = nil
247
+ expect { result = extract(manager, ["Film A"]) }.to output(/Fetching 1 range/).to_stdout.and output(/damaged/).to_stderr
248
+ expect(result["Film A"]).to include("Story here.")
249
+ expect(Dir.glob(File.join(cache_dir, "*", "streams", "*.bad-*")).size).to eq(1)
250
+ end
251
+
252
+ it "refuses ranges of a file that changed on the server since an earlier range" do
253
+ serve_version
254
+ etag = '"one"'
255
+ serve_ranges { |response, _first, _last| response.merge(headers: response[:headers].merge("ETag" => etag)) }
256
+ expect { extract(manager, ["Film A"]) }.to output.to_stdout
257
+ etag = '"two"'
258
+ result = nil
259
+ expect { result = extract(manager, ["Category:Films"]) }
260
+ .to output.to_stdout.and output(/not the one fetched before/).to_stderr
261
+ expect(result).to eq("Category:Films" => :stream_unavailable)
262
+ end
263
+
264
+ it "tries again after a short response" do
265
+ serve_version
266
+ calls = 0
267
+ serve_ranges do |response, _first, _last|
268
+ calls += 1
269
+ calls == 1 ? response.merge(body: response[:body].byteslice(0, 10)) : response
270
+ end
271
+ result = nil
272
+ expect { result = extract(manager, ["Film A"]) }.to output.to_stdout.and output(/attempt 1/).to_stderr
273
+ expect(result["Film A"]).to include("Story here.")
274
+ end
275
+
276
+ {
277
+ "a whole-file answer to a range request" => ->(r, _f, _l) { r.merge(status: 200) },
278
+ "a Content-Range for other bytes" => ->(r, f, l) { r.merge(headers: { "Content-Range" => "bytes #{f + 1}-#{l + 1}/9" }) },
279
+ "a Content-Range without the whole size" => ->(r, f, l) { r.merge(headers: { "Content-Range" => "bytes #{f}-#{l}/*" }) },
280
+ "more bytes than asked for" => ->(r, _f, _l) { r.merge(body: "#{r[:body]}extra") },
281
+ "data that does not decompress" => ->(r, _f, _l) { r.merge(body: "\0" * r[:body].bytesize) }
282
+ }.each do |label, alter|
283
+ it "leaves the range out, and its articles unavailable, after #{label}" do
284
+ serve_version
285
+ serve_ranges(&alter)
286
+ result = nil
287
+ expect { result = extract(manager, ["Film A"]) }.to output.to_stdout.and output(/Could not fetch/).to_stderr
288
+ expect(result).to eq("Film A" => :stream_unavailable)
289
+ expect(Dir.glob(File.join(cache_dir, "**", "*.bz2*")).grep(/streams/)).to be_empty
290
+ end
291
+ end
292
+ end
293
+ end