crawlscope 0.10.1 → 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.
Files changed (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +27 -0
  3. data/README.md +7 -0
  4. data/UPGRADE.md +84 -0
  5. data/docs/architecture.md +73 -0
  6. data/docs/link-map.md +203 -0
  7. data/docs/rails.md +9 -0
  8. data/docs/rules.md +49 -0
  9. data/lib/crawlscope/cli.rb +86 -5
  10. data/lib/crawlscope/configuration.rb +2 -1
  11. data/lib/crawlscope/crawl.rb +11 -79
  12. data/lib/crawlscope/crawling/fetcher_factory.rb +31 -0
  13. data/lib/crawlscope/crawling/target.rb +45 -0
  14. data/lib/crawlscope/crawling/target_resolver.rb +75 -0
  15. data/lib/crawlscope/documents/canonical.rb +22 -0
  16. data/lib/crawlscope/documents/robots.rb +57 -0
  17. data/lib/crawlscope/http.rb +37 -13
  18. data/lib/crawlscope/link_map/audit.rb +240 -0
  19. data/lib/crawlscope/link_map/extractor.rb +59 -0
  20. data/lib/crawlscope/link_map/graph.rb +165 -0
  21. data/lib/crawlscope/link_map/manifest.rb +68 -0
  22. data/lib/crawlscope/link_map/report.rb +217 -0
  23. data/lib/crawlscope/link_map/robots_policy.rb +72 -0
  24. data/lib/crawlscope/link_map/scope.rb +82 -0
  25. data/lib/crawlscope/link_map/sitemap_urls.rb +103 -0
  26. data/lib/crawlscope/page.rb +4 -0
  27. data/lib/crawlscope/rake_tasks.rb +11 -1
  28. data/lib/crawlscope/reporter.rb +19 -162
  29. data/lib/crawlscope/reporting/issue_presenter.rb +162 -0
  30. data/lib/crawlscope/reporting/url_formatter.rb +29 -0
  31. data/lib/crawlscope/rule_registry.rb +2 -2
  32. data/lib/crawlscope/rules/content_quality.rb +18 -0
  33. data/lib/crawlscope/rules/indexability.rb +9 -14
  34. data/lib/crawlscope/rules/links/canonical_checks.rb +102 -0
  35. data/lib/crawlscope/rules/links/extractor.rb +100 -0
  36. data/lib/crawlscope/rules/links/graph.rb +39 -0
  37. data/lib/crawlscope/rules/links/inbound_checks.rb +124 -0
  38. data/lib/crawlscope/rules/links/outgoing_checks.rb +104 -0
  39. data/lib/crawlscope/rules/links/resolution_check.rb +88 -0
  40. data/lib/crawlscope/rules/links/scope.rb +23 -0
  41. data/lib/crawlscope/rules/links/target_lookup.rb +38 -0
  42. data/lib/crawlscope/rules/links/url_checks.rb +54 -0
  43. data/lib/crawlscope/rules/links.rb +18 -600
  44. data/lib/crawlscope/rules/metadata.rb +2 -2
  45. data/lib/crawlscope/rules/structured_data.rb +26 -77
  46. data/lib/crawlscope/rules/uniqueness.rb +1 -1
  47. data/lib/crawlscope/run.rb +16 -0
  48. data/lib/crawlscope/schemas.rb +10 -2
  49. data/lib/crawlscope/server_timing/reporter.rb +2 -13
  50. data/lib/crawlscope/sitemap.rb +16 -5
  51. data/lib/crawlscope/structured_data/audit.rb +17 -76
  52. data/lib/crawlscope/structured_data/check.rb +2 -0
  53. data/lib/crawlscope/structured_data/document.rb +14 -1
  54. data/lib/crawlscope/structured_data/entry.rb +31 -0
  55. data/lib/crawlscope/structured_data/outcome.rb +11 -0
  56. data/lib/crawlscope/structured_data/report.rb +6 -14
  57. data/lib/crawlscope/structured_data/reporter.rb +6 -11
  58. data/lib/crawlscope/structured_data/validator.rb +64 -0
  59. data/lib/crawlscope/version.rb +1 -1
  60. data/lib/tasks/crawlscope_tasks.rake +6 -1
  61. data/test/crawlscope/cli_test.rb +21 -0
  62. data/test/crawlscope/content_quality_rule_test.rb +51 -0
  63. data/test/crawlscope/link_map_test.rb +337 -0
  64. data/test/crawlscope/links_rule_test.rb +16 -0
  65. data/test/crawlscope/rake_tasks_test.rb +10 -0
  66. data/test/crawlscope/reporter_test.rb +12 -0
  67. data/test/crawlscope/schema_registry_test.rb +22 -0
  68. data/test/crawlscope/structured_data_audit_test.rb +60 -0
  69. data/test/crawlscope/structured_data_report_test.rb +32 -0
  70. data/test/crawlscope/structured_data_rule_test.rb +11 -1
  71. data/test/crawlscope/structured_data_validator_test.rb +24 -0
  72. metadata +46 -1
@@ -1,9 +1,14 @@
1
1
  namespace :crawlscope do
2
- desc "Validate URLs with all default Crawlscope rules. Args: [url,sitemap,rules]. ENV: URL, SITEMAP, RULES, JS=1, TIMEOUT, NETWORK_IDLE_TIMEOUT, CONCURRENCY, FETCH_EXECUTOR"
2
+ desc "Validate URLs with all default Crawlscope rules. Args: [url,sitemap,rules]. ENV: URL, SITEMAP, RULES, LINK_MAP=0, JS=1, TIMEOUT, NETWORK_IDLE_TIMEOUT, CONCURRENCY, FETCH_EXECUTOR"
3
3
  task :validate, [:url, :sitemap, :rules] => :environment do |_task, args|
4
4
  Crawlscope::RakeTasks.validate(url: args[:url], sitemap_path: args[:sitemap], rule_names: args[:rules])
5
5
  end
6
6
 
7
+ desc "Export the internal link map (JSON, CSV, DOT, or text). Args: [url,sitemap,format,table]. ENV: URL, SITEMAP"
8
+ task :link_map, [:url, :sitemap, :format, :table] => :environment do |_task, args|
9
+ Crawlscope::RakeTasks.link_map(url: args[:url], sitemap_path: args[:sitemap], format: args[:format], table: args[:table])
10
+ end
11
+
7
12
  namespace :validate do
8
13
  desc "Directly validate JSON-LD on one URL. Args: [url]. ENV: URL (semicolon-separated), DEBUG=1, JS=1, TIMEOUT, NETWORK_IDLE_TIMEOUT, REPORT_PATH, SUMMARY=1"
9
14
  task :ldjson, [:url] => :environment do |_task, args|
@@ -3,6 +3,27 @@
3
3
  require "test_helper"
4
4
 
5
5
  class CrawlscopeCliTest < Minitest::Test
6
+ def test_ldjson_missing_data_fails_in_details_summary_json_and_exit_status
7
+ url = "https://example.com/page?locale=en"
8
+ stub_request(:get, url).to_return(status: 200, headers: {"Content-Type" => "text/html"}, body: "<h1>No markup</h1>")
9
+ out = StringIO.new
10
+ err = StringIO.new
11
+
12
+ Dir.mktmpdir do |directory|
13
+ path = File.join(directory, "report.json")
14
+ status = Crawlscope::Cli.start(["ldjson", "--url", url, "--summary", "--report-path", path], out: out, err: err)
15
+
16
+ assert_equal 1, status
17
+ assert_empty err.string
18
+ assert_includes out.string, "Validation: FAILED (no structured data found)"
19
+ assert_includes out.string, "STATUS: FAILED"
20
+ assert_includes out.string, "MISSING STRUCTURED DATA (1):"
21
+ assert_includes out.string, "• #{url}"
22
+ refute_includes out.string, "Validation: OK"
23
+ refute JSON.parse(File.read(path))["results"][url]["structured_data_found"]
24
+ end
25
+ end
26
+
6
27
  class FakeConfiguration
7
28
  attr_accessor :base_url, :concurrency, :fetch_executor, :network_idle_timeout_seconds, :output, :renderer, :timeout_seconds
8
29
 
@@ -3,6 +3,57 @@
3
3
  require "test_helper"
4
4
 
5
5
  class CrawlscopeContentQualityRuleTest < Minitest::Test
6
+ def test_reports_missing_image_alt_across_the_whole_page
7
+ issues = Crawlscope::IssueCollection.new
8
+ page = page_with(
9
+ main: '<picture><source srcset="/photo.webp"><img src="/photo.jpg"></picture><img src="/photo.jpg"><img loading="lazy">',
10
+ extra_markup: '<header><img src="/logo.svg"></header><footer><img src="/footer.svg"></footer>'
11
+ )
12
+
13
+ Crawlscope::Rules::ContentQuality.new.call(urls: [page.url], pages: [page], issues: issues)
14
+
15
+ matches = issues.to_a.select { |issue| issue.code == :missing_image_alt }
16
+ assert_equal 1, matches.size
17
+ issue = matches.first
18
+ assert_equal :warning, issue.severity
19
+ assert_equal :content_quality, issue.category
20
+ assert_equal page.url, issue.url
21
+ assert_equal "images missing alt attributes: 5", issue.message
22
+ assert_equal 5, issue.details[:count]
23
+ assert_equal ["/logo.svg", "/footer.svg", "/photo.jpg"], issue.details[:image_sources]
24
+ end
25
+
26
+ def test_allows_present_image_alt_attributes_including_decorative_images
27
+ issues = Crawlscope::IssueCollection.new
28
+ page = page_with(main: '<img src="/photo.jpg" alt="A mountain"><img src="/decoration.svg" alt=""><img src="/empty.svg" alt>')
29
+
30
+ Crawlscope::Rules::ContentQuality.new.call(urls: [page.url], pages: [page], issues: issues)
31
+
32
+ refute_includes issues.to_a.map(&:code), :missing_image_alt
33
+ end
34
+
35
+ def test_does_not_report_missing_image_alt_when_there_are_no_images
36
+ issues = Crawlscope::IssueCollection.new
37
+ page = page_with(main: "Text only")
38
+
39
+ Crawlscope::Rules::ContentQuality.new.call(urls: [page.url], pages: [page], issues: issues)
40
+
41
+ refute_includes issues.to_a.map(&:code), :missing_image_alt
42
+ end
43
+
44
+ def test_skips_non_html_pages
45
+ issues = Crawlscope::IssueCollection.new
46
+ page = Crawlscope::Page.new(
47
+ url: "https://example.com/file", normalized_url: "https://example.com/file",
48
+ final_url: "https://example.com/file", normalized_final_url: "https://example.com/file",
49
+ status: 200, headers: {}, body: "", doc: nil
50
+ )
51
+
52
+ Crawlscope::Rules::ContentQuality.new.call(urls: [page.url], pages: [page], issues: issues)
53
+
54
+ assert_empty issues.to_a
55
+ end
56
+
6
57
  def test_reports_thin_visible_text_and_low_html_text_ratio
7
58
  issues = Crawlscope::IssueCollection.new
8
59
  page = page_with(main: "Short page <div>#{"<span></span>" * 500}</div>")
@@ -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
@@ -3,6 +3,22 @@
3
3
  require "test_helper"
4
4
 
5
5
  class CrawlscopeLinksRuleTest < Minitest::Test
6
+ def test_reusing_a_rule_does_not_retain_the_previous_batch_resolver
7
+ rule = Crawlscope::Rules::Links.new
8
+ pages = [page(url: "https://example.com/guide", body: '<a href="/missing">Missing</a>')]
9
+ batch = ->(urls) { urls.to_h { |url| [url, {status: 200, html: true, final_url: url}] } }
10
+ first_issues = Crawlscope::IssueCollection.new
11
+ rule.call(urls: [], pages: pages, issues: first_issues, context: context.merge(resolve_targets: batch))
12
+ refute_includes first_issues.map(&:code), :broken_internal_link
13
+
14
+ second_issues = Crawlscope::IssueCollection.new
15
+ rule.call(urls: [], pages: pages, issues: second_issues, context: context)
16
+
17
+ broken = second_issues.find { |issue| issue.code == :broken_internal_link }
18
+ assert broken
19
+ assert_equal 404, broken.details[:status]
20
+ end
21
+
6
22
  def test_nofollow_controls_do_not_count_as_links_to_the_indexable_page
7
23
  issues = Crawlscope::IssueCollection.new
8
24
  requested = []
@@ -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
@@ -4,6 +4,18 @@ require "stringio"
4
4
  require "test_helper"
5
5
 
6
6
  class CrawlscopeReporterTest < Minitest::Test
7
+ def test_reports_images_missing_alt_with_each_image_source
8
+ output = report_issues(
9
+ {code: :missing_image_alt, category: :content_quality,
10
+ message: "images missing alt attributes: 2",
11
+ details: {count: 2, image_sources: ["https://example.com/photo.jpg", "https://cdn.example.com/logo.svg"]}}
12
+ )
13
+
14
+ assert_includes output, "Content quality: Images missing alt attributes (1 warning)"
15
+ assert_includes output, "/page images missing alt attributes: 2"
16
+ assert_includes output, " image: /photo.jpg\n image: https://cdn.example.com/logo.svg"
17
+ end
18
+
7
19
  def test_reports_ok_result
8
20
  io = StringIO.new
9
21
  result = Crawlscope::Result.new(
@@ -3,6 +3,28 @@
3
3
  require "test_helper"
4
4
 
5
5
  class CrawlscopeSchemaRegistryTest < Minitest::Test
6
+ def test_review_publication_accepts_dates_and_timestamps
7
+ ["2026-09-16", "2026-09-16T12:30:00Z"].each do |published|
8
+ review = {"@type" => "Review", "datePublished" => published, "reviewRating" => {"@type" => "Rating", "ratingValue" => 5}}
9
+ items = [review.merge("itemReviewed" => {"@type" => "SoftwareApplication", "name" => "Example"})]
10
+ items.concat(%w[SoftwareApplication WebApplication Product].map { |type| {"@type" => type, "name" => "Example", "review" => review} })
11
+
12
+ items.each do |item|
13
+ assert_empty Crawlscope::SchemaRegistry.default.validate(item), item.inspect
14
+ end
15
+ end
16
+ end
17
+
18
+ def test_review_publication_rejects_invalid_calendar_dates
19
+ ["2026-02-30", "2026-13-01", "not a date"].each do |published|
20
+ review = {"@type" => "Review", "datePublished" => published, "reviewRating" => {"@type" => "Rating", "ratingValue" => 5}}
21
+ [review.merge("itemReviewed" => {"@type" => "SoftwareApplication"}),
22
+ {"@type" => "SoftwareApplication", "name" => "Example", "review" => review}].each do |item|
23
+ assert Crawlscope::SchemaRegistry.default.validate(item).any? { |error| error.fetch(:field).end_with?("datePublished") }, item.inspect
24
+ end
25
+ end
26
+ end
27
+
6
28
  def test_registers_and_fetches_schema_by_type
7
29
  registry = Crawlscope::SchemaRegistry.default
8
30
  schema = {"type" => "object"}
@@ -3,6 +3,66 @@
3
3
  require "test_helper"
4
4
 
5
5
  class CrawlscopeStructuredDataAuditTest < Minitest::Test
6
+ def test_required_types_are_checked_by_sitemap_and_direct_audits
7
+ required_types = ->(url) { URI(url).path.start_with?("/guides/") ? [["Article", "BlogPosting", "NewsArticle"]] : [] }
8
+ cases = [
9
+ ["/guides/test", {"@type" => "WebPage"}, false],
10
+ ["/features/test", {"@type" => "WebPage"}, true],
11
+ ["/guides/test", {"@graph" => [{"@type" => "BlogPosting", "headline" => "A guide"}], "@type" => "WebPage"}, true],
12
+ ["/guides/test", {"@type" => ["WebPage", "Article"], "headline" => "A guide"}, true],
13
+ ["/guides/test", {"@type" => "ItemList", "itemListElement" => [{"@type" => "Article", "headline" => "Another guide"}]}, false]
14
+ ]
15
+
16
+ cases.each do |path, data, expected_ok|
17
+ page = html_page(url: "https://example.com#{path}", body: %(<script type="application/ld+json">#{JSON.generate(data)}</script>))
18
+ browser = FakeBrowser.new(page: page)
19
+ config = Crawlscope::Configuration.new
20
+ config.browser_factory = -> { -> { browser } }
21
+ config.renderer = :browser
22
+ config.output = StringIO.new
23
+ config.required_structured_data_types = required_types
24
+ outcome = Crawlscope::StructuredData::Check.new(configuration: config).call(urls: [page.url])
25
+ issues = Crawlscope::IssueCollection.new
26
+ config.rule_registry.rules_for([:structured_data]).first.call(urls: [page.url], pages: [page], issues: issues,
27
+ context: {schema_registry: config.schema_registry})
28
+
29
+ assert_equal expected_ok, outcome.ok?, data.inspect
30
+ assert_equal expected_ok ? [] : [:structured_data_missing_required_type], issues.map(&:code), data.inspect
31
+ unless expected_ok
32
+ assert_equal "page", outcome.entries.first.errors.first.fetch(:source)
33
+ assert_equal "Article or BlogPosting or NewsArticle", outcome.entries.first.errors.first.fetch(:type)
34
+ end
35
+ end
36
+ end
37
+
38
+ def test_sitemap_and_direct_audits_agree_on_structured_data_validity
39
+ cases = [
40
+ ["<h1>No markup</h1>", :missing_structured_data],
41
+ ['<script type="application/ld+json">{</script>', :structured_data_parse_error],
42
+ ['<script type="application/ld+json">{"name":"Untyped"}</script>', :structured_data_missing_type],
43
+ ['<script type="application/ld+json">{"@type":"WebPage","@graph":[{"name":"Untyped"}]}</script>', :structured_data_missing_type],
44
+ ['<script type="application/ld+json">{"@type":"Article"}</script>', :structured_data_schema_error],
45
+ ['<script type="application/ld+json">{"@type":"WebPage","name":"Example"}</script>', nil],
46
+ ['<div itemscope itemtype="https://schema.org/WebPage"><span itemprop="name">Example</span></div>', nil]
47
+ ]
48
+ registry = Crawlscope::SchemaRegistry.default
49
+ cases.each do |body, expected_code|
50
+ page = html_page(url: "https://example.com/page", body: body)
51
+ browser = FakeBrowser.new(page: page)
52
+ outcome = Crawlscope::StructuredData::Audit.new(browser_factory: -> { browser }, renderer: :browser,
53
+ schema_registry: registry, timeout_seconds: 20).call(urls: [page.url])
54
+ issues = Crawlscope::IssueCollection.new
55
+ Crawlscope::Rules::StructuredData.new.call(urls: [page.url], pages: [page], issues: issues, context: {schema_registry: registry})
56
+
57
+ assert_equal expected_code.nil?, outcome.ok?, body
58
+ assert_equal expected_code ? [expected_code] : [], issues.map(&:code), body
59
+ assert_equal outcome.ok?, Crawlscope::StructuredData::Report.new(outcome).all_valid?
60
+ schema_issue = issues.find { |issue| issue.code == :structured_data_schema_error }
61
+ assert_equal schema_issue.details[:errors], outcome.entries.first.errors.first[:errors] if schema_issue
62
+ assert browser.closed
63
+ end
64
+ end
65
+
6
66
  class FakeBrowser
7
67
  attr_reader :closed
8
68
 
@@ -3,6 +3,38 @@
3
3
  require "test_helper"
4
4
 
5
5
  class CrawlscopeStructuredDataReportTest < Minitest::Test
6
+ def test_outcome_and_report_agree_for_every_failure_kind_and_success_status
7
+ cases = [
8
+ {status: 200, structured_items: [], failure: :missing_data},
9
+ {status: 201, structured_items: [], failure: :missing_data},
10
+ {status: nil, structured_items: [], failure: :missing_data},
11
+ {status: 200, fetch_error: "Fetch failed", failure: :http},
12
+ {status: 404, fetch_error: "Not found", failure: :http},
13
+ {status: 201, errors: [{errors: [{field: "name", issue: "is required"}]}], failure: :validation},
14
+ {status: nil, errors: [{errors: [{field: "name", issue: "is required"}]}], failure: :validation},
15
+ {status: 200, failure: nil},
16
+ {status: 201, failure: nil},
17
+ {status: nil, failure: nil},
18
+ {status: 200, structured_items: [], skipped_reason: "non-html", failure: nil}
19
+ ]
20
+ cases.each do |attributes|
21
+ attributes = attributes.dup
22
+ failure = attributes.delete(:failure)
23
+ defaults = {url: "https://example.com/page", status: 200, structured_items: [{source: "json-ld", data: {"@type" => "WebPage"}}],
24
+ errors: [], fetch_error: nil, content_type: "text/html", skipped_reason: nil}
25
+ entry = Crawlscope::StructuredData::Audit::Page.new(**defaults.merge(attributes))
26
+ outcome = Crawlscope::StructuredData::Audit::Outcome.new(entries: [entry])
27
+ report = Crawlscope::StructuredData::Report.new(outcome)
28
+
29
+ assert_equal failure.nil?, outcome.ok?, attributes.inspect
30
+ assert_equal outcome.ok?, report.all_valid?, attributes.inspect
31
+ assert_equal failure ? 1 : 0, report.failure_count, attributes.inspect
32
+ assert_equal (failure == :http) ? [entry] : [], report.http_errors
33
+ assert_equal (failure == :missing_data) ? [entry] : [], report.missing_data
34
+ assert_equal (failure == :validation) ? [entry] : [], report.validation_errors
35
+ end
36
+ end
37
+
6
38
  def test_results_maps_validation_errors_and_skips
7
39
  result = Crawlscope::StructuredData::Audit::Outcome.new(
8
40
  entries: [