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

class Backend::StorageTest < ActiveSupport::TestCase

  def setup
    Backend::Storage.reset_config!
  end

  def teardown
    Backend::Storage.reset_config!
  end

  def given_redis_config(yaml)
    FakeFS do
      config = Rails.root.join('config', 'backend_redis.yml')
      config.dirname.mkpath
      config.open('w') { |f| f.puts(yaml) }

      yield
    end
  end

  test 'loads config options from config file' do
    yaml = %{
production:
  db: 0
development:
  db: 1
test:
  host: example.com
  port: 1337
  db: 2
}
    given_redis_config(yaml) do
      Redis::Client.expects(:new).with(Backend::Storage.parse_config)
      storage = Backend::Storage.new
    end
  end

  test 'parse config' do
    yaml = %{
test:
  host: example.com
  port: 1337
  db: 2
}
    given_redis_config(yaml) do
      assert_equal({ :logger => Rails.logger, :thread_safe => false,
                     :host => 'example.com', :port => 1337, :db => 2 },
                     Backend::Storage.parse_config )
    end
  end

  test 'basic operations work' do
    storage = Backend::Storage.new
    storage.set('foo', 'stuff')

    value = storage.get('foo')
    assert_equal 'stuff', value
  end

  test 'set_object serializes and get_object deserializes the object' do
    storage = Backend::Storage.new

    object_before_store = {:name => 'Eric Cartman', :age => 9}
    storage.set_object('foo', object_before_store)

    object_after_store = storage.get_object('foo')
    assert_equal object_before_store, object_after_store
  end

  test 'get_object return nil if value does not exist' do
    storage = Backend::Storage.new
    storage.del('foo')

    assert_nil storage.get_object('foo')
  end

  test 'incrby_and_expire increments' do
    storage = Backend::Storage.new

    storage.set('foo', 42)
    storage.incrby_and_expire('foo', 22, 1.hour)

    assert_equal '64', storage.get('foo')
  end

  test 'incrby_and_expire sets expiration' do
    storage = Backend::Storage.new

    storage.set('foo', 42)
    storage.incrby_and_expire('foo', 22, 1.hour)

    ttl = storage.ttl('foo')
    assert ttl > 0
    assert ttl <= 1.hour
  end
end
