require 'test_helper'
require 'tempfile'

module Versions
  class VersionTest < Minitest::Test
    include RubyBuilder::TestHelper

    def test_get_json
      %w{2.1.2 1.9.3 1.9.3-p484}.each do |version|
        get "/versions/#{version}"
        assert last_response.ok?
        assert last_response.headers['content-type'] =~ /application\/json;?/
        assert json_body.is_a? Hash
        assert json_body.has_key? 'string'
        assert json_body.has_key? 'status'
        assert json_body.has_key? 'build_log'
        assert json_body['string'].include? version
        assert ['build in progress', 'built', 'not built'].include? json_body['status']
      end
    end

    def test_get_text
      %w{2.1.2 1.9.3 1.9.3-p484}.each do |version|
        get "/versions/#{version}.txt"
        assert last_response.ok?
        assert last_response.headers['content-type'] =~ /text\/plain;?/
        assert last_response.body.include? version
        assert !json_body.is_a?(Hash)
      end
    end

    def test_get_string
      %w{2.1.2 1.9.3 1.9.3-p484}.each do |version|
        get "/versions/#{version}/string"
        assert last_response.ok?
        assert last_response.headers['content-type'] =~ /text\/plain;?/
        assert last_response.body.include? version
        assert !json_body.is_a?(Hash)
      end
    end

    def test_get_build_log
      %w{2.1.2 1.9.3 1.9.3-p484}.each do |version|
        get "/versions/#{version}/build_log"
        assert last_response.ok?
        assert last_response.headers['content-type'] =~ /text\/plain;?/
      end
    end

    def test_get_binary
      %w{2.1.2 1.9.3 1.9.3-p484}.each do |version|
        file = Tempfile.new('version-binary')
        file.write "stubbed binary for #{version}"
        path = file.path
        file.close
        Version.any_instance.stubs(:filename).returns path
        get "/versions/#{version}/binary"
        assert last_response.ok?
        assert last_response.headers['content-type'] == 'application/x-gzip'
        assert last_response.headers['content-disposition'] =~ /attachment; filename="#{version}.*\.tar\.gz"/
        assert last_response.body == "stubbed binary for #{version}"
      end
    end

  end
end
