casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
test_vishead.py
Go to the documentation of this file.
00001 import sys
00002 import os
00003 import string
00004 import numpy
00005 import os
00006 import shutil
00007 from __main__ import default
00008 from task_vishead import vishead
00009 import unittest
00010 
00011 '''
00012 Unit tests for task vishead. It tests the following modes:
00013     list, summary, get, put
00014     
00015  This example shows how to run it manually from within casapy.
00016  runUnitTest.main(['test_imhead'])
00017 
00018  or outside casapy like this:
00019  casapy -c runUnitTest.py test_imhead
00020 
00021 '''
00022 
00023 datapath=os.environ.get('CASAPATH').split()[0]+'/data/regression/unittest/vishead/'
00024 
00025 # Pick up alternative data directory to run tests on MMSs
00026 testmms = False
00027 if os.environ.has_key('TEST_DATADIR'):   
00028     DATADIR = str(os.environ.get('TEST_DATADIR'))+'/vishead/'
00029     if os.path.isdir(DATADIR):
00030         testmms = True
00031         datapath = DATADIR
00032     else:
00033         print 'WARN: directory '+DATADIR+' does not exist'
00034 
00035 print 'vishead tests will use data from '+datapath         
00036 
00037 input_file = 'n4826_16apr98.ms'  # 128 channels
00038 if testmms:
00039     input_file = 'n4826_16apr98.mms'
00040 stars = "*************"
00041 
00042 stop_on_first_error = False
00043 
00044 # Keeps track of number of passes, failures
00045 # Private class
00046 class tester:
00047     def __init__(self):
00048         self.total = 0
00049         self.fail = 0
00050         self.current_test = ""
00051 
00052     def start(self, msg):
00053         self.total += 1
00054         print
00055         print stars + " Test %s (" % self.total + msg + ") start " + stars
00056         self.current_test = msg
00057 
00058     def end(self, condition, error_msg):
00059         status = "OK"
00060         if not is_true(condition):
00061             print >> sys.stderr, error_msg
00062             self.fail += 1
00063             status = "FAIL"
00064             if stop_on_first_error:
00065                 raise Exception, "Halt!"
00066         print stars + " Test " + self.current_test + " " + status + " " + stars
00067 
00068     def done(self):
00069         print "%s/%s tests passed" % (self.total-self.fail, self.total)
00070         if self.fail > 0:
00071             raise Exception, "%s/%s failures" % (self.fail, self.total)
00072         else:
00073             print "All tests passed, congratulations!"
00074 
00075 
00076 def is_true(x):
00077     # numpy array comparison yields a list of booleans
00078     # (not a single boolean). If necessary, convert from
00079     # list of booleans to single boolean (all elements must be True)
00080     if type(x) != bool and type(x) != numpy.bool_:
00081         return False not in x
00082     else:
00083         return x
00084 
00085 # Unittest class
00086 class vishead_test(unittest.TestCase):
00087     
00088     def setUp(self):
00089         if(os.path.exists(input_file)):
00090             os.system('rm -rf ' +input_file)
00091 
00092         os.system('cp -RL ' +datapath + input_file +' ' + input_file)
00093         default('vishead')
00094 
00095     def tearDown(self):
00096         if os.path.exists(input_file):
00097             os.system('rm -rf ' +input_file)
00098         
00099     def test_list(self):
00100         '''Vishead: List mode'''
00101         t = tester()
00102     
00103         #os.system('pwd')
00104         #os.system('find ./pointingtest.ms -type f | xargs cksum | grep OBSERVATION | grep -v svn')
00105         
00106         t.start("vishead( '" + input_file + "', 'list', [])")
00107         orig_hdr = vishead(input_file, 'list', [])  # default listitems seems to work when
00108                                                     # run manually, but not from here.
00109         print "Original header ="
00110         print orig_hdr
00111         t.end(type(orig_hdr) == type({'key1':'val1', 'key2':'val2'})
00112               and orig_hdr['source_name'][0][2] == 'NGC4826',
00113               "... is a bad header")
00114     
00115     def test_summary(self):
00116         '''Vishead: Summary mode'''
00117         t = tester()
00118         t.start("summary")
00119         vishead( input_file, 'summary' )
00120         t.end( True, "summary failed" )
00121 
00122     def test_accessors(self):
00123         '''Vishead: Test put/get modes'''
00124         t = tester()
00125         orig_hdr = vishead(input_file, 'list', [])
00126         
00127         # Test the set/get value routines.  All of them
00128         for keyword in orig_hdr:
00129             print "List value of %s:" % (keyword), orig_hdr[keyword]
00130             
00131             # Test getting.
00132             valref = vishead(input_file, mode='get', hdkey=keyword, hdindex='')
00133             print "Read value:     ", valref
00134             #sys.stdout.flush()
00135             for j in range(2):
00136                 t.start("get " + keyword + "[%d]" % j)
00137                 val = valref[j]
00138                 
00139                 # numpy array comparison returns a list of booleans
00140                 # therefore we have to manually traverse (sigh...) larger data
00141                 # structures containing numpy arrays, in order to check
00142                 # for equality
00143                 if type(orig_hdr[keyword][j]) is dict:
00144                     are_equal = (orig_hdr[keyword][j].keys() == val.keys())
00145                     for k in val.keys():
00146                         are_equal = (are_equal and is_true(orig_hdr[keyword][j][k] == val[k]))
00147                         if not is_true(orig_hdr[keyword][j][k] == val[k]):
00148                             print orig_hdr[keyword][j][k] == val[k]
00149                 else:
00150                     are_equal = (val == orig_hdr[keyword][j])
00151                 if hasattr(are_equal, 'all'):
00152                     are_equal = are_equal.all()
00153                 t.end(are_equal, \
00154                       "Got "+str(val)+", expected "+str(orig_hdr[keyword][j]))
00155                 
00156             # Test putting.
00157             # Put does not yet use the ref part of valref.
00158             val = valref[0]
00159             if type(val) is dict:
00160                 print str(keyword) + ' is probably a column ' + \
00161                 'with variable length arrays, don\'t try to write that'
00162                 # because the task doesn't support it
00163                 continue
00164     
00165             if len(val) == 1:
00166                 if type(val[0]) == numpy.string_:
00167                     myval = 'the_coolest_' + val[0]
00168                 else:
00169                     myval = 42.0 + val[0]
00170                     
00171                 t.start("put/get " + keyword)
00172                 print "New value:      ", myval
00173                 vishead(input_file, mode='put', hdkey=keyword, hdindex='', hdvalue=myval)
00174                 
00175                 newval = vishead(input_file, mode='get', hdkey=keyword, hdindex='')[0]
00176                 print "Read new value: ", newval
00177                 
00178                 t.end(newval == myval, "Got "+str(newval)+", expected "+str(myval))
00179             else:
00180                 # read/write full column
00181                 all_values = vishead(input_file, mode='get', hdkey=keyword)[0]
00182                 vishead(input_file, mode='put', hdkey=keyword, hdindex='', hdvalue=all_values)
00183                 
00184                 i = 0
00185                 for e in val:
00186                     if type(e) == numpy.string_:
00187                         myval = 'the_coolest_' + e
00188                     else:
00189                         myval = 42.0 + e
00190         
00191                     t.start("put/get " + keyword + '[' + str(i) + ']')
00192                     
00193                     print "New value:      ", myval
00194                     vishead(input_file, mode='put', hdkey=keyword, hdindex=str(i),
00195                             hdvalue=myval)
00196                     
00197                     newval = vishead(input_file, mode='get', hdkey=keyword, hdindex=str(i))[0]
00198                     print "Read new value: ", newval
00199                     
00200                     t.end(newval == myval, "Got "+str(newval)+", expected "+str(myval))
00201                     
00202                     i += 1
00203             
00204             #imhead( input_file, 'put', 'object', val['value'] )
00205         
00206         t.done()
00207     
00208 
00209 def suite():
00210     return [vishead_test]
00211