require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

require 'hx'
require 'hx/rack'
require 'rack/mock'
require 'rack/lint'

describe Hx::Rack::Application do
  before(:each) do
    @input = FakeInput.new
    @app = Hx::Rack::Application.new(@input, {})
    @app = Rack::Lint.new(@app)
    @service = Rack::MockRequest.new(@app)
  end

  it "should return 404 for unknown paths" do
    response = @service.get("/bogus", :lint => true, :fatal => true)
    response.status.to_i.should == 404
  end

  it "should return 200 with content for known paths" do
    path = "existing"
    content = "BLAH"
    @input.add_entry(path, content)
    response = @service.get("/#{path}", :lint => true, :fatal => true)
    response.status.to_i.should == 200
    response.body.to_s.should == content
  end

  it "should infer content type from file extension by default" do
    cases = { "html" => "text/html",
              "jpeg" => "image/jpeg" }
    for extension, content_type in cases
      path = "blah.#{extension}"
      @input.add_entry(path, "")
      response = @service.get("/#{path}", :lint => true, :fatal => true)
      response.status.to_i.should == 200
      response['Content-Type'].should == content_type
    end
  end

  it "should allow entries to specify their mime type" do
    path = "blah.html"
    content_type = "junk/garbage"
    @input.add_entry(path, "", 'content_type' => content_type)
    response = @service.get("/#{path}", :lint => true, :fatal => true)
    response.status.to_i.should == 200
    response['Content-Type'].should == content_type
  end

  it "should redirect for directories with indices" do
    @input.add_entry("dir/index.html", "")
    response = @service.get("/dir", :lint => true, :fatal => true)
    response.status.to_i.should == 301
    response['Location'].should == "/dir/"
  end

  it "should return index for directories" do
    content = "SOME INDEX STUFF"
    @input.add_entry("dir/index.html", content)
    response = @service.get("/dir/", :lint => true, :fatal => true)
    response.status.to_i.should == 200
    response.body.to_s.should == content
  end

  it "should return index for the root" do
    content = "ROOT INDEX YAY"
    @input.add_entry("index.html", content)
    response = @service.get("/", :lint => true, :fatal => true)
    response.status.to_i.should == 200
    response.body.to_s.should == content
  end
end