33import unittest
44import os
55from numpy .testing import assert_array_equal , assert_array_almost_equal
6+ import numpy as np
67
78def generateString (length , alphabet = string .ascii_letters + string .digits + string .punctuation ):
89 return ('' .join ([random .choice (alphabet ) for i in range (length )]))
@@ -20,6 +21,10 @@ def generateString(length, alphabet=string.ascii_letters + string.digits + strin
2021datau = data .astype ('U' )
2122datac = stringtochar (data , encoding = 'ascii' )
2223
24+ nx , n_strlen = 3 , 10
25+ unicode_strings = np .array (['Münster' , 'London' , 'Amsterdam' ],dtype = 'U' + str (n_strlen ))
26+ unicode_strings2 = np .array (['Münster' , 'Liége' , 'Amsterdam' ],dtype = 'U' + str (n_strlen ))
27+
2328class StringArrayTestCase (unittest .TestCase ):
2429
2530 def setUp (self ):
@@ -28,6 +33,8 @@ def setUp(self):
2833 nc .createDimension ('n1' ,None )
2934 nc .createDimension ('n2' ,n2 )
3035 nc .createDimension ('nchar' ,nchar )
36+ nc .createDimension ("x" , nx )
37+ nc .createDimension ("nstr" , n_strlen )
3138 v = nc .createVariable ('strings' ,'S1' ,('n1' ,'n2' ,'nchar' ))
3239 v2 = nc .createVariable ('strings2' ,'S1' ,('n1' ,'n2' ,'nchar' ))
3340 # if _Encoding set, string array should automatically be converted
@@ -44,6 +51,11 @@ def setUp(self):
4451 v2 [- 1 ,- 1 ] = data [- 1 ,- 1 ].tobytes () # write single python string
4552 # _Encoding should be ignored if an array of characters is specified
4653 v3 [:] = stringtochar (data , encoding = 'ascii' )
54+ # test unicode strings (issue #1440)
55+ v4 = nc .createVariable ("strings4" , "S1" , dimensions = ("x" , "nstr" ,))
56+ v4 ._Encoding = "UTF-8"
57+ v4 [:] = unicode_strings
58+ v4 [1 ] = "Liége"
4759 nc .close ()
4860
4961 def tearDown (self ):
@@ -57,6 +69,8 @@ def runTest(self):
5769 v = nc .variables ['strings' ]
5870 v2 = nc .variables ['strings2' ]
5971 v3 = nc .variables ['strings3' ]
72+ v4 = nc .variables ['strings4' ]
73+ assert np .all (v4 [:]== unicode_strings2 )
6074 assert v .dtype .str [1 :] in ['S1' ,'U1' ]
6175 assert v .shape == (nrecs ,n2 ,nchar )
6276 for nrec in range (nrecs ):
0 commit comments