source: flex_extract.git/Testing/Regression/Compare_gribfiles/test_cmp_grib_file.py @ be6c0a2

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

added Readme to tests; changed directory structure; added recent test results;

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