metainspector 5.21.2 → 5.22.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.
@@ -33,11 +33,15 @@ module MetaInspector
33
33
  return found_tracking_params.any?
34
34
  end
35
35
 
36
+ # Removes only the tracking key=value pairs, keeping the rest of the
37
+ # query string as written: order, repeated keys and encoding.
36
38
  def untracked_url
37
39
  u = parsed(url)
38
- return url unless u.query_values
39
- query_values = u.query_values.delete_if { |key, _| WELL_KNOWN_TRACKING_PARAMS.include? key }
40
- u.query_values = query_values.length > 0 ? query_values : nil
40
+ return url unless u.query
41
+ params = u.query.split('&', -1)
42
+ kept = params.reject { |param| tracking_param?(param) }
43
+ return url if kept.length == params.length
44
+ u.query = kept.empty? ? nil : kept.join('&')
41
45
  u.to_s
42
46
  end
43
47
 
@@ -62,18 +66,41 @@ module MetaInspector
62
66
  MetaInspector::URL.new(url, options).url
63
67
  else
64
68
  uri = Addressable::URI.join(base_url, url)
65
- options[:normalize] ? uri.normalize.to_s : uri.to_s
69
+ options[:normalize] ? normalize(uri) : uri.to_s
66
70
  end
67
71
  rescue MetaInspector::ParserError, Addressable::URI::InvalidURIError, ArgumentError
68
72
  nil
69
73
  end
70
74
 
75
+ # Addressable's normalization, except for the query: reserved characters such
76
+ # as ";" or "[]" and existing escapes are kept as written, since changing them
77
+ # can change the resource (RFC 3986, 2.2). Only what can't be sent is escaped.
78
+ def self.normalize(uri)
79
+ normalized = uri.normalize
80
+ normalized.query = escape_query(uri.query) if uri.query
81
+ normalized.to_s
82
+ end
83
+
84
+ # Bytes allowed in a query by RFC 3986 (pchar, "/" and "?"), plus "[]" and
85
+ # "%" when it starts an escape. Browsers send "[]" unescaped too.
86
+ QUERY_UNSAFE = /%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@\/?\[\]%]/n
87
+ private_constant :QUERY_UNSAFE
88
+
89
+ def self.escape_query(query)
90
+ query.b.gsub(QUERY_UNSAFE) { |byte| format('%%%02X', byte.ord) }.force_encoding(Encoding::UTF_8)
91
+ end
92
+
71
93
  private
72
94
 
73
95
  def self.defaults
74
96
  { :normalize => true }
75
97
  end
76
98
 
99
+ def tracking_param?(param)
100
+ key = Addressable::URI.unencode_component(param.split('=', 2).first)
101
+ WELL_KNOWN_TRACKING_PARAMS.include?(key)
102
+ end
103
+
77
104
  # Adds 'http' as default scheme, if there is none
78
105
  def with_default_scheme(url)
79
106
  parsed(url) && parsed(url).scheme.nil? ? 'http://' + url : url
@@ -82,7 +109,7 @@ module MetaInspector
82
109
  # Normalize url to deal with characters that should be encoded,
83
110
  # add trailing slash, convert to downcase...
84
111
  def normalized(url)
85
- Addressable::URI.parse(url).normalize.to_s
112
+ self.class.normalize(Addressable::URI.parse(url))
86
113
  rescue Addressable::URI::InvalidURIError => e
87
114
  raise MetaInspector::ParserError.new(e)
88
115
  end
@@ -21,7 +21,7 @@ module MetaInspector
21
21
  raise InvalidURL, 'URL must be HTTP or HTTPS'
22
22
  end
23
23
  uri
24
- rescue URI::InvalidURIError => error
24
+ rescue URI::InvalidURIError, URI::InvalidComponentError => error
25
25
  raise InvalidURL.new(error)
26
26
  end
27
27
 
@@ -1,3 +1,3 @@
1
1
  module MetaInspector
2
- VERSION = '5.21.2'
2
+ VERSION = '5.22.0'
3
3
  end
@@ -8,7 +8,7 @@ Gem::Specification.new do |gem|
8
8
  gem.homepage = "https://github.com/jaimeiniesta/metainspector"
9
9
  gem.license = "MIT"
10
10
 
11
- gem.files = `git ls-files`.split("\n") - ["Gemfile.lock"]
11
+ gem.files = (`git ls-files`.split("\n") - ["Gemfile.lock"]).reject { |f| f.start_with?("assets/") }
12
12
  gem.test_files = `git ls-files -- {spec}/*`.split("\n")
13
13
  gem.name = "metainspector"
14
14
  gem.require_paths = ["lib"]
@@ -1,6 +1,76 @@
1
1
  require 'spec_helper'
2
+ require 'json'
2
3
 
3
4
  describe MetaInspector::Document do
5
+ describe '#to_hash response headers' do
6
+ let(:url) { 'https://headers.example/' }
7
+ let(:page) { MetaInspector.new(url, download_images: false) }
8
+
9
+ before do
10
+ stub_request(:get, url).to_return(
11
+ body: '<title>Example</title>',
12
+ headers: { 'Content-Type' => 'text/html', 'X-Olaf' => header_value }
13
+ )
14
+ end
15
+
16
+ {
17
+ 'ASCII text' => ['plain text'.b, 'plain text'],
18
+ 'UTF-8 text' => ["\u2603", "\u2603"],
19
+ 'text with a known encoding' => ["caf\xE9".force_encoding(Encoding::ISO_8859_1), 'café'],
20
+ 'UTF-8 bytes in a binary string' => ["\u2603".b, "\u2603"],
21
+ 'invalid UTF-8 bytes in a binary string' => ["snowman \xFF".b, "snowman \uFFFD"],
22
+ 'invalid bytes in a UTF-8 string' => ["snowman \xFF", "snowman \uFFFD"]
23
+ }.each do |description, (value, expected)|
24
+ context "with #{description}" do
25
+ let(:header_value) { value }
26
+
27
+ it 'serializes the headers as valid UTF-8 in JSON' do
28
+ serialized = JSON.pretty_generate(page.to_hash)
29
+
30
+ expect(JSON.parse(serialized)['response']['headers']['x-olaf']).to eq(expected)
31
+ expect(page.to_hash['response']['headers']['x-olaf'].encoding).to eq(Encoding::UTF_8)
32
+ end
33
+ end
34
+ end
35
+
36
+ context 'when preserving the original response' do
37
+ let(:header_value) { "\u2603".b }
38
+
39
+ it 'leaves the raw headers and their encoding unchanged' do
40
+ raw_headers = page.response.headers
41
+ raw_value = raw_headers['x-olaf']
42
+ raw_value.freeze
43
+ raw_headers.freeze
44
+
45
+ page.to_hash
46
+
47
+ expect(page.response.headers).to equal(raw_headers)
48
+ expect(raw_headers['x-olaf']).to equal(raw_value)
49
+ expect(raw_value.bytes).to eq([0xE2, 0x98, 0x83])
50
+ expect(raw_value.encoding).to eq(Encoding::BINARY)
51
+ end
52
+ end
53
+
54
+ context 'when the response was compressed' do
55
+ let(:header_value) { 'unused' }
56
+ let(:html) { '<html><head><title>Hello</title></head></html>' }
57
+
58
+ before do
59
+ stub_request(:get, url).to_return(
60
+ body: Zlib.gzip(html),
61
+ headers: { 'Content-Type' => 'text/html', 'Content-Encoding' => 'gzip' }
62
+ )
63
+ end
64
+
65
+ it 'keeps header values that are not strings, like the decompressed Content-Length' do
66
+ headers = page.to_hash['response']['headers']
67
+
68
+ expect(headers['content-length']).to eq(html.bytesize)
69
+ expect(JSON.parse(JSON.generate(page.to_hash))['response']['headers']['content-length']).to eq(html.bytesize)
70
+ end
71
+ end
72
+ end
73
+
4
74
  describe 'public API' do
5
75
  let(:html) do
6
76
  <<~HTML
@@ -22,6 +92,40 @@ describe MetaInspector::Document do
22
92
  ])
23
93
  end
24
94
 
95
+ describe 'feed types' do
96
+ let(:html) do
97
+ <<~HTML
98
+ <html><head>
99
+ <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
100
+ <link rel="alternate" type="application/feed+json" title="JSON Feed" href="/feed.json">
101
+ <link rel="alternate" type="Application/Atom+XML" title="Atom" href="/atom.xml">
102
+ <link rel="alternate" type=" application/rss+xml ; charset=utf-8" title="RSS with parameter" href="/rss2.xml">
103
+ <link rel="alternate" type="application/rss+xml-ish" title="Unknown" href="/other.xml">
104
+ <link rel="alternate" type="text/html" title="Translation" href="/es/">
105
+ </head></html>
106
+ HTML
107
+ end
108
+
109
+ it 'matches JSON Feed 1.1 and types with any case, whitespace or parameters, keeping the type as written' do
110
+ expect(page.feeds).to eq([
111
+ { title: 'RSS', href: 'https://example.com/feed.xml', type: 'application/rss+xml' },
112
+ { title: 'JSON Feed', href: 'https://example.com/feed.json', type: 'application/feed+json' },
113
+ { title: 'Atom', href: 'https://example.com/atom.xml', type: 'Application/Atom+XML' },
114
+ { title: 'RSS with parameter', href: 'https://example.com/rss2.xml',
115
+ type: ' application/rss+xml ; charset=utf-8' }
116
+ ])
117
+ end
118
+
119
+ it 'returns RSS or Atom feeds with parameters from the deprecated feed method' do
120
+ page = MetaInspector.new('https://example.com/', document: <<~HTML)
121
+ <link rel="alternate" type="application/feed+json" href="/feed.json">
122
+ <link rel="alternate" type="application/atom+xml; charset=utf-8" href="/atom.xml">
123
+ HTML
124
+
125
+ expect { expect(page.feed).to eq('https://example.com/atom.xml') }.to output(/DEPRECATION/).to_stderr
126
+ end
127
+ end
128
+
25
129
  it 'exposes the favicon through the images API' do
26
130
  expect(page.images.favicon).to eq('https://example.com/icon.png')
27
131
  end
@@ -161,6 +265,20 @@ describe MetaInspector::Document do
161
265
  it "should get the title" do
162
266
  expect(doc.title).to eq("Hello From Passed Html")
163
267
  end
268
+
269
+ it 'returns nil content type and response, since no request was made' do
270
+ expect do
271
+ expect(doc.content_type).to be_nil
272
+ expect(doc.response).to be_nil
273
+ end.not_to output.to_stderr
274
+ end
275
+
276
+ it 'serializes to_hash with nil content type and response' do
277
+ hash = doc.to_hash
278
+
279
+ expect(hash).to include('title' => 'Hello From Passed Html', 'content_type' => nil, 'response' => nil)
280
+ expect(hash['links']['internal']).to eq(['http://cnn.com/hello'])
281
+ end
164
282
  end
165
283
 
166
284
  it "should return a String as to_s" do
@@ -0,0 +1,47 @@
1
+ require 'spec_helper'
2
+
3
+ describe MetaInspector, 'content type normalization' do
4
+ let(:page_url) { 'http://example.com/content-type' }
5
+ let(:html) { '<html><head><title>Downloaded page</title></head></html>' }
6
+
7
+ [false, true].each do |head_first|
8
+ context "with head_first: #{head_first}" do
9
+ ['Text/HTML; charset=utf-8', 'text/html ; charset=utf-8', " \tTEXT/HTML\t; charset=utf-8"].each do |content_type|
10
+ it "parses HTML served as #{content_type.inspect}" do
11
+ stub_request(:head, page_url).to_return(headers: { 'Content-Type' => content_type }) if head_first
12
+ stub_request(:get, page_url).to_return(body: html, headers: { 'Content-Type' => content_type })
13
+
14
+ page = MetaInspector.new(page_url, head_first: head_first)
15
+
16
+ expect(page.title).to eq('Downloaded page')
17
+ expect(page.content_type).to eq('text/html')
18
+ expect(page.to_hash['content_type']).to eq('text/html')
19
+ expect(page.response.headers['content-type']).to eq(content_type)
20
+ end
21
+ end
22
+
23
+ it 'still rejects non-HTML content after normalization' do
24
+ stub_request(:head, page_url).to_return(headers: { 'Content-Type' => 'Application/PDF ; version=1.7' }) if head_first
25
+ get_request = stub_request(:get, page_url)
26
+ .to_return(body: 'PDF data', headers: { 'Content-Type' => 'Application/PDF ; version=1.7' })
27
+
28
+ expect do
29
+ MetaInspector.new(page_url, head_first: head_first)
30
+ end.to raise_error(MetaInspector::NonHtmlError,
31
+ 'The url provided contains application/pdf content instead of text/html content')
32
+
33
+ expect(get_request).not_to have_been_requested if head_first
34
+ end
35
+
36
+ it 'normalizes non-HTML content when explicitly allowed' do
37
+ stub_request(:head, page_url).to_return(headers: { 'Content-Type' => 'Text/Plain ; charset=utf-8' }) if head_first
38
+ stub_request(:get, page_url).to_return(body: 'Plain text', headers: { 'Content-Type' => 'Text/Plain ; charset=utf-8' })
39
+
40
+ page = MetaInspector.new(page_url, head_first: head_first, allow_non_html_content: true)
41
+
42
+ expect(page.to_s).to eq('Plain text')
43
+ expect(page.content_type).to eq('text/plain')
44
+ end
45
+ end
46
+ end
47
+ end
@@ -56,7 +56,7 @@ describe MetaInspector do
56
56
  let(:page) { MetaInspector.new('https://example.com/page', document: document) }
57
57
  let(:expected_link) do
58
58
  attributes = { title: 'Example', href: 'https://example.com/resource', type: 'application/rss+xml' }
59
- attributes[:rel] = rel unless method == :feeds
59
+ attributes[:rel] = rel.gsub(/\r\n?/, "\n") unless method == :feeds
60
60
  attributes
61
61
  end
62
62
 
@@ -68,9 +68,9 @@ describe MetaInspector do
68
68
  let(:rel) { value }
69
69
  let(:rel_attribute) { %(rel="#{rel}") }
70
70
 
71
- it "matches the complete token and preserves the link attributes" do
71
+ it "matches the complete token and preserves the parsed link attributes" do
72
72
  expect(page.public_send(method)).to eq([expected_link])
73
- expect(page.head_links.first[:rel]).to eq(rel)
73
+ expect(page.head_links.first[:rel]).to eq(rel.gsub(/\r\n?/, "\n"))
74
74
  end
75
75
  end
76
76
  end
@@ -58,7 +58,7 @@ describe MetaInspector do
58
58
  "http://international.com/faqs#cami%C3%83%C2%B3n",
59
59
  "http://international.com/search?q=cami%C3%83%C2%B3n",
60
60
  "http://international.com/search?q=espa%C3%83%C2%B1a#top",
61
- "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ==&cntnt01pageid=21"
61
+ "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ%3D%3D&cntnt01pageid=21"
62
62
  ])
63
63
 
64
64
  expect(m.links.external).to eq([
@@ -79,7 +79,7 @@ describe MetaInspector do
79
79
  "http://international.com/faqs#cami%C3%83%C2%B3n",
80
80
  "http://international.com/search?q=cami%C3%83%C2%B3n",
81
81
  "http://international.com/search?q=espa%C3%83%C2%B1a#top",
82
- "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ==&cntnt01pageid=21"
82
+ "http://international.com/index.php?q=espa%C3%83%C2%B1a&url=aHR0zZQ%3D%3D&cntnt01pageid=21"
83
83
  ])
84
84
  end
85
85
 
@@ -215,6 +215,57 @@ describe MetaInspector do
215
215
  end
216
216
  end
217
217
 
218
+ describe 'Base element lookup' do
219
+ # Searching the whole document for <base> once per link, image, iframe or
220
+ # <link> made these methods take quadratic time on large pages (#573).
221
+ callers = {
222
+ 'links.all' => ->(page) { page.links.all },
223
+ 'images.to_a' => ->(page) { page.images.to_a },
224
+ 'iframe_sources' => ->(page) { page.iframe_sources },
225
+ 'head_links' => ->(page) { page.head_links },
226
+ 'feeds' => ->(page) { page.feeds }
227
+ }
228
+
229
+ { 'without a base element' => '', 'with a base element' => '<base href="/dir/">' }.each do |name, base|
230
+ context name do
231
+ let(:html) do
232
+ <<~HTML
233
+ <html><head>#{base}
234
+ <link rel="stylesheet" href="a.css"><link rel="stylesheet" href="b.css">
235
+ <link rel="alternate" type="application/rss+xml" href="a.xml">
236
+ <link rel="alternate" type="application/atom+xml" href="b.xml">
237
+ </head><body>
238
+ <a href="a">a</a><a href="b">b</a><a href="c">c</a>
239
+ <img src="a.png"><img src="b.png"><img srcset="c.png 1x, d.png 2x">
240
+ <iframe src="a.html"></iframe><iframe src="b.html"></iframe>
241
+ </body></html>
242
+ HTML
243
+ end
244
+ let(:page) { MetaInspector.new('http://example.com/', document: html) }
245
+
246
+ callers.each do |method, call|
247
+ it "searches the document for it only once for #{method}" do
248
+ allow(page.parsed).to receive(:search).and_call_original
249
+
250
+ call.call(page)
251
+
252
+ expect(page.parsed).to have_received(:search).with('base').once
253
+ end
254
+ end
255
+ end
256
+ end
257
+
258
+ it 'keeps following the page URL when there is no base element' do
259
+ page = MetaInspector.new('http://example.com/?utm_source=feed', document: '<html><body><a href="a">a</a></body></html>')
260
+
261
+ expect(page.links.base_url).to eq('http://example.com/?utm_source=feed')
262
+
263
+ page.untrack!
264
+
265
+ expect(page.links.base_url).to eq('http://example.com/')
266
+ end
267
+ end
268
+
218
269
  describe 'Non-HTTP links' do
219
270
  before(:each) do
220
271
  @m = MetaInspector.new('http://example.com/nonhttp')
@@ -231,6 +282,51 @@ describe MetaInspector do
231
282
  end
232
283
  end
233
284
 
285
+ describe 'Links inside inline SVG and MathML' do
286
+ let(:page) do
287
+ MetaInspector.new('http://example.com/', document: <<~HTML)
288
+ <html><body>
289
+ <a href="/before">text</a>
290
+ <svg viewBox="0 0 10 10"><a href="/svg-link"><circle r="5"/></a></svg>
291
+ <math><a href="/math-link">x</a></math>
292
+ <a href="/after">text</a>
293
+ </body></html>
294
+ HTML
295
+ end
296
+
297
+ it 'returns them with the HTML links, in document order' do
298
+ expect(page.links.raw).to eq(['/before', '/svg-link', '/math-link', '/after'])
299
+ end
300
+
301
+ it 'resolves them like any other link' do
302
+ expect(page.links.internal).to eq(['http://example.com/before',
303
+ 'http://example.com/svg-link',
304
+ 'http://example.com/math-link',
305
+ 'http://example.com/after'])
306
+ end
307
+ end
308
+
309
+ describe 'Query strings in links' do
310
+ let(:page) do
311
+ MetaInspector.new('http://example.com/dir/', document: <<~HTML)
312
+ <a href="/a?x=1;y=2&b[]=1&c=a%2fb&%61=1">relative</a>
313
+ <a href="http://other.com/a?x=1;y=2&b[]=1&c=a%2fb&%61=1">absolute</a>
314
+ <a href="b?q=café&r=a|b&s=50%">needs escaping</a>
315
+ <link rel="alternate" type="application/rss+xml" href="/feed?x=1;y=2">
316
+ HTML
317
+ end
318
+
319
+ it 'keeps reserved characters and escapes as written (#613)' do
320
+ expect(page.links.all).to eq(['http://example.com/a?x=1;y=2&b[]=1&c=a%2fb&%61=1',
321
+ 'http://other.com/a?x=1;y=2&b[]=1&c=a%2fb&%61=1',
322
+ 'http://example.com/dir/b?q=caf%C3%A9&r=a%7Cb&s=50%25'])
323
+ end
324
+
325
+ it 'applies the same rule to head links' do
326
+ expect(page.feeds.map { |feed| feed[:href] }).to eq(['http://example.com/feed?x=1;y=2'])
327
+ end
328
+ end
329
+
234
330
  describe 'Protocol-relative URLs' do
235
331
  before(:each) do
236
332
  @m_http = MetaInspector.new('http://protocol-relative.com')
@@ -103,5 +103,58 @@ describe MetaInspector do
103
103
 
104
104
  expect(page.charset).to eq(nil)
105
105
  end
106
+
107
+ ['Content-Type', 'content-type', 'Content-type', 'CONTENT-TYPE'].each do |http_equiv|
108
+ it "gets the charset when http-equiv is #{http_equiv}" do
109
+ html = %(<meta http-equiv="#{http_equiv}" content="text/html; charset=utf-8">)
110
+ page = MetaInspector.new('http://example.com', document: html)
111
+
112
+ expect(page.charset).to eq('utf-8')
113
+ end
114
+ end
115
+
116
+ {
117
+ 'text/html; foo=bar; charset=utf-8' => 'utf-8',
118
+ 'text/html; charset=utf-8; foo=bar' => 'utf-8',
119
+ 'text/html; charset = utf-8 ' => 'utf-8',
120
+ "text/html;\tCHARSET\t=\tUTF-8" => 'UTF-8',
121
+ 'text/html; charset="utf-8"' => 'utf-8',
122
+ "text/html; charset='utf-8'" => 'utf-8',
123
+ 'text/html; foo=bar' => nil,
124
+ 'text/html; othercharset=utf-8' => nil,
125
+ 'text/html; charset' => nil,
126
+ 'text/html; charset=' => nil,
127
+ 'text/html' => nil
128
+ }.each do |content, charset|
129
+ it "gets #{charset.inspect} from the content #{content.inspect}" do
130
+ html = %(<meta http-equiv="Content-Type" content="#{content.gsub('"', '&quot;')}">)
131
+ page = MetaInspector.new('http://example.com', document: html)
132
+
133
+ expect(page.charset).to eq(charset)
134
+ end
135
+ end
136
+
137
+ it 'returns nil when the content-type meta tag has no content attribute' do
138
+ page = MetaInspector.new('http://example.com', document: '<meta http-equiv="content-type">')
139
+
140
+ expect(page.charset).to be_nil
141
+ end
142
+
143
+ it 'prefers a meta charset attribute over a content-type declaration' do
144
+ html = '<meta http-equiv="content-type" content="text/html; charset=windows-1252">' \
145
+ '<meta charset="utf-8">'
146
+ page = MetaInspector.new('http://example.com', document: html)
147
+
148
+ expect(page.charset).to eq('utf-8')
149
+ end
150
+
151
+ it 'uses the first content-type declaration and ignores other http-equiv values' do
152
+ html = '<meta http-equiv="refresh" content="0; charset=windows-1252">' \
153
+ '<meta http-equiv="content-type" content="text/html; charset=utf-8">' \
154
+ '<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">'
155
+ page = MetaInspector.new('http://example.com', document: html)
156
+
157
+ expect(page.charset).to eq('utf-8')
158
+ end
106
159
  end
107
160
  end
@@ -1,6 +1,38 @@
1
1
  require 'spec_helper'
2
2
 
3
3
  describe MetaInspector do
4
+ describe 'headings containing paragraphs' do
5
+ (1..6).each do |level|
6
+ {
7
+ '<p>Hello</p>' => 'Hello',
8
+ 'Hi <p>there</p>' => 'Hi there',
9
+ '<p>Hello <em>there</em></p> friend' => 'Hello there friend'
10
+ }.each do |content, text|
11
+ it "preserves #{content.inspect} inside h#{level}" do
12
+ html = "<h#{level}>#{content}</h#{level}><p>Outside</p>"
13
+ page = MetaInspector.new('http://example.com', document: html)
14
+
15
+ expect(page.public_send("h#{level}")).to eq([text])
16
+ end
17
+ end
18
+ end
19
+
20
+ it 'uses the complete first heading as the best title' do
21
+ page = MetaInspector.new('http://example.com', document: '<h1>Hi <p>there</p></h1><h1>Later</h1>')
22
+
23
+ expect(page.best_title).to eq('Hi there')
24
+ expect(page.to_hash['h1']).to eq(['Hi there', 'Later'])
25
+ end
26
+
27
+ it 'preserves paragraph content in downloaded headings' do
28
+ stub_request(:get, 'http://example.com/').to_return(
29
+ body: '<h1><p>Hello</p></h1>', headers: { 'Content-Type' => 'text/html' }
30
+ )
31
+
32
+ expect(MetaInspector.new('http://example.com').h1).to eq(['Hello'])
33
+ end
34
+ end
35
+
4
36
  describe '#language' do
5
37
  ['en', 'en-US', 'zh-Hant-TW'].each do |language|
6
38
  it "should return the declared language #{language.inspect}" do
@@ -50,6 +82,56 @@ describe MetaInspector do
50
82
  expect(page.title).to eq('An example page')
51
83
  end
52
84
 
85
+ describe '#title' do
86
+ let(:page) do
87
+ MetaInspector.new('http://example.com/', document: html)
88
+ end
89
+
90
+ context 'when the head contains multiple titles' do
91
+ let(:html) { '<html><head><title>One</title><title>Two</title></head></html>' }
92
+
93
+ it 'should return only the first title' do
94
+ expect(page.title).to eq('One')
95
+ end
96
+
97
+ it 'should include only the first title in to_hash' do
98
+ expect(page.to_hash['title']).to eq('One')
99
+ end
100
+ end
101
+
102
+ context 'when the first title is empty' do
103
+ let(:html) { '<html><head><title></title><title>Two</title></head></html>' }
104
+
105
+ it 'should return an empty string without falling back to a later title' do
106
+ expect(page.title).to eq('')
107
+ end
108
+ end
109
+
110
+ context 'when the title contains whitespace and entities' do
111
+ let(:html) { '<html><head><title> One &amp; Two </title></head></html>' }
112
+
113
+ it 'should preserve whitespace and decode entities' do
114
+ expect(page.title).to eq(' One & Two ')
115
+ end
116
+ end
117
+
118
+ context 'when there is no title' do
119
+ let(:html) { '<html><head></head><body></body></html>' }
120
+
121
+ it 'should return an empty string' do
122
+ expect(page.title).to eq('')
123
+ end
124
+ end
125
+
126
+ context 'when the title is only in the body' do
127
+ let(:html) { '<html><head></head><body><title>Body title</title></body></html>' }
128
+
129
+ it 'should return an empty string' do
130
+ expect(page.title).to eq('')
131
+ end
132
+ end
133
+ end
134
+
53
135
  describe "#h1" do
54
136
  it "should find h1 content" do
55
137
  page = MetaInspector.new('http://example.com/headings')