
target = Object.new
target.extend(Transfluent::ApiHelper)

describe Transfluent::ApiHelper, '#symbolize_hash' do
  it 'should convert all keys in a hash to symbols' do
    hash = {'foo' => 'bar'}

    result = target.symbolize_hash hash

    expect(result).to have_key(:foo)
    expect(result).not_to have_key('foo')
    expect(result[:foo]).to eq('bar')
  end

  it 'should do conversion recursively' do
    hash = {'foo' => {'bar' => 'baz'}}

    result = target.symbolize_hash hash

    expect(result).to have_key(:foo)
    expect(result[:foo]).to have_key(:bar)
    expect(result[:foo][:bar]).to eq('baz')
  end
end

describe Transfluent::ApiHelper, '#symbolize_array' do
  it 'should convert all hashes in the array' do
    array = [
      {'foo' => 'bar'}
    ]

    result = target.symbolize_array array

    expect(result).to be_a_kind_of(Array)
    expect(result[0]).to have_key(:foo)
    expect(result[0]).not_to have_key('foo')
  end
end

describe Transfluent::ApiHelper, '#parse_response' do
  it 'should return a string when response is a string' do
    result = target.parse_response({ 'status' => 'OK', 'response' => 'a string' })

    expect(result).to eq('a string')
  end

  it 'should return a hash when response is a json object' do
    result = target.parse_response({ 'status' => 'OK', 'response' => { 'foo' => 'bar' }})

    expect(result).to be_a_kind_of(Hash)
    expect(result).to have_key(:foo)
  end

  it 'should return an array when response is an array' do
    result = target.parse_response({ 'status' => 'OK', 'response' => [ { 'foo' => 'bar' } ] })

    expect(result).to be_a_kind_of(Array)
    expect(result[0]).to have_key(:foo)
  end

  it 'should raise an exception when response contains error' do
    expect { target.parse_response({
        'status' => 'ERROR',
        'error' => {
          'type' => 'EBackendError',
          'message' => 'Error description'
        }
      })
    }.to raise_error(Transfluent::ApiError, /EBackendError.*Error description/)
    
  end
end
