require 'spec_helper'

describe 'OperationFailure message' do
  let(:client) { authorized_client }
  let(:collection_name) { 'operation_failure_message_spec' }
  let(:collection) { client[collection_name] }

  context 'crud error' do
    before do
      collection.delete_many
    end

    context 'a command error with code and code name' do
      # Sharded clusters include the code name: SERVER-55582
      require_topology :single, :replica_set

      it 'reports code, code name and message' do
        client.command(bogus_command: nil)
        raise('Should have raised')
      rescue Mongo::Error::OperationFailure::Family => e
        expect(e.code_name).to eq('CommandNotFound')
        e.message.should =~ /\A\[59:CommandNotFound\]: no such (?:command|cmd): '?bogus_command'?/
      end
    end

    context 'a write error with code and no code name' do
      # Sharded clusters include the code name: SERVER-55582
      require_topology :single, :replica_set

      it 'reports code name, code and message' do
        collection.insert_one(_id: 1)
        collection.insert_one(_id: 1)
        raise('Should have raised')
      rescue Mongo::Error::OperationFailure::Family => e
        e.code_name.should be_nil
        e.message.should =~ /\A\[11000\]: (?:insertDocument :: caused by :: 11000 )?E11000 duplicate key error (?:collection|index):/
      end
    end
  end

  context 'authentication error' do
    require_no_external_user

    let(:client) do
      authorized_client.with(user: 'bogus', password: 'bogus')
    end

    it 'includes code and code name in the message' do
      lambda do
        client.command(ping: 1)
      end.should raise_error(Mongo::Auth::Unauthorized,
                             /User bogus.*is not authorized.*\[18:AuthenticationFailed\]: Authentication failed/)
    end
  end

  context 'when include_server_address_in_errors is enabled' do
    around do |example|
      original = Mongo.include_server_address_in_errors
      Mongo.include_server_address_in_errors = true
      example.run
    ensure
      Mongo.include_server_address_in_errors = original
    end

    it 'includes the server address in the message' do
      client.command(bogus_command: nil)
      raise('Should have raised')
    rescue Mongo::Error::OperationFailure => e
      expect(e.message).to match(/\(on [^)]+:\d+\)\z/)
      expect(e.server_address).to be_a(String)
    end
  end
end
