require 'ibm_db2'
require 'stringio'
require 'test/unit'

Dir['tests/test_*.rb'].each do |file|
  next if file =~ /002/
  require file
  break if file =~ /003/
end

class TestIbmDb2 < Test::Unit::TestCase
  attr_reader :database, :user, :password, :hostname, :port

  def initialize *args
    super
    @database = 'SAMPLE';
    @user = 'db2inst1';
    @password = 'password';
    @hostname = 'localhost';
    @port = 50000;

    @db = @database;
    @username = @user;
  end

  def setup
    prepconn = DB2::connect database, user, password

    # Drop the test view, in case it exists
    drop = 'DROP TABLE anime_cat'
    result = DB2::exec prepconn, drop rescue nil
    
    # Drop the test table, in case it exists
    drop = 'DROP TABLE animals'
    result = DB2::exec prepconn, drop rescue nil
    
    # Create the test table
    create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32), name CHAR(16), weight DECIMAL(7,2))'
    result = DB2::exec prepconn, create
    
    # Populate the test table
    animals = [
        [0, 'cat', 'Pook', 3.2],
        [1, 'dog', 'Peaches', 12.3],
        [2, 'horse', 'Smarty', 350.0],
        [3, 'gold fish', 'Bubbles', 0.1],
        [4, 'budgerigar', 'Gizmo', 0.2],
        [5, 'goat', 'Rickety Ride', 9.7],
        [6, 'llama', 'Sweater', 150]
    ]
    
    insert = 'INSERT INTO animals (id, breed, name, weight) VALUES (?, ?, ?, ?)'
    stmt = DB2::prepare prepconn, insert
    if stmt
        for animal in animals
            result = DB2::execute stmt, animal
        end
    end
    
    # Create test view
    DB2::exec prepconn, 'CREATE VIEW anime_cat AS
        SELECT name, breed FROM animals
        WHERE id = 0'

    DB2::close prepconn
  end

  def capture 
    stdout = $stdout
    buffer = $stdout = StringIO.new
    yield
    $stdout = stdout
    buffer.rewind
    buffer.read
  end

  def expected
    open(caller[0].split(':')[0]) {|f| f.read}.split("\n__END__\n",2)[-1]
  end
end
