1# This file is part of h5py, a Python interface to the HDF5 library. 2# 3# http://www.h5py.org 4# 5# Copyright 2008-2013 Andrew Collette and contributors 6# 7# License: Standard 3-clause BSD; see "license.txt" for full license terms 8# and contributor agreement. 9 10""" 11 Tests the h5py.AttributeManager.create() method. 12""" 13 14import numpy as np 15from .. import h5t, h5a 16 17from .common import ut, TestCase 18 19class TestArray(TestCase): 20 21 """ 22 Check that top-level array types can be created and read. 23 """ 24 25 def test_int(self): 26 # See issue 498 27 28 dt = np.dtype('(3,)i') 29 data = np.arange(3, dtype='i') 30 31 self.f.attrs.create('x', data=data, dtype=dt) 32 33 aid = h5a.open(self.f.id, b'x') 34 35 htype = aid.get_type() 36 self.assertEqual(htype.get_class(), h5t.ARRAY) 37 38 out = self.f.attrs['x'] 39 40 self.assertArrayEqual(out, data) 41 42 def test_string_dtype(self): 43 # See issue 498 discussion 44 45 self.f.attrs.create('x', data=42, dtype='i8') 46 47 def test_str(self): 48 # See issue 1057 49 self.f.attrs.create('x', chr(0x03A9)) 50 out = self.f.attrs['x'] 51 self.assertEqual(out, chr(0x03A9)) 52 self.assertIsInstance(out, str) 53 54 def test_tuple_of_unicode(self): 55 # Test that a tuple of unicode strings can be set as an attribute. It will 56 # be converted to a numpy array of vlen unicode type: 57 data = ('a', 'b') 58 self.f.attrs.create('x', data=data) 59 result = self.f.attrs['x'] 60 self.assertTrue(all(result == data)) 61 self.assertEqual(result.dtype, np.dtype('O')) 62 63 # However, a numpy array of type U being passed in will not be 64 # automatically converted, and should raise an error as it does 65 # not map to a h5py dtype 66 data_as_U_array = np.array(data) 67 self.assertEqual(data_as_U_array.dtype, np.dtype('U1')) 68 with self.assertRaises(TypeError): 69 self.f.attrs.create('y', data=data_as_U_array) 70 71 def test_shape(self): 72 self.f.attrs.create('x', data=42, shape=1) 73 result = self.f.attrs['x'] 74 self.assertEqual(result.shape, (1,)) 75 76 self.f.attrs.create('y', data=np.arange(3), shape=3) 77 result = self.f.attrs['y'] 78 self.assertEqual(result.shape, (3,)) 79 80 def test_dtype(self): 81 dt = np.dtype('(3,)i') 82 array = np.arange(3, dtype='i') 83 self.f.attrs.create('x', data=array, dtype=dt) 84 # Array dtype shape is incompatible with data shape 85 array = np.arange(4, dtype='i') 86 with self.assertRaises(ValueError): 87 self.f.attrs.create('x', data=array, dtype=dt) 88 # Shape of new attribute conflicts with shape of data 89 dt = np.dtype('()i') 90 with self.assertRaises(ValueError): 91 self.f.attrs.create('x', data=array, shape=(5,), dtype=dt) 92