source: branches/numpy/anuga/utilities/test_system_tools.py @ 6415

Last change on this file since 6415 was 6415, checked in by rwilson, 15 years ago

Added routines to encode/decode arrays of strings (and test).

File size: 7.1 KB
RevLine 
[5897]1#!/usr/bin/env python
2
3
4import unittest
[6304]5import numpy as num
[5897]6import zlib
7from os.path import join, split, sep
[6086]8from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
[6304]9from anuga.config import netcdf_float
[5897]10
11
12# Please, don't add anuga.utilities to these imports.
13# I'm trying to keep this file general, so it works for EQRM and ANUGA
14# EQRM also uses this file, but has a different directory structure
15from system_tools import *
16
17class Test_system_tools(unittest.TestCase):
18    def setUp(self):
19        pass
20
21    def tearDown(self):
22        pass
23
24    def test_user_name(self):
25        user = get_user_name()
26
27        # print user
28        assert isinstance(user, basestring), 'User name should be a string'
29
30    def test_host_name(self):
31        host = get_host_name()
32
33        # print host
34        assert isinstance(host, basestring), 'User name should be a string'       
35
36    def test_compute_checksum(self):
37        """test_compute_checksum(self):
38
39        Check that checksums on files are OK
40        """
41
42        from tempfile import mkstemp, mktemp
43
44        # Generate a text file
45        tmp_fd , tmp_name = mkstemp(suffix='.tmp', dir='.')
46        fid = os.fdopen(tmp_fd, 'w+b')
47        string = 'My temp file with textual content. AAAABBBBCCCC1234'
48        fid.write(string)
49        fid.close()
50
51        # Have to apply the 64 bit fix here since we aren't comparing two
52        # files, but rather a string and a file.
53        ref_crc = safe_crc(string)
54
55        checksum = compute_checksum(tmp_name)
56        assert checksum == ref_crc
57
58        os.remove(tmp_name)
59       
60
61
62        # Binary file
63        tmp_fd , tmp_name = mkstemp(suffix='.tmp', dir='.')
64        fid = os.fdopen(tmp_fd, 'w+b')
65
66        string = 'My temp file with binary content. AAAABBBBCCCC1234'
67        fid.write(string)
68        fid.close()
69
70        ref_crc = safe_crc(string)
71        checksum = compute_checksum(tmp_name)
72
73        assert checksum == ref_crc
74
75        os.remove(tmp_name)       
76       
77        # Binary NetCDF File X 2 (use mktemp's name)
78
79        try:
80            from Scientific.IO.NetCDF import NetCDFFile
81        except ImportError:
82            # This code is also used by EQRM which does not require NetCDF
83            pass
84        else:
[6304]85            test_array = num.array([[7.0, 3.14], [-31.333, 0.0]],
86                                   dtype=num.float)
[5897]87
88            # First file
89            filename1 = mktemp(suffix='.nc', dir='.')
[6086]90            fid = NetCDFFile(filename1, netcdf_mode_w)
[5897]91            fid.createDimension('two', 2)
[6304]92            fid.createVariable('test_array', netcdf_float,
[5897]93                               ('two', 'two'))
94            fid.variables['test_array'][:] = test_array
95            fid.close()
96           
97            # Second file
98            filename2 = mktemp(suffix='.nc', dir='.')
[6086]99            fid = NetCDFFile(filename2, netcdf_mode_w)
[5897]100            fid.createDimension('two', 2)
[6304]101            fid.createVariable('test_array', netcdf_float,
[5897]102                               ('two', 'two'))
103            fid.variables['test_array'][:] = test_array
104            fid.close()
105           
106           
107            checksum1 = compute_checksum(filename1)
108            checksum2 = compute_checksum(filename2)       
109            assert checksum1 == checksum2
110
111
112            os.remove(filename1)
113            os.remove(filename2)
114
115
116    def test_compute_checksum_real(self):
117        """test_compute_checksum(self):
118
119        Check that checksums on a png file is OK
120        """
121
122        # Get path where this test is run
123        # I'm trying to keep this file general, so it works for EQRM and ANUGA
124        path, tail = split(__file__)
125        if path == '':
126            path = '.' + sep
127       
128        filename = path + sep +  'crc_test_file.png'
129
130        ref_crc = 1203293305 # Computed on Windows box
131        checksum = compute_checksum(filename)
132
133        msg = 'Computed checksum = %s, should have been %s'\
134              %(checksum, ref_crc)
135        assert checksum == ref_crc, msg
136        #print checksum
[6360]137
138################################################################################
139# Test the clean_line() utility function.
140################################################################################
141
142    # helper routine to test clean_line()
143    def clean_line_test(self, instr, delim, expected):
144        result = clean_line(instr, delim)
145        self.failUnless(result == expected,
146                        "clean_line('%s', '%s'), expected %s, got %s"
147                        % (str(instr), str(delim), str(expected), str(result)))
148
149    def test_clean_line_01(self):
150        self.clean_line_test('abc, ,,xyz,123', ',', ['abc', '', 'xyz', '123'])
151
152    def test_clean_line_02(self):
153        self.clean_line_test(' abc , ,, xyz  , 123  ', ',',
154                             ['abc', '', 'xyz', '123'])
155
156    def test_clean_line_03(self):
157        self.clean_line_test('1||||2', '|', ['1', '2'])
158
159    def test_clean_line_04(self):
160        self.clean_line_test('abc, ,,xyz,123, ', ',',
[6410]161                             ['abc', '', 'xyz', '123']) 
[6360]162
163    def test_clean_line_05(self):
164        self.clean_line_test('abc, ,,xyz,123, ,    ', ',',
[6410]165                             ['abc', '', 'xyz', '123', ''])
[6360]166
167    def test_clean_line_06(self):
168        self.clean_line_test(',,abc, ,,xyz,123, ,    ', ',',
[6410]169                             ['abc', '', 'xyz', '123', ''])
[6360]170
171    def test_clean_line_07(self):
172        self.clean_line_test('|1||||2', '|', ['1', '2'])
173
174    def test_clean_line_08(self):
175        self.clean_line_test(' ,a,, , ,b,c , ,, , ', ',',
[6410]176                             ['a', '', '', 'b', 'c', '', ''])
[6360]177
178    def test_clean_line_09(self):
179        self.clean_line_test('a:b:c', ':', ['a', 'b', 'c'])
180
181    def test_clean_line_10(self):
182        self.clean_line_test('a:b:c:', ':', ['a', 'b', 'c'])
183
184################################################################################
[6415]185# Test the string_to_char() and char_to_string() utility functions.
186################################################################################
[6360]187
[6415]188    def test_string_to_char(self):
189        import random
190
191        MAX_CHARS = 10
192        MAX_ENTRIES = 100000
193        A_INT = ord('a')
194        Z_INT = ord('z')
195
196        # generate some random strings in a list, with guaranteed lengths
197        str_list = ['x' * MAX_CHARS]        # make first maximum length
198        for entry in xrange(MAX_ENTRIES):
199            length = random.randint(1, MAX_CHARS)
200            s = ''
201            for c in range(length):
202                s += chr(random.randint(A_INT, Z_INT))
203            str_list.append(s)
204
205        x = string_to_char(str_list)
206        new_str_list = char_to_string(x)
207
208        self.failUnlessEqual(new_str_list, str_list)
209
210
211################################################################################
212# Test the raw I/O to NetCDF files of string data encoded/decoded with
213# string_to_char() and char_to_string().
214################################################################################
215
216################################################################################
217
[5897]218if __name__ == "__main__":
[6415]219    #suite = unittest.makeSuite(Test_system_tools, 'test')
220    suite = unittest.makeSuite(Test_system_tools, 'test_string_to_char')
[5897]221    runner = unittest.TextTestRunner()
222    runner.run(suite)
223
Note: See TracBrowser for help on using the repository browser.