require 'spec_helper'

describe ExceptionApp::Middleware do

  let(:app) do
    ExceptionApp::Middleware.new( ->(env){ [418, {}, ["I'm a teapot."]] }, '/dev/null')
  end
  # let(:bad_param) { "commit=%u00ABscript%u00BBalert(209);%u00AB/script%u00BB" }
  let(:bad_param) { "frontend_query=znaqnag%3N%22Nhgbunhf+Sevfpu" }
  let(:env) do
    {
      "REQUEST_METHOD"=>"GET",
      "QUERY_STRING"=> bad_param,
      "REQUEST_URI"=>"/?#{bad_param}",
      "PATH_INFO"=>"/",
      "HTTP_ACCEPT"=>"application/json",
      "rack.input" => ""
    }
  end

  it "returns an early 'Bad Request' when given params with a bad encoding" do
    status, headers, body = app.call(env)

    expect(body.join).to eq("Bad Request")
    expect(status).to eq(400)
    expect(headers["Content-Type"]).to eq("application/json; charset=utf-8")
    expect(headers["Content-Length"]).to eq("11")
  end

  it "does nothing when no encoding error if found" do
    status, headers, body = app.call(env.merge("QUERY_STRING" => "", "REQUEST_URI" => "/"))

    expect(body.join).to eq("I'm a teapot.")
    expect(status).to eq(418)
    expect(headers["Content-Type"]).to be_nil
    expect(headers["Content-Length"]).to be_nil
  end

end