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

class WebHookJobTest < ActiveSupport::TestCase
  disable_transactional_fixtures!

  setup do
    User.current = nil
  end

  teardown do
    User.current = nil
  end

  test 'webhook job performs work' do
    webhook = Factory(:webhook, :account_created_on => true, :user_created_on => true)
    Account.any_instance.stubs(:web_hooks_allowed?).returns(true)
    User.current = webhook.account.users.first

    jobs = Resque.queue(:web_hooks)
    assert jobs.empty?
    buyer = Factory(:buyer_account, :provider_account => webhook.account)
    assert_equal 2, jobs.size
  end

  test 'be retried' do
    WebHookJob.ancestors.include?(Resque::Plugins::Retry)
  end

  class CustomError < StandardError; end

  test 'raises exception when not last retry' do
    WebHookJob.stubs(:retry_criteria_valid?).returns(true)

    assert_raise(CustomError) do
      WebHookJob.handle_failure(CustomError.new, 'some-uuid', 'provider-id')
    end
  end

  test 'handles failure when last retry' do
    WebHookJob.stubs(:retry_criteria_valid?).returns(false)

    exception = CustomError.new
    WebHookFailures.expects(:add).with('provider_id', exception, 'some-uuid', 'url', 'xml')
    WebHookJob.handle_failure(exception, 'some-uuid', 'provider_id', 'url', 'xml')
  end

  test 'perform sends the webhook' do
    WebHookJob.expects(:push).with('url', 'xml', 'content_type')
    WebHookJob.perform('uuid', 'provider', 'url', 'xml', 'content_type')
  end

  test 'perform handles failure' do
    WebHookJob.expects(:push).raises(RestClient::Exception)
    WebHookJob.expects(:handle_failure).with(instance_of(RestClient::Exception), 'uuid', 'provider', 'url', 'xml')
    WebHookJob.perform('uuid', 'provider', 'url', 'xml', 'content_type')
  end

  test 're-raises errors generated by the remote' do
    RestClient.expects(:post).with('url', 'xml', :content_type => 'content_type').raises(RestClient::Exception)
    assert_raise(::WebHookJob::ClientError) do
      WebHookJob.push('url', 'xml', 'content_type')
    end
  end

  test 'push with content type' do
    RestClient.expects(:post).with('url', 'xml', :content_type => 'application/xml')
    WebHookJob.push('url', 'xml', 'application/xml')
  end

  test 'push without content type' do
    RestClient.expects(:post).with('url', :params => {:xml => 'xml'})
    WebHookJob.push('url', 'xml')
  end

end
