Skip to content

Commit

Permalink
Add spec for middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielHeath committed Apr 30, 2019
1 parent 426e8c3 commit edeeb3d
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 5 deletions.
24 changes: 19 additions & 5 deletions lib/html-proofer/middleware.rb
Expand Up @@ -3,6 +3,16 @@
module HTMLProofer
class Middleware

class InvalidHtmlError < StandardError
def initialize(failures)
@failures = failures
end

def message
"HTML Validation errors (skip by adding ?SKIP_VALIDATION to URL): \n#{@failures.join("\n")}"
end
end

def self.options
@options ||= {
type: :file,
Expand Down Expand Up @@ -43,12 +53,16 @@ def call(env)
return result if env['REQUEST_METHOD'] != 'GET'
return result if env['QUERY_STRING'] =~ /SKIP_VALIDATION/
return result if result.first != 200

# [@status, @headers, @response]
body = []
result.last.each { |e| body << e }
html = body.join('').lstrip
if HTML_SIGNATURE.any? { |sig| html.downcase.starts_with? sig.downcase }

body = body.join('')
begin
html = body.lstrip
rescue
return result # Invalid encoding; it's not gonna be html.
end
if HTML_SIGNATURE.any? { |sig| html.upcase.starts_with? sig }
parsed = HTMLProofer::Runner.new(
'response',
Middleware.options
Expand All @@ -57,7 +71,7 @@ def call(env)
)

if parsed[:failures].length > 0
raise "HTML Validation errors (skip by adding ?SKIP_VALIDATION to URL): \n#{parsed[:failures].join("\n")}"
raise InvalidHtmlError.new(parsed[:failures])
end
end
result
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions spec/html-proofer/middleware_spec.rb
@@ -0,0 +1,33 @@
require 'spec_helper'

describe 'Middleware test' do
let(:request) { {'REQUEST_METHOD' => 'GET'} }
let(:response) { File.open(response_fixture) }
let(:app) { Proc.new { |*args| [200, {}, response] } }
let(:middleware) { HTMLProofer::Middleware.new(app) }
subject { middleware.call(request) }

context 'with invalid HTML' do
let(:response_fixture) { File.join(FIXTURES_DIR, 'html', 'missing_closing_quotes.html') }
it 'raises an error' do
expect {
subject
}.to raise_error(HTMLProofer::Middleware::InvalidHtmlError)
end
end

context 'with valid HTML' do
let(:response_fixture) { File.join(FIXTURES_DIR, 'html', 'html5_tags.html') }
it 'does not raise an error' do
subject
end
end

context 'with non-HTML content' do
let(:response_fixture) { File.join(FIXTURES_DIR, 'images', 'gpl.png') }
it 'does not raise an error' do
subject
end
end

end

0 comments on commit edeeb3d

Please sign in to comment.