require 'test/unit'
require 'numru/netcdf'
include NumRu

class TestArefAset < Test::Unit::TestCase
  def startup  # call once before tests
  end
  def setup     # call before each test
    @s = 'tmp.nc'
  end
  def teardown  # call after each test
  end
  def shutdown  # call once after tests
  end

  def test_netcdf_create
    f = NetCDF.create(@s)
    f.redef
    dx = f.def_dim('x',5)
    dy = f.def_dim('y',3)
    v = f.def_var('x','sfloat',[dx])
    v2 = f.def_var('x2',NArray::SFLOAT,[dx])
    vxy = f.def_var('xy','sfloat',[dx,dy])
    f.enddef
    v.put([1,2,3,4,5])
    v[{0..3=>2}]=[100,500]
    v[1]=999
    v[3..4]=[-99,-99]
    v2.put(666)
    v2[0..2]=777
    vxy.put(NArray.sfloat(5,3).indgen!)
    vxy[[2,0],[0,2,1]] = [[1,2],[3,4],[5,6]]
    vxy[1,[2,0,1]] = [10,20,30]
    vxy[[4,3],2] = [100,200]
    f.close
  end

  def test_netcdf_open
    unless File.exist?(@s)
      test_netcdf_create
    else
      f = NetCDF.open(@s)
      v = f.var('x')
      assert_equal v[{0..3=>2}], NArray[100.0,500.0].to_f
      assert_equal v[1], NArray[999.0].to_f
      assert_equal v[3..4], NArray[-99.0,-99.0].to_f
      assert_equal v.rank, 1
      assert_equal v[[2,0,0]], NArray[500.0,100.0,100.0].to_f
      vxy = f.var('xy')
      assert_equal vxy[[2,0],[0,2,1]],
                   NArray[[1.0,2.0],[3.0,4.0],[5.0,6.0]].to_f
      assert_equal vxy[1,[2,0,1]],
                   NArray[10.0,20.0,30.0].to_f
      assert_equal vxy[[4,3],2],
                   NArray[100.0,200.0].to_f
      f.close
    end
    if File.exist?(@s)
      begin
        File.delete(@s)
      rescue
        p $!
      end
    end
  end

end
