#!/usr/bin/env ruby

# :nodoc:

require 'ftools'
require 'test/unit'
require '../lib/xmlconfigfile'

class TC_Reload < Test::Unit::TestCase # :nodoc:
  def setup
    ENV['PARAM_1'] = 'param1'
    ENV['PARAM2']  = '4711'
    File::copy('original_files/config.xml', '.')
  end

  def test_invalid_reload_period
    assert_raises(ArgumentError) { XmlConfigFile.new('config.xml', 'crap') }
    assert_raises(ArgumentError) { XmlConfigFile.new('config.xml', 0) }
    assert_raises(ArgumentError) { XmlConfigFile.new('config.xml', -1) }
    assert_raises(ArgumentError) { XmlConfigFile.new('config.xml', -1.5) }
  end

  def test_reload_valid_configuration
    config = XmlConfigFile.new('config.xml', 2)
    File::copy('original_files/changed_config.xml', 'config.xml')
    File::utime(0, 0, 'config.xml')
    sleep 3
    assert_equal('schmidt', config.get_string('/config/db/user'))
    assert_equal(4711, config.get_int('/config/environment-variable/@att'))

    # Check, if changes in environment are reflected correctly.
    ENV['PARAM_1'] = 'new'
    ENV['PARAM2'] = '4712'
    sleep 3
    assert_equal('schmidt', config.get_string('/config/db/user'))
    assert_equal(4711, config.get_int('/config/environment-variable/@att'))

    # We have to touch the file explicitly!
    now = Time::now
    File::utime(now, now, 'config.xml')
    sleep 3
    assert_equal('This is new (4712).', config.get_string('/config/environment-variable'))
    assert_equal(4712, config.get_int('/config/environment-variable/@att'))
    config.close
  end

  def test_reload_invalid_configuration
    # An invalid configuration file will be ignored, i.e.
    # the last working configuration will be used. Additionally,
    # a message will be printed on STDERR.
    config = XmlConfigFile.new('config.xml', 2)
    File::copy('original_files/invalid_config.xml', 'config.xml')
    File::utime(0, 0, 'config.xml')
    sleep 3
    assert_equal('maik', config.get_string('/config/db/user'))

    # Wellformed changes are fine. This test ensures, that an
    # instance of class XmlConfigFile will still work after
    # reading an invalid configuration file.
    File::copy('original_files/changed_config.xml', 'config.xml')
    sleep 3
    assert_equal('schmidt', config.get_string('/config/db/user'))
    config.close
  end
end

