require 'test/unit'
require 'numru/netcdf'
require 'date'
include NumRu
class TestPutAttr < Test::Unit::TestCase
  def setup
    @s = 'tmp.nc'
    @f = NetCDF.create(@s)
    @d = @f.def_dim('x',5)
    @v = @f.def_var('x','sfloat',[@d])
  end
  def teardown
    @f.close
    if File.exist?(@s)
      begin
        File.delete(@s)
      rescue
        p $!
      end
    end
  end
  def test_att_history_get
    att = @f.put_att("history", Date.today.to_s )
    assert_equal att.get,
                 @f.att("history").get
  end
  def test_att_int_att_get
    att = @f.put_att("int_att",123)
    att = @f.put_att("sfloat_att",1.0/3.0,'sfloat')
    att = @f.put_att("sfloat_att2",2.0/3.0,NArray::SFLOAT)
    att = @v.put_att("long_name",'test variable')
    att = @v.put_att("int_att",123)
    assert_equal att.get,
                 @v.att("int_att").get
  end

  def test_att_changed_to_text
    att = @v.put_att("float_att",1.0/3.0)
    att = @v.put_att("float_array",[0.1, 0.2, 30])
    tmp = NArray.sfloat(3).indgen!
    tmp = tmp/3
    att = @v.put_att("sfloat_narray",tmp)
    att = @v.put_att("float_narray",NArray.float(3).indgen!)
    att = @v.put_att("sint_narray",NArray.sint(3).indgen!)
    att = @v.put_att("int2float",10,'float')
    att = att = @v.put_att("dummy",10,'float')
    assert att.put('changed to text')
    att.name = 'changed'
  end

  def test_destined_to_fail_complex
    assert_raise(NetcdfError) do
      @v.put_att("destined_to_fail", 9.8, 'complex')
      # "unsupported type. code = 7"
    end
  end

  def test_destined_to_fail_string
    assert_raise(ArgumentError) do
      @v.put_att("destined_to_fail", 9.8, 'string')
      # Unrecognized NArray type>
    end
  end

  def test_destined_to_fail_int
    assert_raise(NetcdfError) do
      @v.put_att("destined_to_fail", 'hello', 'int')
      # attribute type must be 'char' (or nil) for a String value
    end
  end

  def test_destined_to_fail_mixed_array
    assert_raise(TypeError) do
      @v.put_att("destined_to_fail",[10,30,'sss'])
      # no implicit conversion of String into Integer
    end
  end
end
