crawlscope 0.10.2 → 0.11.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.
@@ -0,0 +1,337 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+ require "stringio"
5
+
6
+ class CrawlscopeLinkMapTest < Minitest::Test
7
+ ORIGIN = "https://example.com"
8
+
9
+ def setup
10
+ WebMock.reset!
11
+ @directory = Dir.mktmpdir
12
+ @sitemap = File.join(@directory, "sitemap.xml")
13
+ stub_request(:get, "#{ORIGIN}/robots.txt").to_return(status: 404)
14
+ end
15
+
16
+ def teardown
17
+ FileUtils.remove_entry(@directory)
18
+ end
19
+
20
+ def test_sitemap_graph_records_occurrences_diagnostics_and_independent_shortest_depths
21
+ sitemap("/", "/catalog/", "/priority", "/orphan", "/cluster-a", "/cluster-b", "/old", "/gone", "/noindex", "/failed", "/nofollow-only")
22
+ html("/", <<~HTML)
23
+ <nav><a href="/catalog/">Catalog</a><a href="/nofollow-only" rel="nofollow">Hidden from traversal</a></nav>
24
+ <main><a href="/catalog/#details"><img alt="Ver catálogo" src="/image.jpg"></a>
25
+ <a href="/catalog/">Browse</a><a href="/old">Old</a><a href="/gone">Gone</a></main>
26
+ <footer><a href="/noindex">Terms</a></footer>
27
+ <aside><a href="/priority?utm_campaign=private-tracking">Promo</a></aside>
28
+ <a href="https://other.example/private">External</a>
29
+ HTML
30
+ html("/catalog/", '<main><a href="../priority">Priority</a><a href="/">Home</a></main>')
31
+ html("/priority", '<link rel="canonical" href="/catalog/"><h1>Priority</h1>')
32
+ html("/orphan", "<h1>Orphan</h1>")
33
+ html("/cluster-a", '<main><a href="/cluster-b">Next</a></main>')
34
+ html("/cluster-b", '<main><a href="/cluster-a">Back</a></main>')
35
+ stub_request(:get, "#{ORIGIN}/old").to_return(status: 302, headers: {"Location" => "/catalog/"})
36
+ stub_request(:get, "#{ORIGIN}/gone").to_return(status: 404)
37
+ html("/noindex", '<meta name="robots" content="noindex">')
38
+ html("/nofollow-only", "<h1>Unreached</h1>")
39
+ stub_request(:get, "#{ORIGIN}/failed").to_timeout
40
+
41
+ settings = {
42
+ inventory: ["/priority", "/search-console-only", "https://outside.example/private"],
43
+ manifest: {
44
+ pages: {"/priority" => {priority: true, cluster: "products", page_type: "guide"}},
45
+ edges: [
46
+ {source: "/", target: "/priority", type: "recommendation", reason: "Useful starting point", position: "main"},
47
+ {source: "/failed", target: "/priority", type: "related", reason: "Related product"},
48
+ {source: "/", target: "/orphan", type: "navigation", reason: "Help users", approved_exception: "Archived"}
49
+ ]
50
+ }
51
+ }
52
+ report = crawl(**settings)
53
+ data = report.to_h
54
+ nodes = data[:nodes].to_h { |node| [node[:url].delete_prefix(ORIGIN), node] }
55
+ expected_depths = {
56
+ "/" => 0, "/catalog/" => 1, "/old" => 1, "/priority" => 2, "/noindex" => 1
57
+ }
58
+ assert_equal expected_depths, nodes.filter_map { |path, node| [path, node[:click_depth]] unless node[:click_depth].nil? }.to_h
59
+ assert nodes["/orphan"][:sitemap_only]
60
+ assert_equal [[url("/cluster-a"), url("/cluster-b")]], data[:unreachable_clusters]
61
+ assert_equal "fetch_failed", nodes["/failed"][:coverage]
62
+ assert_equal "unobserved", nodes["/search-console-only"][:coverage]
63
+ assert_equal false, nodes["/noindex"][:indexable]
64
+ assert_equal false, nodes["/priority"][:indexable]
65
+ assert_equal 1, nodes["/priority"][:contextual_inbound_sources]
66
+ assert_equal [302, 200, url("/catalog/")], nodes["/old"].values_at(:status, :resolved_status, :resolved_url)
67
+ assert_includes data[:issues].map { |issue| issue[:code] }, :broken_target
68
+ missing = data[:issues].find { |issue| issue[:code] == :missing_expected_edge }
69
+ assert_equal url("/"), missing[:url]
70
+ assert_equal url("/priority"), missing[:details][:target_url]
71
+ assert_equal %w[excepted missing unknown], data[:expected_edges].map { |edge| edge[:state] }
72
+ assert_equal 1, data[:exclusions]["inventory:outside_origin"]
73
+ refute_includes JSON.generate(data), "private-tracking"
74
+
75
+ pair = data[:pairs].find { |edge| edge.values_at(:source_url, :target_url) == [url("/"), url("/catalog/")] }
76
+ assert_equal [3, 2], pair.values_at(:occurrences, :contextual_occurrences)
77
+ image = data[:occurrences].find { |edge| edge[:image_alt] == "Ver catálogo" }
78
+ assert_equal ["/catalog/", "main", true], image.values_at(:raw_href, :position, :contextual)
79
+ assert_equal %w[footer main nav sidebar], data[:occurrences].select { |edge| edge[:source_url] == url("/") }.map { |edge| edge[:position] }.uniq.sort
80
+ assert_equal [url("/catalog/"), url("/priority")], report.to_h(view: :contextual, priority: true, cluster: "products")[:occurrences].first.values_at(:source_url, :target_url)
81
+ assert_equal JSON.generate(data), JSON.generate(crawl(**settings).to_h)
82
+ end
83
+
84
+ def test_bounded_follow_respects_entry_connectivity_robots_scope_and_caps
85
+ sitemap("/", "/unreachable", "/failed")
86
+ stub_request(:get, url("/robots.txt")).to_return(body: <<~ROBOTS)
87
+ User-agent: *
88
+ Disallow: /a
89
+ User-agent: Crawlscope
90
+ Disallow: /private*
91
+ Allow: /private-public$
92
+ Disallow: /%73ecret
93
+ ROBOTS
94
+ html("/", <<~HTML)
95
+ <a href="/a">A</a><a href="/private">Private</a><a href="/private-public">Allowed by robots</a>
96
+ <a href="/secret">Secret</a><a href="/removed">Out of scope</a>
97
+ <a href="/unsupported" rel="nofollow">Nofollow</a>
98
+ <a href="/tracked?token=do-not-export">Tracked</a>
99
+ HTML
100
+ html("/unreachable", '<a href="/undiscovered">Undiscovered</a>')
101
+ stub_request(:get, url("/failed")).to_return(status: 307, headers: {"Location" => "https://other.example/nope"})
102
+ html("/a", '<a href="/deep">Deep</a>')
103
+ html("/private-public", "<h1>Public</h1>")
104
+
105
+ bounded = crawl(follow_limit: 2, follow_depth: 1, exclude_paths: ["/removed"]).to_h
106
+ nodes = bounded[:nodes].to_h { |node| [node[:url], node] }
107
+ assert_equal 1, nodes[url("/a")][:click_depth]
108
+ assert_equal 1, nodes[url("/private-public")][:click_depth]
109
+ assert_equal "robots_disallowed", nodes[url("/private")][:coverage]
110
+ assert_equal "robots_disallowed", nodes[url("/secret")][:coverage]
111
+ assert_equal "outside_origin", nodes[url("/failed")][:redirect_exclusion]
112
+ assert_equal "unobserved", nodes[url("/deep")][:coverage]
113
+ assert_equal "unobserved", nodes[url("/undiscovered")][:coverage]
114
+ refute nodes.key?(url("/removed"))
115
+ %w[/deep /private /secret /removed /unsupported /undiscovered /tracked?token=do-not-export].each do |path|
116
+ assert_not_requested(:get, url(path))
117
+ end
118
+ assert_not_requested(:get, "https://other.example/nope")
119
+ refute_includes JSON.generate(bounded), "do-not-export"
120
+
121
+ limited = crawl(follow_limit: 1, follow_depth: 2, exclude_paths: ["/removed"]).to_h
122
+ assert_equal ["page_limit"], limited[:nodes].select { |node| node[:url] == url("/private-public") }.map { |node| node[:coverage] }
123
+ assert_requested(:get, url("/private-public"), times: 1)
124
+ end
125
+
126
+ def test_cli_exports_csv_and_dot_and_diffs_a_real_link_edit
127
+ sitemap("/", "/priority")
128
+ html("/", '<nav><a href="/priority">Priority</a></nav>')
129
+ html("/priority", "<h1>Priority</h1>")
130
+ manifest = File.join(@directory, "links.json")
131
+ inventory = File.join(@directory, "pages.csv")
132
+ File.write(manifest, JSON.generate(
133
+ pages: {"/priority" => {priority: true}},
134
+ edges: [{source: "/", target: "/priority", type: "next_step", position: "main", reason: "Guide readers"}]
135
+ ))
136
+ File.write(inventory, "Top pages,Clicks\n#{url("/priority")},12\n")
137
+ options = ["--manifest", manifest, "--inventory", inventory]
138
+ before = cli(*options)
139
+ html("/", '<nav><a href="/priority">Priority</a></nav><main><a href="/priority">=HYPERLINK()</a></main>')
140
+ after = cli(*options)
141
+ assert JSON.parse(after)["nodes"].find { |node| node["url"] == url("/priority") }["inventory"]
142
+
143
+ paths = [before, after].each_with_index.map do |snapshot, index|
144
+ path = File.join(@directory, "#{index}.json")
145
+ File.write(path, snapshot)
146
+ path
147
+ end
148
+ diff = JSON.parse(cli("diff", *paths))
149
+ assert_equal 1, diff.dig("nodes", "changed", 0, "after", "contextual_inbound_sources")
150
+ assert_equal 2, diff.dig("pairs", "changed", 0, "after", "occurrences")
151
+ assert_equal 1, diff.dig("pairs", "changed", 0, "after", "contextual_occurrences")
152
+ assert_equal "observed", diff.dig("expected_edges", "changed", 0, "after", "state")
153
+
154
+ csv = CSV.parse(cli("--format", "csv", "--view", "contextual"), headers: true)
155
+ assert_equal 1, csv.size
156
+ assert_equal "'=HYPERLINK()", csv.first["anchor_text"]
157
+ assert_includes cli("--format", "dot"), "\"#{url("/")}\" -> \"#{url("/priority")}\" [label=\"2\"]"
158
+ assert_includes cli("--format", "text"), "Public HTTP crawl"
159
+ end
160
+
161
+ def test_edge_limit_only_makes_truncated_sources_inconclusive
162
+ sitemap("/", "/a", "/b")
163
+ html("/", '<main><a href="/a">A</a><a href="/b">B</a></main>')
164
+ html("/a", "<h1>A</h1>")
165
+ html("/b", "<h1>B</h1>")
166
+ manifest = {
167
+ edges: [
168
+ {source: "/", target: "/b", type: "next_step", reason: "Review B"},
169
+ {source: "/a", target: "/b", type: "next_step", reason: "Review B"}
170
+ ]
171
+ }
172
+
173
+ report = crawl(max_edges: 1, manifest: manifest).to_h
174
+ nodes = report[:nodes].to_h { |node| [node[:url], node] }
175
+ assert_equal false, nodes[url("/")][:outgoing_complete]
176
+ assert_equal true, nodes[url("/a")][:outgoing_complete]
177
+ assert_equal %w[unknown missing], report[:expected_edges].map { |edge| edge[:state] }
178
+ assert_equal 1, report[:exclusions]["link:edge_limit"]
179
+ end
180
+
181
+ def test_validate_shows_link_map_from_already_fetched_pages_and_preserves_failure_status
182
+ sitemap("/", "/guide", "/orphan", "/missing")
183
+ html("/", '<nav><a href="/guide">Guide</a></nav>')
184
+ html("/guide", "<h1>Guide</h1>")
185
+ html("/orphan", "<h1>Orphan</h1>")
186
+ stub_request(:get, url("/missing")).to_return(status: 404)
187
+ arguments = ["validate", "--url", ORIGIN, "--sitemap", @sitemap, "--rules", "indexability"]
188
+
189
+ summary = StringIO.new
190
+ assert_equal 1, Crawlscope::Cli.start(arguments, out: summary, err: StringIO.new)
191
+ assert_includes summary.string, "HTML fetched during validation"
192
+ assert_match(/Sitemap URLs reached\s+2 \/ 4/, summary.string)
193
+ assert_match(/HTML URLs with no observed path\s+1/, summary.string)
194
+ assert_match(/Sitemap URLs without verified HTML\s+1/, summary.string)
195
+ assert_match(/Unique internal link pairs\s+1/, summary.string)
196
+ assert_match(/Pages with no contextual inlinks\s+2/, summary.string)
197
+ assert_includes summary.string, "Coverage is partial"
198
+ assert_includes summary.string, "--format csv --table nodes > nodes.csv"
199
+ assert_includes summary.string, "--format dot > links.dot"
200
+ assert_includes summary.string, "sfdp -Gsplines=line -Tsvg links.dot -o links.svg"
201
+ assert_not_requested(:get, url("/robots.txt"))
202
+ %w[/ /guide /orphan /missing].each do |path|
203
+ assert_requested(:get, url(path), times: 1)
204
+ end
205
+
206
+ normal = StringIO.new
207
+ assert_equal 1, Crawlscope::Cli.start([*arguments, "--no-link-map"], out: normal, err: StringIO.new)
208
+ refute_includes normal.string, "Internal link map"
209
+ assert summary.string.start_with?(normal.string)
210
+ end
211
+
212
+ def test_validate_describes_an_entry_root_missing_from_the_sitemap_without_fetching_it
213
+ sitemap("/guide")
214
+ html("/guide", "<main><a href='/'>Home</a></main>")
215
+
216
+ output = StringIO.new
217
+ arguments = ["validate", "--url", ORIGIN, "--sitemap", @sitemap, "--rules", "indexability"]
218
+ assert_equal 0, Crawlscope::Cli.start(arguments, out: output, err: StringIO.new)
219
+ assert_includes output.string, "Entry root HTML unavailable in this snapshot."
220
+ assert_match(/Sitemap URLs reached\s+0 \/ 1/, output.string)
221
+ assert_not_requested(:get, url("/"))
222
+ end
223
+
224
+ def test_invalid_cli_export_format_reports_an_option_error
225
+ out = StringIO.new
226
+ err = StringIO.new
227
+
228
+ assert_equal 1, Crawlscope::Cli.start(%w[link-map --format svg], out: out, err: err)
229
+ assert_empty out.string
230
+ assert_includes err.string, "invalid argument: --format svg"
231
+ end
232
+
233
+ def test_rake_validation_suggests_rake_exports_with_the_same_sitemap
234
+ sitemap("/", "/guide")
235
+ html("/", '<a href="/guide">Guide</a>')
236
+ html("/guide", "<h1>Guide</h1>")
237
+
238
+ output, errors = capture_io do
239
+ Crawlscope::RakeTasks.validate(url: ORIGIN, sitemap_path: @sitemap, rule_names: "indexability")
240
+ end
241
+
242
+ assert_empty errors
243
+ args = "URL=#{ORIGIN} SITEMAP=#{@sitemap}"
244
+ assert_includes output, "rake crawlscope:link_map #{args} > links.json"
245
+ assert_includes output, "rake 'crawlscope:link_map[,,csv,nodes]' #{args} > nodes.csv"
246
+ assert_includes output, "rake 'crawlscope:link_map[,,dot]' #{args} > links.dot"
247
+ assert_includes output, "sfdp -Gsplines=line -Tsvg links.dot -o links.svg"
248
+ end
249
+
250
+ def test_dot_exports_all_nodes_and_pairs_above_the_previous_size_cutoff
251
+ urls = Array.new(151) { |index| url("/page-#{index}") }
252
+ nodes = urls.map { |url| {url: url} }
253
+ pairs = urls.each_with_index.flat_map do |source, index|
254
+ (1..4).map do |offset|
255
+ {source_url: source, target_url: urls[(index + offset) % urls.size], occurrences: 1}
256
+ end
257
+ end
258
+ output = StringIO.new
259
+
260
+ Crawlscope::LinkMap::Report.new(nodes: nodes, pairs: pairs).write(output, format: :dot)
261
+
262
+ assert_equal 151, output.string.lines.count { |line| line.include?("style=dashed") }
263
+ assert_equal 604, output.string.lines.count { |line| line.include?(" -> ") }
264
+ end
265
+
266
+ def test_validation_snapshot_ignores_links_in_rendered_error_pages
267
+ root = url("/")
268
+ page = Crawlscope::Page.new(
269
+ url: root, final_url: root, normalized_url: root, normalized_final_url: root,
270
+ status: 404, headers: {"Content-Type" => "text/html"}, body: nil,
271
+ doc: Nokogiri::HTML('<a href="/error-help">Help</a>')
272
+ )
273
+
274
+ report = Crawlscope::LinkMap::Audit.new(base_url: ORIGIN).from_pages(urls: [root], pages: [page]).to_h
275
+ assert_nil report[:nodes].first[:click_depth]
276
+ assert_empty report[:occurrences]
277
+ end
278
+
279
+ def test_remote_sitemap_children_stay_on_origin_and_robots_failure_is_closed
280
+ remote_sitemap = url("/sitemap.xml")
281
+ stub_request(:get, remote_sitemap).to_return(body: <<~XML)
282
+ <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
283
+ <sitemap><loc>https://elsewhere.example/sitemap.xml</loc></sitemap>
284
+ <sitemap><loc>/child.xml</loc></sitemap>
285
+ <sitemap><loc>/unavailable.xml</loc></sitemap>
286
+ </sitemapindex>
287
+ XML
288
+ stub_request(:get, url("/child.xml")).to_return(body: sitemap_xml("/", "https://elsewhere.example/external", "/private"))
289
+ stub_request(:get, url("/unavailable.xml")).to_return(status: 503)
290
+ stub_request(:get, url("/robots.txt")).to_return(status: 503)
291
+ report = crawl(sitemap_path: remote_sitemap).to_h
292
+
293
+ assert_equal "unavailable", report[:robots]
294
+ assert_equal ["robots_unavailable"], report[:nodes].map { |node| node[:coverage] }.uniq
295
+ assert_equal 1, report[:exclusions]["sitemap:outside_origin"]
296
+ assert_equal 1, report[:exclusions]["sitemap:excluded_child"]
297
+ assert_equal 1, report[:exclusions]["sitemap:unavailable_child"]
298
+ assert_not_requested(:get, url("/"))
299
+ assert_not_requested(:get, url("/private"))
300
+ assert_not_requested(:get, "https://elsewhere.example/sitemap.xml")
301
+ end
302
+
303
+ private
304
+
305
+ def sitemap(*paths)
306
+ File.write(@sitemap, sitemap_xml(*paths))
307
+ end
308
+
309
+ def sitemap_xml(*paths)
310
+ locations = paths.map { |path| "<url><loc>#{path.start_with?("/") ? url(path) : path}</loc></url>" }.join
311
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">#{locations}</urlset>"
312
+ end
313
+
314
+ def url(path)
315
+ "#{ORIGIN}#{path}"
316
+ end
317
+
318
+ def html(path, body)
319
+ stub_request(:get, url(path)).to_return(body: body, headers: {"Content-Type" => "text/html; charset=utf-8"})
320
+ end
321
+
322
+ def crawl(**options)
323
+ configuration = Crawlscope::Configuration.new
324
+ configuration.fetch_executor = :threaded
325
+ Crawlscope::Run.new(configuration: configuration).link_map(base_url: ORIGIN, sitemap_path: @sitemap, **options)
326
+ end
327
+
328
+ def cli(*arguments)
329
+ arguments = ["--url", ORIGIN, "--sitemap", @sitemap, *arguments] unless arguments.first == "diff"
330
+ out = StringIO.new
331
+ err = StringIO.new
332
+ status = Crawlscope::Cli.start(["link-map", *arguments], out: out, err: err)
333
+ assert_equal 0, status, err.string
334
+ assert_empty err.string
335
+ out.string
336
+ end
337
+ end
@@ -59,6 +59,16 @@ class CrawlscopeRakeTasksTest < Minitest::Test
59
59
  )
60
60
  end
61
61
 
62
+ def test_link_map_passes_rake_arguments_to_cli
63
+ calls = capture_cli_calls
64
+
65
+ Crawlscope::RakeTasks.link_map(url: "http://localhost:3001", sitemap_path: "sitemap.xml", format: "csv", table: "nodes")
66
+
67
+ call = calls.fetch(0)
68
+ assert_equal ["link-map", "--url", "http://localhost:3001", "--sitemap", "sitemap.xml", "--format", "csv", "--table", "nodes"], call.fetch(:argv)
69
+ assert_same Crawlscope.configuration, call.fetch(:kwargs).fetch(:configuration)
70
+ end
71
+
62
72
  def test_run_passes_the_shared_configuration_to_cli
63
73
  calls = capture_cli_calls
64
74
  configuration = Crawlscope.configuration
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: crawlscope
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.10.2
4
+ version: 0.11.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Paulo Fidalgo
@@ -24,6 +24,20 @@ dependencies:
24
24
  - - ">="
25
25
  - !ruby/object:Gem::Version
26
26
  version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: csv
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '3.3'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '3.3'
27
41
  - !ruby/object:Gem::Dependency
28
42
  name: async
29
43
  requirement: !ruby/object:Gem::Requirement
@@ -179,6 +193,7 @@ files:
179
193
  - README.md
180
194
  - UPGRADE.md
181
195
  - docs/architecture.md
196
+ - docs/link-map.md
182
197
  - docs/rails.md
183
198
  - docs/rules.md
184
199
  - docs/server-timing.md
@@ -202,6 +217,14 @@ files:
202
217
  - lib/crawlscope/http.rb
203
218
  - lib/crawlscope/issue.rb
204
219
  - lib/crawlscope/issue_collection.rb
220
+ - lib/crawlscope/link_map/audit.rb
221
+ - lib/crawlscope/link_map/extractor.rb
222
+ - lib/crawlscope/link_map/graph.rb
223
+ - lib/crawlscope/link_map/manifest.rb
224
+ - lib/crawlscope/link_map/report.rb
225
+ - lib/crawlscope/link_map/robots_policy.rb
226
+ - lib/crawlscope/link_map/scope.rb
227
+ - lib/crawlscope/link_map/sitemap_urls.rb
205
228
  - lib/crawlscope/page.rb
206
229
  - lib/crawlscope/rails.rb
207
230
  - lib/crawlscope/railtie.rb
@@ -260,6 +283,7 @@ files:
260
283
  - test/crawlscope/http_test.rb
261
284
  - test/crawlscope/indexability_rule_test.rb
262
285
  - test/crawlscope/install_generator_test.rb
286
+ - test/crawlscope/link_map_test.rb
263
287
  - test/crawlscope/links_rule_test.rb
264
288
  - test/crawlscope/loader_test.rb
265
289
  - test/crawlscope/metadata_rule_test.rb