test_suite.py 29.3 KB
Newer Older
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
# METRo : Model of the Environment and Temperature of Roads
# METRo is Free and is proudly provided by the Government of Canada
# Copyright (C) Her Majesty The Queen in Right of Canada, Environment Canada, 2006
#
#  Questions or bugs report: metro@ec.gc.ca
#  METRo repository: https://framagit.org/metroprojects/metro
#  Documentation: https://framagit.org/metroprojects/metro/wikis/home
#
# Code contributed by:
#  Francois Fortin - Canadian meteorological center
#  Sasa Zhang - Canadian meteorological center
#
#  $LastChangedDate$
#  $LastChangedRevision$
###################################################################################
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

Sasa Zhang's avatar
Sasa Zhang committed
30
31
32
33
34
35
36
37
"""
    This test_suit.py file runs the test suite that comes with the METRo program
"""

import argparse
import json
import os
import subprocess
38
import sys
Sasa Zhang's avatar
Sasa Zhang committed
39
40
41
42
43
import xml.etree.ElementTree as ET

num_of_success = 0
num_of_failure = 0
list_of_failure_cases = []
Sasa Zhang's avatar
Sasa Zhang committed
44
list_of_missing_file_cases = []
Sasa Zhang's avatar
Sasa Zhang committed
45
46
47
dict_error = {}
list_of_errors = []
error_difference = 0
Sasa Zhang's avatar
Sasa Zhang committed
48
49
50
51
52
forecast_exists = False
station_exists = False
observation_exists = False
json_exists = False
reference_exists = False
Sasa Zhang's avatar
Sasa Zhang committed
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


# -------------------------------------Class definition: XmlTree--------------------------------------------------------
class XmlTree:
    sum_of_error_outside_tolerance = 0
    sum_of_error_within_tolerance = 0
    list_of_diff_case = []
    display_info = True

    def __init__(self, error_value=0.01):
        self._error = error_value

    def get_error(self):
        return self._error

    def set_error(self, error_value):
        self._error = error_value

    @staticmethod
    def convert_string_to_tree(xml_file):
        """
            Convert an XML file into a tree
            :param xml_file: the name of the file that is going to be converted
            :return: the tree which is converted from the 'xml_file'
        """
        return (ET.parse(xml_file)).getroot()

Sasa Zhang's avatar
Sasa Zhang committed
80
81
82
83
84
85
86
87
88
89
90
91
92
    def text_compare(self, text1, text2):
        """
            Compare two text strings
            :param text1: text one
            :param text2: text two
            :return: True if these two text strings are a match
        """
        if not text1 and not text2:
            return True
        if text1 == '*' or text2 == '*':
            return True
        return (text1 or '').strip() == (text2 or '').strip()

Sasa Zhang's avatar
Sasa Zhang committed
93
94
95
96
97
98
99
100
101
102
103
104
    def xml_compare(self, xml_file1, xml_file2, excludes=None, display_info=True):
        """
            Compare two xml trees
            :param display_info: boolean variable to indicate if the program display all the different value of tags
            :param xml_file1: the first tree from xml_file1
            :param xml_file2: the second tree from xml_file2
            :param excludes: list of attributes to exclude from comparison
            :return: True if both files match with each other
        """
        global dict_error
        global list_of_errors
        global error_difference
105

Sasa Zhang's avatar
Sasa Zhang committed
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
        if excludes is None:
            excludes = []

        if xml_file1.tag != xml_file2.tag:
            if display_info:
                print('Tags do not match: {} and {}.'.format(xml_file1.tag, xml_file2.tag))
            return False

        for name, value in xml_file1.attrib.items():
            if name not in excludes:
                if xml_file2.attrib.get(name) != value:
                    if display_info:
                        print('Attributes do not match: {}={} and {}={}.'.format(name, value, name,
                                                                                 xml_file2.attrib.get(name)))
                    return False

        for name in xml_file2.attrib.keys():
            if name not in excludes:
                if name not in xml_file1.attrib:
                    if display_info:
                        print('xml_file2 has an attribute xml_file1 is missing: {}.'.format(name))
                    return False

        if not self.text_compare(xml_file1.text, xml_file2.text):
            if abs(float(xml_file1.text) - float(xml_file2.text)) - self.get_error() <= 0.00000001:
                XmlTree.sum_of_error_within_tolerance += 1

            elif abs(float(xml_file1.text) - float(xml_file2.text)) - self.get_error() > 0.00000001:
                XmlTree.sum_of_error_outside_tolerance += 1
                if display_info:
136
137
138
                    if XmlTree.sum_of_error_outside_tolerance == 1:
                        print("\nroadcast_reference.xml            roadcast_test_suite_run.xml"
                              "\n----------------------            ---------------------------")
Sasa Zhang's avatar
Sasa Zhang committed
139
140
141
142
                    tag_reference = '<' + xml_file1.tag + '>' + xml_file1.text + '<' + xml_file1.tag + '>'
                    tag_test_suite_run = '<' + xml_file2.tag + '>' + xml_file2.text + '<' + xml_file2.tag + '>'
                    print("{}{}{}".format(tag_reference.ljust(24), '!='.ljust(10), tag_test_suite_run))

143
144
145
146
147
148
149
150
151
152
153
154
155
156
                    abs_error_difference = abs(float(xml_file1.text) - float(xml_file2.text))

                    if xml_file1.tag not in dict_error.keys():
                        if abs(abs_error_difference - error_difference) <= 0.00000001:
                            dict_error[xml_file1.tag] = []
                            dict_error[xml_file1.tag].append([float(xml_file1.text), float(xml_file2.text)])
                        elif abs_error_difference - error_difference > 0.00000001:
                            dict_error.clear()
                            dict_error[xml_file1.tag] = []
                            dict_error[xml_file1.tag].append([float(xml_file1.text), float(xml_file2.text)])
                            error_difference = abs_error_difference

                    elif xml_file1.tag in dict_error.keys():
                        if abs(abs_error_difference - error_difference) <= 0.00000001:
Sasa Zhang's avatar
Sasa Zhang committed
157
                            list_of_errors = [float(xml_file1.text), float(xml_file2.text)]
158
159
160
161
162
163
                            dict_error[xml_file1.tag].append(list_of_errors)
                        elif abs_error_difference - error_difference > 0.00000001:
                            dict_error.clear()
                            dict_error[xml_file1.tag] = []
                            dict_error[xml_file1.tag].append([float(xml_file1.text), float(xml_file2.text)])
                            error_difference = abs_error_difference
Sasa Zhang's avatar
Sasa Zhang committed
164
165
166
167
168
169
170
            return False

        if not self.text_compare(xml_file1.tail, xml_file2.tail):
            if display_info:
                print('tail: {} != {}.'.format(xml_file1.tail, xml_file2.tail))
            return False

Sasa Zhang's avatar
Sasa Zhang committed
171
172
        child1 = list(xml_file1)
        child2 = list(xml_file2)
Sasa Zhang's avatar
Sasa Zhang committed
173
174
175
176
177
178
179
180
181
182
183
        if len(child1) != len(child2):
            if display_info:
                print('children length differs, {} != {}.'.format(len(child1), len(child2)))
            return False

        for c1, c2 in zip(child1, child2):
            if c1.tag not in excludes:
                if not self.xml_compare(c1, c2, excludes, display_info):
                    pass
        return True

184

Sasa Zhang's avatar
Sasa Zhang committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# -----------------------------------------Method definition------------------------------------------------------------
def process_case_name(case_string, case_list=None):
    """
        Process the case name(s) that is/are passed by the command line.
        :param case_string: case number entered by the user through command line
        :param case_list: a case list including all case number entered by the user
        :return: a validated case list for further process
    """
    if case_list is None:
        case_list = []
    case_string = ''.join(case_string)
    case_string = list(case_string.split(','))
    for case in case_string:
        if case.startswith('case'):
            case = case[4:]
        case = case.zfill(3)
        case = 'case' + case
        if case not in case_list:
            case_list.append(case)
    return case_list


207
def process_test_result(case_folder, test_code, expected_value_json, verbosity=False):
Sasa Zhang's avatar
Sasa Zhang committed
208
209
    """
        Processes the running result(s) of the test suite
210
        :param verbosity: indicate the willingness of the user having the info displayed in detail
Sasa Zhang's avatar
Sasa Zhang committed
211
212
213
214
215
        :param case_folder: case name which is being tested
        :param test_code: code returned by the program after done running the case
        :param expected_value_json: predefined value inside 'config.jason' file
        :return: case running result
    """
Sasa Zhang's avatar
Sasa Zhang committed
216
217
    global num_of_success, num_of_failure, list_of_failure_cases
    global forecast_exists, station_exists, observation_exists, json_exists, reference_exists
Sasa Zhang's avatar
Sasa Zhang committed
218
219
220
221
222

    if (test_code == 0 and expected_value_json == 'SUCCESS' and XmlTree.sum_of_error_outside_tolerance == 0) \
            or (test_code != 0 and expected_value_json == 'FAILURE'):
        num_of_success += 1
        print(case_folder, ' SUCCESS!')
Sasa Zhang's avatar
Sasa Zhang committed
223
224
225
226
227
228
229
        if (not reference_exists or not json_exists) and verbosity:
            print()
            if not reference_exists:
                print("Note: 'roadcast_reference' file does not exist for {}".format(case_folder))
            if not json_exists:
                print("Note: 'config.json' file does not exist for {}".format(case_folder))

Sasa Zhang's avatar
Sasa Zhang committed
230
    elif (test_code != 0 and expected_value_json == 'SUCCESS') or (test_code == 0 and expected_value_json == 'FAILURE') \
231
232
233
            or (test_code == 0 and (expected_value_json == 'SUCCESS' or expected_value_json == '')
                and XmlTree.sum_of_error_outside_tolerance > 0) or \
            ((not forecast_exists or not station_exists or not observation_exists) and not json_exists):
Sasa Zhang's avatar
Sasa Zhang committed
234
235
        num_of_failure += 1
        list_of_failure_cases.append(case_folder)
236
        if verbosity:
237
            print('The exit code of METRo is: {}\n'.format(test_code))
Sasa Zhang's avatar
Sasa Zhang committed
238
        print(case_folder, ' FAILURE! ***')
Sasa Zhang's avatar
Sasa Zhang committed
239
240
241
242
243
244
245

        if (not reference_exists or not json_exists) and verbosity:
            print()
            if not reference_exists:
                print("Note: 'roadcast_reference' file does not exist for {}".format(case_folder))
            if not json_exists:
                print("Note: 'config.json' file does not exist for {}".format(case_folder))
Sasa Zhang's avatar
Sasa Zhang committed
246
247
248
249
250
251
252
253
254
255
    else:
        print('Something went wrong with this test run, please try to restart it again!')


def process_xml_file(current_case_path, case_folder, error_value, verbosity=False):
    """
        Compares the output XML file with the given benchmark XML file
        :param current_case_path: directory of the current case that is going to be compared
        :param case_folder: case number that is being compared
        :param error_value: defined error tolerance for the running case
256
        :param verbosity: boolean variable to indicate the willingness of display the comparison result in detail
Sasa Zhang's avatar
Sasa Zhang committed
257
258
259
260
261
        :return: comparison result
    """
    global dict_error
    global list_of_errors
    global error_difference
Sasa Zhang's avatar
Sasa Zhang committed
262
    global reference_exists
263

Sasa Zhang's avatar
Sasa Zhang committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    os.chdir(current_case_path)
    XmlTree.sum_of_error_within_tolerance = 0
    XmlTree.sum_of_error_outside_tolerance = 0
    comparator = XmlTree(error_value)
    if verbosity:
        XmlTree.display_info = True
    elif not verbosity:
        XmlTree.display_info = False

    try:
        tree1 = XmlTree.convert_string_to_tree('roadcast_reference.xml')
        tree2 = XmlTree.convert_string_to_tree('roadcast_test_suite_run.xml')

        dict_error = {}
        list_of_errors = []
        error_difference = 0.0

        if comparator.xml_compare(tree1, tree2, ['production-date'],
                                  XmlTree.display_info) and XmlTree.sum_of_error_outside_tolerance == 0:
Sasa Zhang's avatar
Sasa Zhang committed
283
            if reference_exists and verbosity:
Sasa Zhang's avatar
Sasa Zhang committed
284
285
286
287
288
                print('\nXML FILES COMPARISON RESULT: \t', end='')
                print('  {} differences within the predefined error tolerance.\n'.
                      format(XmlTree.sum_of_error_within_tolerance))
        elif XmlTree.sum_of_error_outside_tolerance != 0:
            XmlTree.list_of_diff_case.append(case_folder)
Sasa Zhang's avatar
Sasa Zhang committed
289
            if reference_exists and verbosity:
Sasa Zhang's avatar
Sasa Zhang committed
290
291
292
293
294
                print('\nXML FILES COMPARISON RESULT: ', end='')
                print('\t  {} differences within the predefined error tolerance.'
                      .format(str(XmlTree.sum_of_error_within_tolerance).rjust(4)))
                print('                             \t  {} differences outside the predefined error tolerance.\n'
                      .format(str(XmlTree.sum_of_error_outside_tolerance).rjust(4)))
295
296
297
298
299
300
301
302
303
304
305
                print('The largest error difference is:              {}\n'.format(round(error_difference, 2)))
                print('The largest error difference exists in:       ', end='')
                print('roadcast_reference.xml'
                      '         roadcast_test_suite.xml')
                print('                                              ----------------------'
                      '         -----------------------')
                for key, values in dict_error.items():
                    for value in values:
                        error_reference = '<' + key + '>' + str(value[0]) + '<' + key + '>'
                        error_test_suite_run = '<' + key + '>' + str(value[1]) + '<' + key + '>'
                        print('\t\t\t\t\t\t{}\t\t{}'.format(error_reference.ljust(20), error_test_suite_run.ljust(20)))
Sasa Zhang's avatar
Sasa Zhang committed
306
307
308
    except FileNotFoundError:
        pass

309

Sasa Zhang's avatar
Sasa Zhang committed
310
311
312
313
314
# ---------------------------------------Method: main()-----------------------------------------------------------------
def main():
    # ----------------------------------------Process user's input from command line------------------------------------
    case_name = ''
    default_error_tolerance = 0.01
Sasa Zhang's avatar
Sasa Zhang committed
315

Sasa Zhang's avatar
Sasa Zhang committed
316
    parser = argparse.ArgumentParser(description='run the test suite')
317
318
    parser.add_argument('-c', '--case', nargs='+', default=[], metavar='', help='add case number(s) to a case list')
    parser.add_argument('-s', '--skip', nargs='+', default=[], metavar='', help='add case number(s) to a do-not-run case list')
319
    parser.add_argument('-v', '--verbose', action='store_true', help='display the process in a complete detailed way')
Sasa Zhang's avatar
Sasa Zhang committed
320
321
322
    parser.add_argument('-e', '--error', type=float, help='specified value of error tolerance')
    parser.add_argument('--clean', action='store_true', help="clean up output XML file 'roadcast_test_suite_run.xml'")
    args = parser.parse_args()
Sasa Zhang's avatar
Sasa Zhang committed
323

324
325
326
327
328
    if args.verbose:
        verbosity = True
    else:
        verbosity = False

Sasa Zhang's avatar
Sasa Zhang committed
329
    if args.case or args.skip:
330
        if args.case and args.skip:
331
332
            print("'-c' and '-s' cannot be used at the same time. The METRo program will exit with code 2.")
            sys.exit(2)
Sasa Zhang's avatar
Sasa Zhang committed
333
        run_all_cases = False
334
    else:
Sasa Zhang's avatar
Sasa Zhang committed
335
336
        case_name = 'case'
        run_all_cases = True
337

Sasa Zhang's avatar
Sasa Zhang committed
338
339
340
341
342
    if args.error:
        error_value = args.error
    else:
        error_value = default_error_tolerance

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
    num_of_folders = 0
    list_of_folders = []
    list_of_wrong_folders = []
    test_suite_path = os.getcwd()
    num_of_clean_up = 0
    # -------------------------------------------Clean up the output XML file-------------------------------------------
    if args.clean:
        if args.case or args.skip or args.error:
            print("'--clean' can only be used individually. The METRo program will exit with code 0.")
            sys.exit(0)

        for folder in sorted(os.listdir(test_suite_path)):
            if folder.startswith('case'):
                try:
                    os.remove(test_suite_path + '/' + folder + '/roadcast_test_suite_run.xml')
                    num_of_clean_up += 1
                    if  verbosity:
                        if num_of_clean_up == 1:
                            print('File(s) that are successfully removed:')
                        print(test_suite_path + '/' + folder + '/roadcast_test_suite_run.xml')
                except FileNotFoundError as e:
                    continue
        if num_of_clean_up == 0:
            print('There is nothing needs to be cleaned up.')
        else:
            if not verbosity:
                print("Note: all 'roadcast_test_suite_run.xml' files are cleaned up.")
        sys.exit(0)

Sasa Zhang's avatar
Sasa Zhang committed
372
373
374
375
376
    # --------------------------------------------List of validated test cases------------------------------------------
    if verbosity:
        print('\n\n================================================================================')
        print('\n', '                         ', 'VALIDATED LIST OF TEST CASES: ')
        print('\n================================================================================')
Sasa Zhang's avatar
Sasa Zhang committed
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

    if args.case:
        case_list = process_case_name(args.case, case_list=None)
    else:
        case_list = []

    if args.skip:
        do_not_run_case_list = process_case_name(args.skip, case_list=None)
    else:
        do_not_run_case_list = []

    if do_not_run_case_list and not case_list:
        list_of_folders = []
        case_name = 'case'
        for folder in sorted(os.listdir(test_suite_path)):
            if folder.startswith(case_name):
                list_of_folders.append(folder)
        list_of_folders = list_of_folders

        for case in do_not_run_case_list:
            if list_of_folders:
                for folder in list_of_folders:
                    if case not in list_of_folders and case not in list_of_wrong_folders:
                        list_of_wrong_folders.append(case)
            else:
                if case not in list_of_wrong_folders:
                    list_of_wrong_folders.append(case)

        if list_of_wrong_folders:
            print('\nWarning: No case named by: {}. The program exits with code 0.\n'.
                  format(', '.join(list_of_wrong_folders)))
            sys.exit(0)

        case_list = sorted(list(set([folder for folder in sorted(os.listdir(test_suite_path)) if folder.startswith(case_name)])
                         - set(do_not_run_case_list)))

Sasa Zhang's avatar
Sasa Zhang committed
413
    if run_all_cases:
Sasa Zhang's avatar
Sasa Zhang committed
414
        list_of_folders = []
Sasa Zhang's avatar
Sasa Zhang committed
415
416
417
418
419
420
421
422
423
        for folder in sorted(os.listdir(test_suite_path)):
            try:
                if folder.startswith(case_name):
                    list_of_folders.append(folder)
                    num_of_folders += 1
                    if verbosity:
                        print(folder)
            except TypeError:
                break
Sasa Zhang's avatar
Sasa Zhang committed
424
425
426

    if not run_all_cases:
        list_of_folders = []
Sasa Zhang's avatar
Sasa Zhang committed
427
428
429
430
431
432
433
434
        for case in case_list:
            for folder in os.listdir(test_suite_path):
                if case == folder:
                    list_of_folders.append(case)
                    num_of_folders += 1
                    if verbosity:
                        print(case)

Sasa Zhang's avatar
Sasa Zhang committed
435
    if (sorted(list_of_folders) != sorted(case_list)) and not run_all_cases and not do_not_run_case_list:
Sasa Zhang's avatar
Sasa Zhang committed
436
        for case in case_list:
Sasa Zhang's avatar
Sasa Zhang committed
437
438
439
440
441
442
            if list_of_folders:
                for folder in list_of_folders:
                    if case not in list_of_folders and case not in list_of_wrong_folders:
                        list_of_wrong_folders.append(case)
            else:
                if case not in list_of_wrong_folders:
Sasa Zhang's avatar
Sasa Zhang committed
443
                    list_of_wrong_folders.append(case)
Sasa Zhang's avatar
Sasa Zhang committed
444

Sasa Zhang's avatar
Sasa Zhang committed
445
446
        print('\nWarning: No case named by: {}. The program exits with code 0.\n'.
              format(', '.join(list_of_wrong_folders)))
447
        sys.exit(0)
Sasa Zhang's avatar
Sasa Zhang committed
448
449

    # -------------------------------------------------Test running process--------------------------------------------
Sasa Zhang's avatar
Sasa Zhang committed
450
451
    global forecast_exists, station_exists, observation_exists, json_exists, reference_exists
    global num_of_failure, list_of_failure_cases, list_of_missing_file_cases
Sasa Zhang's avatar
Sasa Zhang committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    file_forecast_path = ''
    file_station_path = ''
    file_observation_path = ''
    extra_parameter = ''
    expected_value = 'SUCCESS'
    arrow_line = '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
    ripple_line = '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'

    if verbosity:
        print('\n\n\n================================================================================')
        print('\n', '                            ', 'TESTING PROCESS: ')
        print('\n================================================================================')
    for folder in list_of_folders:
        current_case_path = './' + str(folder)
        for (dir_path, dir_names, file_names) in os.walk(current_case_path):  # Walk into each case.
Sasa Zhang's avatar
Sasa Zhang committed
467
468
469
470
471
            forecast_exists = False
            station_exists = False
            observation_exists = False
            json_exists = False
            reference_exists = False
Sasa Zhang's avatar
Sasa Zhang committed
472
473
            for file_name in file_names:
                extra_parameter = ''  # Set a default value for extra_parameter as not all cases need it.
Sasa Zhang's avatar
Sasa Zhang committed
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
                forecast_exists = os.path.isfile(current_case_path + '/forecast.xml')
                station_exists = os.path.isfile(current_case_path + '/station.xml')
                observation_exists = os.path.isfile(current_case_path + '/observation.xml')
                json_exists = os.path.isfile(current_case_path + '/config.json')
                reference_exists = os.path.isfile(current_case_path + '/roadcast_reference.xml')

            if forecast_exists:
                file_forecast_path = os.path.join(test_suite_path + dir_path[1:], 'forecast.xml')
            if station_exists:
                file_station_path = os.path.join(test_suite_path + dir_path[1:], 'station.xml')
            if observation_exists:
                file_observation_path = os.path.join(test_suite_path + dir_path[1:], 'observation.xml')
            if json_exists:
                os.chdir(current_case_path)  # Change the current path to the current case directory.
                with open('config.json') as f:
                    data = json.load(f)
                    for key, value in data.items():
                        if key == 'addition_to_command_line':
                            if value is not None:
                                extra_parameter = value
                        if key == 'expected_running_result':
                            if value == 'FAILURE':
                                expected_value = 'FAILURE'
                            elif value == 'SUCCESS':
                                expected_value = 'SUCCESS'
                            else:
                                print('Please verify the format/syntax of the config.json file.')
                        if key == 'error_tolerance':
                            error_value = value

            if forecast_exists and station_exists and observation_exists:
                file_output_path = os.path.join(test_suite_path + dir_path[1:], 'roadcast_test_suite_run.xml')
                os.chdir(test_suite_path)  # Change back the path so as to make the function call.
Sasa Zhang's avatar
Sasa Zhang committed
507

Sasa Zhang's avatar
Sasa Zhang committed
508
                command_to_run = 'python3 ../../../../bin/metro {} --input-forecast {} --input-station {} ' \
Sasa Zhang's avatar
Sasa Zhang committed
509
510
511
512
513
514
                                 '--input-observation {} --output-roadcast {}'.format(extra_parameter,
                                                                                      file_forecast_path,
                                                                                      file_station_path,
                                                                                      file_observation_path,
                                                                                      file_output_path)

Sasa Zhang's avatar
Sasa Zhang committed
515
516
517
518
519
520
521
522
523
524
525
                if verbosity:
                    try:
                        print('\n>>>>>>>>>>>>>>>>>>>>>>>> {} starts to run...... <<<<<<<<<<<<<<<<<<<<<<<<<<'
                              '<'.format(folder))
                        if expected_value == 'FAILURE':
                            print('>>>>>>>>>>>>>>>>>>>>>>>> {} is expected to FAIL...... <<<<<<<<<<<<<<<<<<'
                                  '<<<'.format(folder))

                        print('\nSyntax to run {}:'.format(folder))
                        print('--------------------------------------------------------------------------------')
                        print(
Sasa Zhang's avatar
Sasa Zhang committed
526
                            'python3 ../../../../bin/metro {0} --input-forecast ../test_suite'
Sasa Zhang's avatar
Sasa Zhang committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
                            '/{1}/forecast.xml --input-station ../test_suite/{1}/station.xml --input'
                            '-observation ../test_suite/{1}/observation.xml --output-roadcast '
                            '../test_suite/{1}/roadcast_individual_run.xml\n'.format(extra_parameter, folder))
                        print('--------------------------------------------------------------------------------')

                        print('\n\n')
                        test_run = subprocess.run(command_to_run, shell=True, check=True)
                        print('\n\n{}'.format(arrow_line))
                        if reference_exists:
                            print('\nError Tolerance:                  {}'.format(error_value))
                        process_xml_file(current_case_path, folder, error_value, verbosity=True)
                        if not reference_exists:
                            print('No reference XML file to do the comparison.\n')
                        process_test_result(folder, test_run.returncode, expected_value, verbosity=True)
                    except subprocess.CalledProcessError:
                        print('\n\n{}'.format(arrow_line))
                        if not reference_exists:
                            print('No reference XML file to do the comparison.')
                        print('No generated XML file to do the comparison.\n')
                        process_test_result(folder, 1, expected_value, verbosity=True)
                        print('\n{}\n\n'.format(arrow_line))
                        continue
                    os.chdir(test_suite_path)
Sasa Zhang's avatar
Sasa Zhang committed
550
551
                    print('\n{}\n\n'.format(arrow_line))

Sasa Zhang's avatar
Sasa Zhang committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                elif not verbosity:
                    test_run = subprocess.run(command_to_run, shell=True, stdout=subprocess.DEVNULL,
                                              stderr=subprocess.STDOUT)
                    process_xml_file(current_case_path, folder, error_value, verbosity=False)
                    process_test_result(folder, test_run.returncode, expected_value, verbosity=False)
                    os.chdir(test_suite_path)

            elif not forecast_exists or not station_exists or not observation_exists:
                if verbosity:
                    print('\n>>>>>>>>>>>>>>>>>>>>>>>> {} cannot be started...... <<<<<<<<<<<<<<<<<<<<<<'.format(folder))
                    print('\n{} has missing input file(s): '.format(folder))
                    if not forecast_exists:
                        print("\t\t\t\t\t'forecast.xml'")
                    if not station_exists:
                        print("\t\t\t\t\t'station.xml'")
                    if not observation_exists:
                        print("\t\t\t\t\t'observation.xml'")
                num_of_failure += 1
                list_of_missing_file_cases.append(folder)
                print(folder, ' FAILURE! ***')
                if verbosity:
                    print('\n{}\n\n'.format(arrow_line))
Sasa Zhang's avatar
Sasa Zhang committed
574
                os.chdir(test_suite_path)
Sasa Zhang's avatar
Sasa Zhang committed
575

Sasa Zhang's avatar
Sasa Zhang committed
576
577
    # ----------------------------------------------Summary after test running------------------------------------------
    print('\n\n\n================================================================================')
Sasa Zhang's avatar
Sasa Zhang committed
578
    print('\n', '                                  ', 'SUMMARY: ')
Sasa Zhang's avatar
Sasa Zhang committed
579
580
581
582
    print('\n================================================================================')
    print('Total number of test cases ran:\t\t\t\t', str(num_of_folders), '.\nNumber of cases ran with SUCCESS:\t\t\t',
          str(num_of_success), '.\nNumber of cases  ran with FAILURE: \t\t\t', str(num_of_failure), '.')

Sasa Zhang's avatar
Sasa Zhang committed
583
584
585
586
    if len(list_of_missing_file_cases) != 0:
        print('Case(s) missing proper input file(s):\t\t\t', end=' ')
        print(*list_of_missing_file_cases, sep=', ')

Sasa Zhang's avatar
Sasa Zhang committed
587
    if len(XmlTree.list_of_diff_case) != 0:
Sasa Zhang's avatar
Sasa Zhang committed
588
        print('Case(s) having different XML file comparison result:\t', end=' ')
Sasa Zhang's avatar
Sasa Zhang committed
589
590
591
592
593
        print(*XmlTree.list_of_diff_case, sep=', ')
    print('\n\n\n')

    if (len(list_of_failure_cases) != 0) and verbosity:
        print('\n\n\n================================================================================')
Sasa Zhang's avatar
Sasa Zhang committed
594
        print('\n', '                           ', 'FAILED RUNNING CASE(S): ')
Sasa Zhang's avatar
Sasa Zhang committed
595
596
597
598
        print('\n================================================================================')
        for case in list_of_failure_cases:
            print(case)
            print(ripple_line)
Sasa Zhang's avatar
Sasa Zhang committed
599
600
            print('Syntax to run this individual case with more details:')
            print('-----------------------------------------------------')
Sasa Zhang's avatar
Sasa Zhang committed
601
            print('python3 ../../../../bin/metro {0} --verbose-level 4 --input-forecast ../test_suite'
Sasa Zhang's avatar
Sasa Zhang committed
602
603
                  '/{1}/forecast.xml --input-station ../test_suite/{1}/station.xml --input'
                  '-observation ../test_suite/{1}/observation.xml --output-roadcast '
Sasa Zhang's avatar
Sasa Zhang committed
604
                  '../test_suite/{1}/roadcast_individual_run.xml\n'.format(extra_parameter, case))
Sasa Zhang's avatar
Sasa Zhang committed
605
606
607
608


if __name__ == '__main__':
    main()
609
    sys.exit(num_of_failure)