#!/usr/bin/env ruby
# $Id: tc_ext_wikidb.rb,v 1.5 2004/05/11 14:43:28 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require "test_common"

module Qwik
  class WikiDB
    def test_private(t)
      t.assert_equal(",k,v", encode_line("k", "v"))
      t.assert_equal(",k,v1,v2", encode_line("k", ["v1", "v2"]))
      t.assert_equal(",k,v1,v2", encode_line("k", "v1", "v2"))
      t.assert_equal(",k,,v2", encode_line("k", nil, "v2"))
    end
  end
end

class TC_WikiDB < Test::Unit::TestCase
  include TestSession

  def test_wikidb
    @page = @site.create("TestPage")
    @wdb  = Qwik::WikiDB.new(@page)

    # test_wikidb_private
    @wdb.test_private(self)

    assert_equal(false, @wdb.exist?("k"))
    @wdb.add("k", "v")
    assert_equal(",k,v\n",  @page.load)

    assert_equal(true,  @wdb.exist?("k"))
    assert_equal(["v"], @wdb["k"])
    assert_equal("v", @wdb["k"][0])
    assert_equal(false, @wdb["k"][0].frozen?)

    assert_equal({"k"=>["v"]}, @wdb.hash)
    @wdb.add("k", "v2")
    assert_equal(["v2"], @wdb["k"]) # can get second value
    
    assert_equal(true,  @wdb.remove("k")) # remove
    assert_equal(false, @wdb.remove("k")) # fail to remove

    assert_equal(false, @wdb.exist?("k"))
    @wdb.add("k", "v1", "v2")
    assert_equal(true,  @wdb.exist?("k"))
    assert_equal(["v1", "v2"], @wdb["k"])
    assert_equal({"k"=>["v1", "v2"]}, @wdb.hash)
    assert_equal(true,  @wdb.remove("k")) # remove
    assert_equal(false, @wdb.remove("k")) # fail to remove

    @wdb.add("a", "b")
    @wdb.add("c", "d")
    assert_equal({"a"=>["b"], "c"=>["d"]}, @wdb.hash)

    @wdb.each {|k, v|
      assert_instance_of(String, k)
      assert_equal(false, k.frozen?)
      assert_instance_of(Array, v)
    }
  end

  def test_nil
    @page = @site.create("TestPage")
    @wdb  = Qwik::WikiDB.new(@page)

    assert_equal(false, @wdb.exist?("k"))
    @wdb.add("k", nil, "v2")
    assert_equal(",k,,v2\n",  @page.load)
    assert_equal(["", "v2"], @wdb["k"])
  end
end
