-
Notifications
You must be signed in to change notification settings - Fork 12
/
unittests.py
executable file
·1873 lines (1642 loc) · 66.9 KB
/
unittests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
a module to execute unittests on all important pieces
of code in this module.
For the moment it mainly calls the example programs defined
in the example_programs directory, and compares the outputs to
stored expected outputs, but later more detailed unittests
are planned as well.
"""
# #[ some notes
#
# Note about the use of the "# #[" and "# #]" comments:
# these are folding marks for my favorite editor, emacs, combined with its
# folding mode
# (see http://www.emacswiki.org/emacs/FoldingMode for more details)
# Please do not remove them.
#
# For details on the revision history, refer to the log-notes in
# the mercurial revisioning system hosted at google code.
#
# Written by: J. de Kloe, KNMI (www.knmi.nl), Initial version 12-Nov-2009
#
# Copyright J. de Kloe
# This software is licensed under the terms of the LGPLv3 Licence
# which can be obtained from https://www.gnu.org/licenses/lgpl.html
#
# note: the tests in the test classes below MUST have a name starting
# with "test" otherwise the unittest module will not use them
#
# note for debugging:
# run a single testcase like this:
# ./unittests.py CheckBUFRWriter.test_run_unknown_descriptor_case
# #]
# #[ pylint exceptions
#
# disable the warning on too many records, since here this
# is caused by the many methods in the unittest.TestCase
# class that is used for unit testing, and there is really
# nothing I can do to change this.
#
# disable warning: Too many public methods (../20)
# pylint: disable=R0904
#
# #]
# #[ imported modules
from __future__ import (absolute_import, division,
print_function) # , unicode_literals)
import os # operating system functions
import sys # operating system functions
import shutil # operating system functions
import unittest # import the unittest functionality
import subprocess # support running additional executables
import stat # to retrieve a file modification timestamp
import time # to handle date/time formatting
from pybufr_ecmwf.helpers import get_and_set_the_module_path
from pybufr_ecmwf.custom_exceptions import IncorrectUsageError
DUMMY_SYS_PATH = sys.path[:] # provide a copy
(DUMMY_SYS_PATH, MY_MODULE_PATH) = get_and_set_the_module_path(DUMMY_SYS_PATH)
# print '(sys.path, MY_MODULE_PATH) = ',(sys.path, MY_MODULE_PATH)
# in case the build is done by setup.py, the created ecmwfbufr.so module will
# be in a path like SWROOT/build/lib.linux-x86_64-2.7/pybufr_ecmwf/
# To ensure the unittests find it, temporarily rename SWROOT/pybufr_ecmwf/
# and create a symlink to SWROOT/build/lib.linux-x86_64-2.7/pybufr_ecmwf/
PYBUFR_ECMWF_MODULE_WAS_RENAMED = False
if 'build/lib' in MY_MODULE_PATH:
print('renaming pybufr_ecmwf to pybufr_ecmwf.renamed')
shutil.move('pybufr_ecmwf', 'pybufr_ecmwf.renamed')
print('creating symlink pybufr_ecmwf')
os.symlink(os.path.join(MY_MODULE_PATH, 'pybufr_ecmwf'), # source
'pybufr_ecmwf') # destination
PYBUFR_ECMWF_MODULE_WAS_RENAMED = True
#else:
# print('MY_MODULE_PATH = ', MY_MODULE_PATH)
try:
from pybufr_ecmwf.bufr_interface_ecmwf import BUFRInterfaceECMWF
from pybufr_ecmwf.raw_bufr_file import RawBUFRFile
# from pybufr_ecmwf import bufr
# from pybufr_ecmwf import bufr_table
from pybufr_ecmwf import ecmwfbufr
except (SyntaxError, ImportError): # as err:
# ensure the code reaches the point where the pybufr_ecmwf.renamed
# is renamed back to pybufr_ecmwf, so allow imports to fail
print('ERROR: some imports failed!!!')
# print('Error was: '+str(err))
# pass
# raise
#import ecmwfbufr # import the wrapper module
# #]
# #[ some constants
EXAMPLE_PROGRAMS_DIR = 'example_programs'
TEST_DIR = 'test_old'
TESTDATADIR = os.path.join(TEST_DIR, 'testdata')
EXP_OUTP_DIR = os.path.join(TEST_DIR, 'expected_test_outputs')
ACT_OUTP_DIR = os.path.join(TEST_DIR, 'actual_test_outputs')
if not os.path.exists(ACT_OUTP_DIR):
os.mkdir(ACT_OUTP_DIR)
# #]
def call_cmd(cmd, rundir=''):
# #[ do the actual call to an external test script
""" a wrapper around run_shell_command for easier testing.
It sets the environment setting PYTHONPATH to allow the
code to find the current pybufr-ecmwf library"""
# get the list of already defined env settings
env = os.environ
if 'PYTHONPATH' in env:
settings = env['PYTHONPATH'].split(':')
if not MY_MODULE_PATH in settings:
env['PYTHONPATH'] = MY_MODULE_PATH+':'+env['PYTHONPATH']
else:
env['PYTHONPATH'] = MY_MODULE_PATH
if use_eccodes:
env['PYBUFR_ECMWF_USE_ECCODES'] = 'True'
else:
env['PYBUFR_ECMWF_USE_ECCODES'] = 'False'
# print('DEBUG: env[PYTHONPATH] = ',env['PYTHONPATH'])
# print('DEBUG: env[BUFR_TABLES] = ',env.get('BUFR_TABLES','undefined'))
# print('DEBUG: cmd = ',cmd)
# remove the env setting to
# /tmp/pybufr_ecmwf_temporary_files_*/tmp_BUFR_TABLES/
# that may have been left by a previous test
if 'BUFR_TABLES' in env:
del env['BUFR_TABLES']
# change dir if needed
if rundir:
cwd = os.getcwd()
os.chdir(rundir)
# execute the test and catch all output
subpr = subprocess.Popen(cmd, shell=True, env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines_stdout = subpr.stdout.readlines()
lines_stderr = subpr.stderr.readlines()
subpr.stdout.close()
subpr.stderr.close()
subpr.wait()
if rundir:
os.chdir(cwd)
text_lines_stdout = [l.decode() for l in lines_stdout]
text_lines_stderr = [l.decode() for l in lines_stderr]
return (text_lines_stdout, text_lines_stderr)
# #]
def prune_stderr_line(line):
# #[ remove paths from stderr
'''
in case of an error the stderr lines will contain full paths
to the problematic python files, and these may differ from
installation to installation, so cut them away.
'''
search_str1 = 'File "'
search_str2 = '", line '
if (search_str1 in line) and (search_str2 in line):
start_index = line.index(search_str1) + len(search_str1)
end_index = line.index(search_str2)
problematic_file = line[start_index:end_index]
# print('DEBUG: problematic_file = [{0}]'.format(problematic_file))
# print('DEBUG: start_index = ', start_index)
# print('DEBUG: end_index = ', end_index)
# print('DEBUG: line = [{0}]'.format(line))
# print('DEBUG: line[:start_index] = [{0}]'.format(line[:start_index]))
# print('DEBUG: line[end_index:] ) = [{0}]'.format(line[end_index:] ))
pruned_line = ( line[:start_index] +
os.path.split(problematic_file)[1] +
line[end_index:] )
# print('DEBUG: pruned_line = [{0}]'.format(pruned_line))
return pruned_line
else:
return line
# #]
#def call_cmd_and_verify_output(cmd, rundir='', verbose=False):
def call_cmd_and_verify_output(cmd, rundir='', verbose=True,
template_values={}):
# #[ call a test script and verify its output
""" a wrapper around run_shell_command for easier testing.
It automatically constructs a name for the test output based
on the class and function name from which it was called.
Then it executes the test function and redirects the stdout and
stderr outputs to files with the just constructed names.
Finally it compares the actual test outputs with expected outputs
that should be present in the current directory.
If the outputs are as expected the function returns True,
otherwise False."""
# disable the "Too many local variables" pylint warning
# since I feel this helper routine really could not be
# rewritten using less local variables
#
# pylint: disable=R0914
# assume at first that all will work as planned
success = True
# force verbose output (usefull to see what happens if
# travis fails for a python version I dont have locally)
#verbose = True
# #[ some old notes
#print("__name__ = ", __name__)
#print("__file__ = ", __file__)
#print("self.__class__.__name__ = ", self.__class__.__name__)
#print("func_filename = ", sys._getframe().f_code.co_filename)
#print("func_name = ", sys._getframe().f_code.co_name)
#print("dir(frame) = ", dir(sys._getframe()))
#print("dir(f_code) = ", dir(sys._getframe().f_code))
#print("0:callers name = ", sys._getframe(0).f_code.co_name)
#
#print("2:callers name = ", sys._getframe(2).f_code.co_name)
#sys.exit(1)
# see: http://code.activestate.com/recipes/66062/
# for more examples on using sys._getframe()
# #]
# determine the full path of the current python interpreter
# python_interpreter = sys.executable
# disable the pylint warning:
# "Access to a protected member _getframe of a client class"
# pylint: disable=W0212
# determine the name of the calling function
name_of_calling_function = sys._getframe(1).f_code.co_name
# determine the name of the class that defines the calling function
classname_of_calling_function = \
sys._getframe(1).f_locals['self'].__class__.__name__
# pylint: enable=W0212
# construct filenames for the actual and expected outputs
basename_exp = os.path.join(EXP_OUTP_DIR,
classname_of_calling_function+"."+\
name_of_calling_function)
basename_act = os.path.join(ACT_OUTP_DIR,
classname_of_calling_function+"."+\
name_of_calling_function)
actual_stdout = basename_act+".actual_stdout"
actual_stderr = basename_act+".actual_stderr"
expected_stdout = basename_exp+".expected_stdout"
expected_stderr = basename_exp+".expected_stderr"
tmp_cmd = 'python3 '+cmd
# execute the test and catch all output
(lines_stdout, lines_stderr) = call_cmd(tmp_cmd, rundir)
# write the actual outputs to file
file_descr = open(actual_stdout, 'w')
file_descr.writelines(lines_stdout)
file_descr.close()
file_descr = open(actual_stderr, 'w')
file_descr.writelines(lines_stderr)
file_descr.close()
# try to read the expected outputs
try:
fd_stdout = open(expected_stdout, 'r')
fd_stderr = open(expected_stderr, 'r')
expected_lines_stdout = fd_stdout.readlines()
expected_lines_stderr = fd_stderr.readlines()
fd_stdout.close()
fd_stderr.close()
except IOError:
print("ERROR: expected output not found; probably because")
print("you just defined a new unittest case.")
print("Missing filenames:")
if not os.path.exists(expected_stdout):
print("expected_stdout: ", expected_stdout)
print("(actual output available in: ", actual_stdout, ")")
if not os.path.exists(expected_stderr):
print("expected_stderr: ", expected_stderr)
print("(actual output available in: ", actual_stderr, ")")
success = False
return success
for i, line in enumerate(lines_stderr):
lines_stderr[i] = prune_stderr_line(line)
for i, line in enumerate(expected_lines_stderr):
expected_lines_stderr[i] = prune_stderr_line(line)
if template_values:
for key in template_values:
value = template_values[key]
for i, line in enumerate(expected_lines_stdout):
if '#'+key+'#' in line:
modified_line = line.replace('#'+key+'#', value)
expected_lines_stdout[i] = modified_line
for i, line in enumerate(expected_lines_stderr):
if '#'+key+'#' in line:
modified_line = line.replace('#'+key+'#', value)
expected_lines_stderr[i] = modified_line
# since the python3 version changes much printing properties,
# make life easier by ignoring whitespace
lines_stdout = [l.strip() for l in lines_stdout]
lines_stderr = [l.strip() for l in lines_stderr]
expected_lines_stdout = [l.strip() for l in expected_lines_stdout]
expected_lines_stderr = [l.strip() for l in expected_lines_stderr]
# compare the actual and expected outputs
if lines_stdout != expected_lines_stdout:
print("stdout differs from what was expected!!!")
print("to find out what happended execute this diff command:")
print("xdiff "+actual_stdout+' '+expected_stdout)
if verbose:
nlines = max(len(lines_stdout),
len(expected_lines_stdout))
for iline in range(nlines):
try:
line_stdout = lines_stdout[iline]
except:
line_stdout = '[empty]'
try:
exp_line_stdout = expected_lines_stdout[iline]
except:
exp_line_stdout = '[empty]'
if line_stdout != exp_line_stdout:
print('line {0} stdout output: [{1}]'.
format(iline, line_stdout[:80]))
print('line {0} stdout exp. output: [{1}]'.
format(iline, exp_line_stdout[:80]))
success = False
if lines_stderr != expected_lines_stderr:
print("stderr differs from what was expected!!!")
print("to find out what happended execute this diff command:")
print("xdiff "+actual_stderr+' '+expected_stderr)
if verbose:
nlines = max(len(lines_stderr),
len(expected_lines_stderr))
for iline in range(nlines):
try:
line_stderr = lines_stderr[iline]
except IndexError:
line_stderr = '[empty]'
try:
exp_line_stderr = expected_lines_stderr[iline]
except IndexError:
exp_line_stderr = '[empty]'
if line_stderr != exp_line_stderr:
print('line {0} stderr output: [{1}]'.
format(iline, line_stderr[:80]))
print('line {0} stderr exp. output: [{1}]'.
format(iline, exp_line_stderr[:80]))
success = False
return success
# enable the "Too many local variables" warning again
# pylint: enable=R0914
# #]
print("Starting test program:")
use_eccodes = False # not yet default
if '--eccodes' in sys.argv:
use_eccodes = True
sys.argv.remove('--eccodes')
print('using eccodes for unittest run')
else:
print('using bufrdc for unittest run')
# test classes that work for both bufrdc and eccodes
# manual run:
'''
setenv PYTHONPATH `pwd`
setenv PYBUFR_ECMWF_USE_ECCODES True
./example_programs/example_for_using_bufr_message_iteration.py test/testdata/S-O3M_GOME_NOP_02_M02_20120911034158Z_20120911034458Z_N_O_20120911043724Z.bufr
'''
class CheckBUFRReader(unittest.TestCase):
# #[ 3 tests
"""
a class to check the BUFRReader class
"""
# common settings for the following tests
testinputfileERS = os.path.join(
TESTDATADIR, 'ISXH58EUSR199812162225')
testinputfileGOME = os.path.join(
TESTDATADIR,
'S-O3M_GOME_NOP_02_M02_20120911034158Z_20120911034458Z_N_O_20120911043724Z.bufr')
testinputfileGRAS = os.path.join(
TESTDATADIR,
'S-GRM_-GRAS_RO_L12_20120911032706_001_METOPA_2080463714_DMI.BUFR')
# taken from development branch nl8_CY45R1_May23
testinputfileAEOLUS = os.path.join(TESTDATADIR, "aeolus_l2b.bufr")
def test_run_decoding_example_message_iter_ERS(self):
# #[
"""
test the decoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_bufr_message_iteration.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfileERS
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_decoding_example_message_iter_GOME(self):
# #[
"""
test the decoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_bufr_message_iteration.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfileGOME
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_decoding_example_message_iter_GRAS(self):
# #[
"""
test the decoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_bufr_message_iteration.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfileGRAS
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_decoding_example_message_iter_AEOLUS(self):
# #[
"""
test the decoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_bufr_message_iteration.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfileAEOLUS
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
# #]
# test classes that only work for bufrdc
if not use_eccodes:
class CheckRawECMWFBUFR(unittest.TestCase):
# #[ 4 tests
"""
a class to check the ecmwf_bufr_lib interface
"""
# common settings for the following tests
testinputfile = os.path.join(TESTDATADIR, 'Testfile.BUFR')
corruptedtestinputfile = os.path.join(TESTDATADIR,
'Testfile3CorruptedMsgs.BUFR')
testoutputfile2u = os.path.join(TESTDATADIR, 'Testoutputfile2u.BUFR')
def test_run_decoding_example(self):
# #[
"""
run the decoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_ecmwfbufr_for_decoding.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfile
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# unfortunately the next check is impossible because the
# fort.12 file holding the fortran stdout seems only closed/flushed
# after the end of this python script, causing inpredictible results.
# Note that the example_for_using_bufrinterface_ecmwf_for_decoding
# and example_for_using_bufrinterface_ecmwf_for_encoding tests
# use the bufr_interface_ecmwf.py module which implement an explicit
# close of the fortran file used for stdout, so in these tests
# the actual text output of the ecmwf bufr library routines is
# tested as well.
# verify the output to the 'fort.12' file
#success = True
#expected_stdout = \
# os.path.join("example_programs/expected_test_outputs",
# 'CheckRawECMWFBUFR.test_run_decoding_example.fort.12')
#actual_stdout = 'fort.12'
#try:
# # try to read the actual and expected outputs
# expected_lines_stdout = open(expected_stdout, 'r').readlines()
# lines_stdout = open(actual_stdout, 'r').readlines()
#
# # compare the actual and expected outputs
# if not (lines_stdout == expected_lines_stdout):
# print("stdout differs from what was expected!!!")
# print("to find out what happended execute this diff command:")
# cmd = "xdiff "+actual_stdout+' '+expected_stdout
# print(cmd)
# # os.system(cmd)
# success = False
#
#except IOError:
# print("ERROR: expected output not found; probably because")
# print("you just defined a new unittest case.")
# print("Missing filename:")
# if not os.path.exists(expected_stdout):
# print("expected_stdout: ", expected_stdout)
# print("(actual output available in: ", actual_stdout, ")")
# success = False
#
#self.assertEqual(success, True)
os.remove('fort.12')
# #]
def test_run_encoding_example(self):
# #[
"""
run the encoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_ecmwfbufr_for_encoding.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testoutputfile2u
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# see also the note on why the 'fort.12' redirected stdout is
# not tested in the test_run_decoding_example method above.
os.remove('fort.12')
# #]
def test_run_pb_routines_example(self):
# #[
"""
run the pb routines example program
"""
# NOTE: for debugging the pb-routines it is possible
# to set the PBIO_PBOPEN environment setting to a value
# of 1. From this it is clear that the pbopen code is
# executed, and the problem is in the interfacingm which
# leads to this error:
#
# SystemError: NULL result without error in PyObject_Call
# run the provided example code and verify the output
testprog = "example_for_using_pb_routines.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfile
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_pb_routines_example2(self):
# #[
"""
run the pb routines example program
"""
# NOTE: for debugging the pb-routines it is possible
# to set the PBIO_PBOPEN environment setting to a value
# of 1. From this it is clear that the pbopen code is
# executed, and the problem is in the interfacingm which
# leads to this error:
#
# SystemError: NULL result without error in PyObject_Call
# run the provided example code and verify the output
testprog = "example_for_using_pb_routines.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.corruptedtestinputfile
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
# #]
class CheckBUFRInterfaceECMWF(unittest.TestCase):
# #[ 5 tests
"""
a class to check the bufr_interface_ecmwf class
"""
# common settings for the following tests
testinputfile = os.path.join(TESTDATADIR, 'Testfile.BUFR')
testoutputfile1u = os.path.join(TESTDATADIR, 'Testoutputfile1u.BUFR')
def test_init(self):
# #[
"""
test instantiating the class
"""
# just instantiate the class
# since this was done already above, before starting the
# sequence of unit tests, and since we omit the verbose
# option, this should be silent
bufrobj = BUFRInterfaceECMWF()
# check its type
checkbufr1 = isinstance(bufrobj, BUFRInterfaceECMWF)
self.assertEqual(checkbufr1, True)
checkbufr2 = isinstance(bufrobj, int)
self.assertEqual(checkbufr2, False)
# check that a call with a non-defined keyword fails
self.assertRaises(TypeError,
BUFRInterfaceECMWF, dummy=42)
# todo: implement this (if this turns out to be important)
# the module does no typechecking (yet) on its
# inputs, so this one is not yet functional
# self.assertRaises(TypeError,
# BUFRInterfaceECMWF, verbose=42)
# #]
def test_get_exp_bufr_table_names(self):
# #[
"""
test the get_expected_ecmwf_bufr_table_names method
"""
center = 210 # = ksec1( 3)
subcenter = 0 # = ksec1(16)
local_version = 1 # = ksec1( 8)
master_table_version = 0 # = ksec1(15)
edition_number = 3 # = ksec0( 3)
master_table_number = 0 # = ksec1(14)
bufrobj = BUFRInterfaceECMWF()
# inspect the location of the ecmwfbufr*.so file, and derive
# from this the location of the BUFR tables that are delivered
# with the ECMWF BUFR library software
ecmwfbufr_path = os.path.split(ecmwfbufr.__file__)[0]
path1 = os.path.join(ecmwfbufr_path, "ecmwf_bufrtables")
path2 = os.path.join(ecmwfbufr_path, '..', "ecmwf_bufrtables")
if os.path.exists(path1):
ecmwf_bufr_tables_dir = path1
elif os.path.exists(path2):
ecmwf_bufr_tables_dir = path2
else:
print("Error: could not find BUFR tables directory")
raise IOError
# make sure the path is absolute, otherwise the ECMWF library
# might fail when it attempts to use it ...
bufrobj.ecmwf_bufr_tables_dir = os.path.abspath(ecmwf_bufr_tables_dir)
(btable, ctable, dtable) = \
bufrobj.get_expected_ecmwf_bufr_table_names(\
center,
subcenter,
local_version,
master_table_version,
edition_number,
master_table_number)
# print("tabel name B: ", btable)
# print("tabel name D: ", dtable)
self.assertEqual(btable, 'B0000000000210000001.TXT')
self.assertEqual(ctable, 'C0000000000210000001.TXT')
self.assertEqual(dtable, 'D0000000000210000001.TXT')
# #]
def test_run_decoding_example(self):
# #[
"""
test the decoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_bufrinterface_ecmwf_for_decoding.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfile
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_encoding_example(self):
# #[
"""
test the encoding example program
"""
# run the provided example code and verify the output
testprog = "example_for_using_bufrinterface_ecmwf_for_encoding.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testoutputfile1u
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_extract_data_category(self):
# #[
"""
test the bufr_extract_data_category example program
"""
# run the provided example code and verify the output
testprog = "bufr_extract_data_category.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfile
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
# #]
class CheckBUFRSorter(unittest.TestCase):
# #[ 1 test
"""
a class to check the sort_bufr_msgs tool
"""
# common settings for the following tests
testinputfile = os.path.join(
TESTDATADIR, 'synop2.bin')
def test_run_sort_bufr_msgs(self):
# #[
"""
test the sort_bufr_msgs tool
"""
# run the provided example code and verify the output
testprog = "sort_bufr_msgs.py"
cmd = os.path.join(EXAMPLE_PROGRAMS_DIR, testprog)
cmd = cmd + ' ' + self.testinputfile
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def tearDown(self):
# cleanup after running the tests from this class
# print('tearDown running')
os.system('\\rm -f 3070*')
os.system('\\rm -f 001101_001102*')
# #]
class CheckBUFRWriter(unittest.TestCase):
# #[ 1 test
def test_run_test_simple_wmo_template(self):
# #[
"""
test a simple writer without delayed replication
"""
# run the provided example code and verify the output
testprog = "test_simple_wmo_template.py"
cmd = os.path.join(TEST_DIR, testprog)
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_test_simple_ccittia5_template(self):
# #[
"""
test a simple writer with ascii text entries
"""
# run the provided example code and verify the output
testprog = "test_simple_ccittia5_template.py"
cmd = os.path.join(TEST_DIR, testprog)
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def test_run_unknown_descriptor_case(self):
# #[
"""
test composing a BUFR message with an unknown descriptor
"""
# run the provided script and verify the output
testprog = "test_unknown_descriptor_in_template.py"
cmd = os.path.join(TEST_DIR, testprog)
success = call_cmd_and_verify_output(cmd)
self.assertEqual(success, True)
# #]
def tearDown(self):
# cleanup after running the tests from this class
# print('tearDown running')
os.system('\\rm -f dummy_bufr_file*')
# #]
class CheckBUFRMessage_W(unittest.TestCase):
# #[ test filling BUFRMessage_W instances
# for the default WMO definitions see:
# pybufr_ecmwf/ecmwf_bufrtables/B0000000000000026000.TXT
# pybufr_ecmwf/ecmwf_bufrtables/D0000000000000026000.TXT
#
def setUp(self):
# #[ setup BUFRWriter and BUFRMessage_W instances
#print('doing setup')
from pybufr_ecmwf.bufr import BUFRWriter
self.bwr = BUFRWriter()
#self.bwr.open(output_bufr_file)
self.msg = self.bwr.add_new_msg(num_subsets=3)
# #]
def test_single_descriptor(self):
# #[ properties of a single descriptor for pressure
self.msg.set_template('010004')
names = self.msg.get_field_names()
self.assertEqual(names, ['PRESSURE',])
props = self.msg.field_properties[10004]
self.assertEqual(props['min_allowed_value'], 0.0)
self.assertEqual(props['max_allowed_value'], 163830.0)
self.assertEqual(props['step'], 10.0)
# #]
def test_str_assign_single_descriptor(self):
# #[ assign to a single descriptor for pressure using str. descr.
self.msg.set_template('010004')
self.msg['PRESS'] = -10.0
def assign(msg, value):
msg['PRESS'] = value
return True
self.assertRaises(IncorrectUsageError, assign, self.msg, [])
self.assertRaises(IncorrectUsageError, assign, self.msg, [10., 20.])
self.assertEqual(assign(self.msg, 123.), True)
self.assertEqual(assign(self.msg, [10., 20., 30.]), True)
# #]
def test_numstr_assign_single_descriptor(self):
# #[ assign to a single descr. for pressure using numstr. descr.
self.msg.set_template('010004')
def assign1(msg, value):
msg['010004'] = value
return True
self.assertEqual(assign1(self.msg, 123.), True)
self.assertEqual(assign1(self.msg, [10., 20., 30.]), True)
# #]
def test_num_assign_single_descriptor(self):
# #[ assign to a single descr. for pressure using num. descr.
self.msg.set_template('010004')
def assign2(msg, value):
msg[0] = value
return True
self.assertEqual(assign2(self.msg, 123.), True)
self.assertEqual(assign2(self.msg, [10., 20., 30.]), True)
# #]
def test_range_single_descriptor(self):
# #[ range check for a single descriptor for pressure
self.msg.set_template('010004')
self.msg['PRESS'] = -10.0
def assign(msg, value):
msg['PRESS'] = value
return True
self.msg.do_range_check = False # default
self.assertEqual(assign(self.msg, -120.), True)
self.msg.do_range_check = True
self.assertRaises(ValueError, assign, self.msg, -120.)
# #]
def test_simple_sequence(self):
# #[ properties for a shore sequence
self.msg.set_template('301033')
names = self.msg.get_field_names()
self.assertEqual(names,
['BUOY/PLATFORM IDENTIFIER',
'TYPE OF STATION',
'YEAR',
'MONTH',
'DAY',
'HOUR',
'MINUTE',
'LATITUDE (HIGH ACCURACY)',
'LONGITUDE (HIGH ACCURACY)'])
# #]
def test_assign_simple_sequence(self):
# #[ assign to an element of a short sequence
self.msg.set_template('301033')
def assign(msg, value):
msg['LATITUDE'] = value
return True
self.assertEqual(assign(self.msg, 1.), True)
self.assertEqual(assign(self.msg, [1., 2., 3.]), True)
self.assertRaises(IncorrectUsageError, assign, self.msg, [])
self.assertRaises(IncorrectUsageError, assign, self.msg,
[1., 2., 3., 4., 5., 6.])
# #]
def test_invalid_assign_simple_sequence(self):
# #[ invalid assignments for a short sequence
self.msg.set_template('301033')
def assign(msg, value):
msg['WRONGTITUDE'] = value
return True
self.assertRaises(IncorrectUsageError, assign, self.msg, 1.0)
# #]
def test_double_assign_simple_sequence(self):
# #[ double assignments for a short sequence
self.msg.set_template('301033')
def assign(msg, value):
msg['ITUDE'] = value
return True
#assign(self.msg, 1.0)
self.assertRaises(IncorrectUsageError, assign, self.msg, 1.0)
# #]
def test_assign_longer_sequence(self):
# #[ assign to an element of a longer sequence
self.msg.set_template('312021') # ERS scatterometer template
names = self.msg.get_field_names()
#self.assertEqual('names', names)
def assign(msg, value):
msg['BACKSCATTER[1]'] = value
return True
self.assertEqual(assign(self.msg, 1.), True)
#self.assertEqual(assign(self.msg, [1., 2., 3.]), True)
#self.assertRaises(IncorrectUsageError, assign, self.msg, [])
#self.assertRaises(IncorrectUsageError, assign, self.msg,
# [1., 2., 3., 4., 5., 6.])
# #]
def test_num_assign_longer_sequence(self):
# #[ assign to an element of a longer sequence
self.msg.set_template('312021') # ERS scatterometer template
names = self.msg.get_field_names()
#self.assertEqual('names', list(enumerate(names)))
def assign(msg, value):
# element with index 28 is first occurrence of BACKSCATTER
# in this template
msg[28] = value
return True
self.assertEqual(assign(self.msg, 1.), True)
self.assertEqual(assign(self.msg, [1., 2., 3.]), True)
# #]
def test_invalid_assign_longer_sequence(self):
# #[ assign to an element of a longer sequence
self.msg.set_template('312021') # ERS scatterometer template
names = self.msg.get_field_names()
def assign(msg, value):
msg['BACKSCATTER'] = value
return True
self.assertRaises(IncorrectUsageError, assign, self.msg, 1.)
# #]
def test_invalid_num_assign_longer_sequence(self):
# #[ assign to an element of a longer sequence
self.msg.set_template('312021') # ERS scatterometer template
names = self.msg.get_field_names()
#self.assertEqual('names', list(enumerate(names)))
def assign(msg, value):
# this template has only 44 elements, index 0 upto 43,
# so 44 should be out of range
msg[44] = value
return True
self.assertRaises(IndexError, assign, self.msg, 1.)
# #]
def test_assign_2d_array(self):
# #[ fill a bufr msg using a 2d array
self.msg.set_template('301033')
def assign(msg, values):
msg.fill(values)
return True
test_values = [3*[1,],
3*[2,],
3*[2016,],