require 'minitest/autorun'
require 'minitest/unit'
require 'mocha/mini_test'
require './lib/couchpillow.rb'

class TestDocument < Minitest::Test

  class TestDoc < CouchPillow::Document
    type              :test
    validate_presence :xyz
    validate          :xyz, "must be Numeric", lambda { |v| v.is_a? Numeric }
  end


  def mock_time
    return @time if @time
    @time = Time.now
    Time.stubs(:now).returns(@time)
    @time
  end


  def setup
    @db = mock('couchbaseserver')
    @db.stubs(:set)
    @db.stubs(:delete)
    @db.stubs(:replace)
    @db.stubs(:get)
    CouchPillow.db = @db
  end


  def test_create
    d = CouchPillow::Document.new
    d.save!
  end


  def test_timestamp
    d = CouchPillow::Document.new({}, "1")
    d.save!
    assert d.created_at
    assert d.updated_at
  end


  def test_type
    d = CouchPillow::Document.new({}, "1")
    assert_equal "default", d._type
  end


  def test_type_subclasses
    d = TestDoc.new({}, "1")
    assert_equal "test", d._type
  end


  def test_validate_presence
    d = TestDoc.new
    assert_raises CouchPillow::Document::ValidationError do
      d.save!
    end

    d.xyz = 10
    d.save!
  end


  def test_validate_custom
    d = TestDoc.new
    d.xyz = "string"
    assert_raises CouchPillow::Document::ValidationError do
      d.save!
    end

    d.xyz = {}
    assert_raises CouchPillow::Document::ValidationError do
      d.save!
    end

    d.xyz = 123
    d.save!
  end


  def test_to_json
    mock_time
    d = CouchPillow::Document.new({}, "1")
    assert_equal "{\"_id\":\"1\",\"created_at\":\"#{mock_time.to_s}\",\"_type\":\"default\"}", d.to_json
  end

end