source: flex_extract.git/test/Regression/Compare_gribfiles/test_cmp_grib_file.py @ 16560bc

ctbtodev
Last change on this file since 16560bc was 16560bc, checked in by Anne Philipp <anne.philipp@…>, 5 years ago

Added a comparison test for retrieved grib files of different versions (Regression test)

  • Property mode set to 100644
File size: 8.0 KB
Line 
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4"""
5
6# ------------------------------------------------------------------------------
7# MODULES
8# ------------------------------------------------------------------------------
9import os
10import sys
11from eccodes import GribFile, GribMessage
12
13# ------------------------------------------------------------------------------
14# FUNCTION
15# ------------------------------------------------------------------------------
16def get_cmdline_params(parlist, debug=True):
17
18    import getopt
19
20    iref_path = '' # e.g. Reference_files
21    inew_path = '' # e.g. New_files
22    smatch = '' # e.g. files matching pattern
23
24    try:
25        opts, pars = getopt.getopt(parlist,
26                                   "hr:n:p:",
27                                   ["ipref=", "ipnew=", "pattern="])
28    except getopt.GetoptError:
29        print('test_cmp_grib_file.py -r <ipref> -n <ipnew> -p <pattern>')
30        sys.exit(2)
31
32    for opt, par in opts:
33        if opt == '-h':
34            print('test_cmp_grib_file.py -r <ipref> -n <ipnew> -p <pattern>')
35            sys.exit()
36        elif opt in ("-r", "--ipref"):
37            iref_path = par
38        elif opt in ("-n", "--ipnew"):
39            inew_path = par
40        elif opt in ("-p", "--pattern"):
41            smatch = par
42
43    if iref_path == '':
44        sys.exit('NO REFERENCE INPUT PATH SET!')
45    if inew_path == '':
46        sys.exit('NO "NEW" COMPARISON INPUT PATH SET!')
47    if smatch == '':
48        sys.exit('NO MATCHING PATTERN FOR FILES SET!')
49
50    if debug:
51        print("\n\nWelcome!")
52        print('Reference path is: ', iref_path)
53        print('New path is: ', inew_path)
54        print('Filepattern is: ', smatch)
55
56    return iref_path, inew_path, smatch
57
58def get_files(ipath, matchingstring, debug=True):
59    """
60        @Description:
61            Get filenames from input path matching the
62            string or regular expression and return it.
63
64        @Input:
65            ipath: string
66                Path to the files.
67
68            matchingstring: string
69                A string defining the filenames,
70                with or without regular exprssion.
71
72        @Return
73            filename: list of strings
74                A list of all files matching the pattern of
75                matchingstring.
76    """
77    import fnmatch
78
79    files = []
80
81    for fn in os.listdir(ipath):
82        if fnmatch.fnmatch(fn, matchingstring):
83            files.append(fn)
84
85    filelist = sorted(files)
86    if debug:
87        print('The input files are: %s' %(filelist))
88
89    return filelist
90
91def cmp_files_list(flist1, flist2):
92    '''
93    '''
94
95    # 1. same length?
96    length = len(flist1) == len(flist2)
97    if not length:
98        print('There are not the same amount of files.')
99        sys.exit('Message 1')
100
101    # 2. same content?
102    content = [True for i, j in zip(flist1, flist2) if i == j]
103    if not len(content) == len(flist1):
104        print('Not the same file list')
105        sys.exit('Message 2')
106
107    return True
108
109
110def cmp_number_messages(iref, flist1, inew, flist2):
111
112    ref_dict = {}
113    new_dict = {}
114    res_dict = {}
115    for file in flist1:
116        with GribFile(os.path.join(iref,file)) as grib:
117            ref_dict[file] = len(grib)
118        with GribFile(os.path.join(inew,file)) as grib:
119            new_dict[file] = len(grib)
120
121        res_dict[file] = ref_dict[file] == new_dict[file]
122
123    for k, res in res_dict.items():
124        if not res == True:
125            print('LOG: Amount of messages in files {} are not the same!'.format(k))
126
127    return True
128
129
130def cmp_grib_msg_header(ipath_ref, ipath_new, filelist):
131    from subprocess import Popen, PIPE
132    # ref_dict = {}
133    # new_dict = {}
134    # for file in flist1:
135        # with GribFile(os.path.join(iref,file)) as grib:
136            # for i in range(len(grib)):
137                # msg = GribMessage(grib)
138                # ref_dict[file] = {}
139                # ref_dict[file][i] = [msg['shortName'],msg['level'],
140                                  # msg['editionNumber'],msg['dataDate'],
141                                  # msg['dataTime'],msg['marsClass'],
142                                  # msg['type'], msg['gridType'],
143                                  # msg['stepRange']]
144    error_flag = False
145    cmp_flag = False
146    for file in filelist:
147        try:
148            res = Popen(['grib_compare', '-H',
149                         ipath_ref + '/' + file,
150                         ipath_new + '/' + file],
151                        stdin=PIPE, stdout=PIPE, stderr=PIPE)
152            output, error = res.communicate()#.decode("utf-8"))
153            if error:
154                print('... ERROR: \n\t{}'.format(error.decode()))
155                error_flag = True
156            if output:
157                print('{}'.format(output.decode()))
158                cmp_flag = True
159        except ValueError as e:
160            print('... ERROR CODE: ' + str(e.returncode))
161            print('... ERROR MESSAGE:\n \t ' + str(res))
162            error_flag = True
163        except OSError as e:
164            print('... ERROR CODE: ' + str(e.errno))
165            print('... ERROR MESSAGE:\n \t ' + str(e.strerror))
166            error_flag = True
167
168    if error_flag:
169        sys.exit('... ERROR IN GRIB MESSAGE COMPARISON!')
170    if cmp_flag:
171        sys.exit('... FILES HAVE DIFFERENCES IN GRIB MESSAGES!')
172
173    return True
174
175
176def cmp_grib_msg_statistics(ipath_ref, ipath_new, filelist):
177
178    from subprocess import Popen, PIPE
179
180    error_flag = False
181    cmp_flag = False
182    for file in filelist:
183        try:
184            res = Popen(['grib_compare', '-c', 'statistics:n',
185                         ipath_ref + '/' + file,
186                         ipath_new + '/' + file],
187                        stdin=PIPE, stdout=PIPE, stderr=PIPE)
188            output, error = res.communicate()#.decode("utf-8"))
189            if error:
190                print('... ERROR: \n\t{}'.format(error.decode()))
191                error_flag = True
192            if output:
193                print('\nIn File: {}'.format(file))
194                print('{}'.format(output.decode()))
195                cmp_flag = True
196        except ValueError as e:
197            print('... ERROR CODE: ' + str(e.returncode))
198            print('... ERROR MESSAGE:\n \t ' + str(res))
199            error_flag = True
200        except OSError as e:
201            print('... ERROR CODE: ' + str(e.errno))
202            print('... ERROR MESSAGE:\n \t ' + str(e.strerror))
203            error_flag = True
204
205    if error_flag:
206        sys.exit('... ERROR IN GRIB MESSAGE COMPARISON!')
207    if cmp_flag:
208        sys.exit('... FILES HAVE DIFFERENT STATISTICS!')
209    return True
210
211if __name__ == '__main__':
212
213    # get the parameter list of program call
214    ref_path, new_path, fmatch = get_cmdline_params(sys.argv[1:])
215
216    # get the list of files of both cases
217    ref_files = get_files(ref_path, fmatch)
218    new_files = get_files(new_path, fmatch)
219
220    # flag to store successfull tests
221    suc = True
222
223    # 1. Does the 2 cases contain the same list of files?
224    suc = True if suc and cmp_files_list(ref_files, new_files) else False
225
226    # 2. Does each file in both cases contain the same amount of messages?
227    suc = True if suc and cmp_number_messages(ref_path, ref_files, new_path, new_files) else False
228
229    # 3. Does each file has the same parameters (in Header)?
230    # Since we can be sure that both cases have the same files,
231    # we just use 1 filelist
232    suc = True if suc and cmp_grib_msg_header(ref_path, new_path, new_files) else False
233
234    # 4. Are the statistics of each message the same?
235    # Since we can be sure that both cases have the same files,
236    # we just use 1 filelist
237    suc = True if suc and cmp_grib_msg_statistics(ref_path, new_path, new_files) else False
238
239    # If the program comes this far and flag "suc" = True,
240    # all tests were successful
241    if suc:
242        exit('GRIB_COMPARISON: SUCCESSFULL!')
243    else:
244        exit('GRIB_COMPARISON: FAILURE!')
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG