#!/usr/bin/env ruby
# $Id: tc_ext_wikidb.rb,v 1.3 2004/04/21 09:32:30 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.

$LOAD_PATH.unshift('../../lib')
$LOAD_PATH.unshift('../../compat')
require 'test/unit'
require 'qwik/site'
require 'qwik/ext_wikidb'

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'))
    end
  end
end

class TC_WikiDB < Test::Unit::TestCase
  def setup
    @config = Qwik::Config.new(true)
    @config.data_dir = './'
    @dir = './test/'.path
    @dir.rmtree if @dir.directory?
    @dir.rmdir  if @dir.directory?
    @dir.mkdir if !@dir.directory?
    @site = Qwik::Site.new(@config, 'test')
    @page = @site.create('tesdb')
    @wdb  = Qwik::WikiDB.new(@page)
  end

  def test_wikidb_private
    @wdb.test_private(self)
  end

  def test_wikidb
    assert_equal(false, @wdb.exist?('k'))
    assert_equal(true,  @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)
    assert_equal(true, @wdb.add('k', 'v2')) # added twice
    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'))
    assert_equal(true,  @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

    assert_equal(true,  @wdb.add('a', 'b'))
    assert_equal(true,  @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 teardown()
    @dir.rmtree if @dir.directory?
    @dir.rmdir  if @dir.directory?
  end
end
