parser.py 23 KB
Newer Older
1
#!/usr/bin/env python3
2
3
#SCT log parser

4

5
import sys
Vincent Stehlé's avatar
Vincent Stehlé committed
6
import argparse
Vincent Stehlé's avatar
Vincent Stehlé committed
7
import csv
Vincent Stehlé's avatar
Vincent Stehlé committed
8
import logging
Vincent Stehlé's avatar
Vincent Stehlé committed
9
import json
10
import re
11
12
13
14
15

try:
    from packaging import version
except ImportError:
    print('No packaging...')
Vincent Stehlé's avatar
Vincent Stehlé committed
16

Vincent Stehlé's avatar
Vincent Stehlé committed
17
18
19
20
21
try:
    import yaml
except ImportError:
    print('No yaml...')

22
23
24
25
26
27
if 'yaml' in sys.modules:
    try:
        from yaml import CDumper as Dumper
    except ImportError:
        from yaml import Dumper

Vincent Stehlé's avatar
Vincent Stehlé committed
28
# Not all yaml versions have a Loader argument.
29
30
if 'packaging.version' in sys.modules and \
   version.parse(yaml.__version__) >= version.parse('5.1'):
Vincent Stehlé's avatar
Vincent Stehlé committed
31
32
33
34
    yaml_load_args = {'Loader': yaml.FullLoader}
else:
    yaml_load_args = {}

35

36
#based loosley on https://stackoverflow.com/a/4391978
Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
37
# returns a filtered dict of dicts that meet some Key-value pair.
38
# I.E. key="result" value="FAILURE"
39
def key_value_find(list_1, key, value):
40
    found = list()
41
    for test in list_1:
42
        if test[key] == value:
43
            found.append(test)
44
    return found
45

46
47

#Were we intrept test logs into test dicts
48
def test_parser(string, current):
49
    test_list = {
Vincent Stehlé's avatar
Vincent Stehlé committed
50
      "name": string[2], #FIXME:Sometimes, SCT has name and Description,
51
      "result": string[1],
52
      **current,
53
      "guid": string[0], #FIXME:GUID's overlap
Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
54
      #"comment": string[-1], #FIXME:need to hash this out, sometime there is no comments
55
      "log": ' '.join(string[3:])
56
    }
57
    return test_list
Vincent Stehlé's avatar
Vincent Stehlé committed
58

59
#Parse the ekl file, and create a map of the tests
60
61
def ekl_parser (file):
    #create our "database" dict
62
    temp_list = list()
63
64
65
66
67
68
69
70
    # All tests are grouped by the "HEAD" line, which precedes them.
    current = {}

    # Count number of tests since beginning of the set
    n = 0

    # Number of skipped tests sets
    s = 0
71

72
    for i, line in enumerate(file):
Vincent Stehlé's avatar
Vincent Stehlé committed
73
74
75
76
77
78
79
        # Strip the line from trailing whitespaces
        line = line.rstrip()

        # Skip empty line
        if line == '':
            continue

80
81
        # strip the line of | & || used for sepration
        split_line = line.split('|')
82

83
84
85
86
        # TERM marks the end of a test set
        # In case of empty test set we generate an artificial skipped test
        # entry. Then reset current as a precaution, as well as our test
        # counter.
87
        if split_line[0] == '' and split_line[1] == "TERM":
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
            if not n:
                logging.debug(f"Skipped test set `{current['sub set']}'")

                temp_list.append({
                    **current,
                    'name': '',
                    'guid': '',
                    'log': '',
                    'result': 'SKIPPED',
                })

                s += 1

            current = {}
            n = 0
103
104
            continue

105
106
107
        # The "HEAD" tag is the only indcation we are on a new test set
        if split_line[0] == '' and split_line[1] == "HEAD":
            # split the header into test group and test set.
108
            try:
109
110
111
                group, Set = split_line[12].split('\\')
            except Exception:
                group, Set = '', split_line[12]
112
113
114
            current = {
                'group': group,
                'test set': Set,
115
116
117
118
119
120
121
122
                'sub set': split_line[10],
                'set guid': split_line[8],
                'iteration': split_line[4],
                'start date': split_line[6],
                'start time': split_line[7],
                'revision': split_line[9],
                'descr': split_line[11],
                'device path': '|'.join(split_line[13:]),
123
            }
124

Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
125
        #FIXME:? EKL file has an inconsistent line structure,
126
127
        # sometime we see a line that consits ' dump of GOP->I\n'
        #easiest way to skip is check for blank space in the first char
128
        elif split_line[0] != '' and split_line[0][0] != " ":
129
130
131
132
            try:
                #deliminiate on ':' for tests
                split_test = [new_string for old_string in split_line for new_string in old_string.split(':')]
                #put the test into a dict, and then place that dict in another dict with GUID as key
133
                tmp_dict = test_parser(split_test, current)
134
                temp_list.append(tmp_dict)
135
                n += 1
136
137
            except Exception:
                print(f"Line {i+1}:", split_line)
138
                sys.exit("your log may be corrupted")
139
140
141
        else:
            logging.error(f"Unparsed line {i} `{line}'")

142
143
144
    if s:
        logging.debug(f'{s} skipped test set(s)')

145
    return temp_list
146

Jeff Booher-Kaeding's avatar
Jeff Booher-Kaeding committed
147
#Parse Seq file, used to tell which tests should run.
148
def seq_parser(file):
149
    temp_dict = list()
150
    lines=file.readlines()
Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
151
    magic=7 #a test in a seq file is 7 lines, if not mod7, something wrong..
152
153
    if len(lines)%magic != 0:
        sys.exit("seqfile cut short, should be mod7")
154
155
156
157
158
159
160
161
    #the utf-16 char makes this looping a bit harder, so we use x+(i) where i is next 0-6th
    for x in range(0,len(lines),magic): #loop ever "7 lines"
        #(x+0)[Test Case]
        #(x+1)Revision=0x10000
        #(x+2)Guid=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
        #(x+3)Name=InstallAcpiTableFunction
        #(x+4)Order=0xFFFFFFFF
        #(x+5)Iterations=0xFFFFFFFF
Vincent Stehlé's avatar
Vincent Stehlé committed
162
        #(x+6)(utf-16 char)
163
        #currently only add tests that are supposed to run, should add all?
Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
164
        #0xFFFFFFFF in "Iterations" means the test is NOT supposed to run
165
166
167
168
169
170
171
172
        if not "0xFFFFFFFF" in lines[x+5]:
            seq_dict = {
                "name": lines[x+3][5:-1],#from after "Name=" to end (5char long)
                "guid": lines[x+2][5:-1],#from after"Guid=" to the end, (5char long)
                "Iteration": lines[x+5][11:-1],#from after "Iterations=" (11char long)
                "rev": lines[x+1][9:-1],#from after "Revision=" (9char long)
                "Order": lines[x+4][6:-1]#from after "Order=" (6char long)
            }
173
            temp_dict.append(seq_dict) #put in a dict based on guid
174

175
    return temp_dict
176

177
178
179
180
#group items by key, and print by key
#we slowly iterate through the list, group and print groups
def key_tree_2_md(input_list,file,key):
    #make a copy so we don't destroy the first list.
Vincent Stehlé's avatar
Vincent Stehlé committed
181
    temp_list = input_list.copy()
182
183
184
185
186
187
188
189
190
191
192
193
    while temp_list:
        test_dict = temp_list.pop()
        found, not_found = [test_dict],[]
        #go through whole list looking for key match
        while temp_list:
            next_dict = temp_list.pop()
            if next_dict[key] == test_dict[key]: #if match add to found
                found.append(next_dict)
            else: #else not found
                not_found.append(next_dict)
        temp_list = not_found #start over with found items removed
        file.write("### " + test_dict[key])
194
        dict_2_md(found,file)
Vincent Stehlé's avatar
Vincent Stehlé committed
195

196
197


198
199
200
#generic writer, takes a list of dicts and turns the dicts into an MD table.
def dict_2_md(input_list,file):
    if len(input_list) > 0:
Jeff Booher-Kaeding's avatar
Jeff Booher-Kaeding committed
201
        file.write("\n\n")
202
203
204
205
        #create header for MD table using dict keys
        temp_string1, temp_string2 = "|", "|"
        for x in (input_list[0].keys()):
            temp_string1 += (x + "|")
Jeff Booher-Kaeding's avatar
Jeff Booher-Kaeding committed
206
            temp_string2 += ("---|")
207
208
209
210
211
212
213
        file.write(temp_string1+"\n"+temp_string2+"\n")
        #print each item from the dict into the table
        for x in input_list:
            test_string = "|"
            for y in x.keys():
                test_string += (x[y] + "|")
            file.write(test_string+'\n')
Vincent Stehlé's avatar
Vincent Stehlé committed
214
    #seprate table from other items in MD
215
    file.write("\n\n")
216

Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
217

Vincent Stehlé's avatar
Vincent Stehlé committed
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
# Sanitize our YAML configuration
# We modify conf in-place
# TODO: use a proper validator instead
def sanitize_yaml(conf):
    rules = set()

    for i in range(len(conf)):
        r = conf[i]

        # Generate a rule name if needed
        if 'rule' not in r:
            r['rule'] = f'r{i}'
            logging.debug(f"Auto-naming rule {i} `{r['rule']}'")
            conf[i] = r

        if r['rule'] in rules:
            logging.warning(f"Duplicate rule {i} `{r['rule']}'")

        rules.add(r['rule'])

        if 'criteria' not in r or not type(r['criteria']) is dict or \
           'update' not in r or not type(r['update']) is dict:
            logging.error(f"Bad rule {i} `{r}'")
            raise Exception()


# Evaluate if a test dict matches a criteria
# The criteria is a dict of Key-value pairs.
# I.E. crit = {"result": "FAILURE", "xxx": "yyy", ...}
# All key-value pairs must be present and match for a test dict to match.
# A test value and a criteria value match if the criteria value string is
# present anywhere in the test value string.
# For example, the test value "abcde" matches the criteria value "cd".
# This allows for more "relaxed" criteria than strict comparison.
def matches_crit(test, crit):
    for key, value in crit.items():
        if key not in test or test[key].find(value) < 0:
            return False

    return True


# Apply all configuration rules to the tests
# We modify cross_check in-place
def apply_rules(cross_check, conf):
    # Prepare statistics counters
    stats = {}

    for r in conf:
        stats[r['rule']] = 0

    # Apply rules on each test data
    s = len(cross_check)

    for i in range(s):
        test = cross_check[i]

        for r in conf:
            if not matches_crit(test, r['criteria']):
                continue

            rule = r['rule']

            logging.debug(
                f"Applying rule `{rule}'"
                f" to test {i} `{test['name']}'")

            test.update({
                **r['update'],
                'Updated by': rule,
            })

            stats[rule] += 1
            break

    # Statistics
    n = 0

    for rule, cnt in stats.items():
        logging.debug(f"{cnt} matche(s) for rule `{rule}'")
        n += cnt

    if n:
        r = len(conf)
        logging.info(
            f'Updated {n} test(s) out of {s} after applying {r} rule(s)')


# Use YAML configuration file and perform all the transformations described in
# there.
# See the README.md for details on the file format.
# We modify cross_check in-place
def use_config(cross_check, filename):
    assert('yaml' in sys.modules)

    # Load configuration file
    logging.debug(f'Read {filename}')

    with open(filename, 'r') as yamlfile:
Vincent Stehlé's avatar
Vincent Stehlé committed
317
        conf = yaml.load(yamlfile, **yaml_load_args)
Vincent Stehlé's avatar
Vincent Stehlé committed
318
319
320
321
322

    logging.debug('{} rule(s)'.format(len(conf)))
    sanitize_yaml(conf)
    apply_rules(cross_check, conf)

323
324
325
326
327
328
329

# Filter tests data
# Filter is a python expression, which is evaluated for each test
# When the expression evaluates to True, the test is kept
# Otherwise it is dropped
def filter_data(cross_check, Filter):
    logging.debug(f"Filtering with `{Filter}'")
330
    before = len(cross_check)
331
332
333
334
335

    # This function "wraps" the filter and is called for each test
    def function(x):
        return eval(Filter)

336
337
338
339
    r = list(filter(function, cross_check))
    after = len(r)
    logging.info(f"Filtered out {before - after} test(s), kept {after}")
    return r
340
341


Vincent Stehlé's avatar
Vincent Stehlé committed
342
343
344
345
346
347
348
349
350
351
# Sort tests data in-place
# sort_keys is a comma-separated list
# The first key has precedence, then the second, etc.
# To use python list in-place sorting, we use the keys in reverse order.
def sort_data(cross_check, sort_keys):
    logging.debug(f"Sorting on `{sort_keys}'")
    for k in reversed(sort_keys.split(',')):
        cross_check.sort(key=lambda x: x[k])


352
353
354
355
356
# Keep only certain fields in data, in-place
# The fields to write are supplied as a comma-separated list
def keep_fields(cross_check, fields):
    logging.debug(f"Keeping fields: `{fields}'")
    s = set(fields.split(','))
Vincent Stehlé's avatar
Vincent Stehlé committed
357
358

    for x in cross_check:
359
360
361
362
363
        for k in list(x.keys()):
            if k not in s:
                del x[k]


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
# Do a "uniq" pass on the data
# All duplicate entries are collapsed into a single one
# We add a "count" field
def uniq(cross_check):
    logging.debug("Collapsing duplicates")

    # First pass to count all occurences
    h = {}

    for x in cross_check:
        i = ''

        for k in sorted(x.keys()):
            i += f"{k}:{x[k]} "

        if i not in h:
            h[i] = {
                'count': 0,
                **x,
            }

        h[i]['count'] += 1

    # Transform back to list
    r = list(h.values())
    logging.info(f"{len(r)} unique entries")
    return r


393
394
395
396
397
398
399
400
401
402
403
404
# Discover fields
# The fields can be supplied as a comma-separated list
# Order is preserved
# Additional fields are auto-discovered and added to the list, sorted
def discover_fields(cross_check, fields=None):
    if fields is not None:
        keys = fields.split(',')
    else:
        keys = []

    # Find keys, not already listed
    s = set()
Vincent Stehlé's avatar
Vincent Stehlé committed
405

406
407
408
409
410
411
412
413
414
415
416
417
418
419
    for x in cross_check:
        s = s.union(x.keys())

    s = s.difference(keys)
    keys += sorted(s)

    logging.debug(f'Fields: {keys}')
    return keys


# Generate csv
# The fields to write are supplied as a list
def gen_csv(cross_check, filename, fields):
    logging.debug(f'Generate {filename} (fields: {fields})')
Vincent Stehlé's avatar
Vincent Stehlé committed
420

Vincent Stehlé's avatar
Vincent Stehlé committed
421
422
    with open(filename, 'w', newline='') as csvfile:
        writer = csv.DictWriter(
423
            csvfile, fieldnames=fields, delimiter=';')
Vincent Stehlé's avatar
Vincent Stehlé committed
424
425
426
427
        writer.writeheader()
        writer.writerows(cross_check)


Vincent Stehlé's avatar
Vincent Stehlé committed
428
429
430
431
432
433
434
435
# Generate json
def gen_json(cross_check, filename):
    logging.debug(f'Generate {filename}')

    with open(filename, 'w') as jsonfile:
        json.dump(cross_check, jsonfile, sort_keys=True, indent=2)


436
437
438
439
440
441
# Generate yaml
def gen_yaml(cross_check, filename):
    assert('yaml' in sys.modules)
    logging.debug(f'Generate {filename}')

    with open(filename, 'w') as yamlfile:
442
        yaml.dump(cross_check, yamlfile, Dumper=Dumper)
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
# Generate yaml config template
# This is to help writing yaml config.
# We omit tests with result PASS.
# We omit some tests keys: iteration and dates.
# We remove the leading directory from C filename in log.
def gen_template(cross_check, filename):
    assert('yaml' in sys.modules)
    logging.debug(f'Generate {filename}')
    omitted_keys = set(['iteration', 'start date', 'start time'])
    t = []
    i = 1

    for x in cross_check:
        if x['result'] == 'PASS':
            continue

        r = {
            'rule': f'Generated rule ({i})',
            'criteria': {},
            'update': {'result': 'TEMPLATE'},
        }

        for key, value in x.items():
            if key in omitted_keys:
                continue

            if key == 'log':
                value = re.sub(r'^/.*/', '', value)

            r['criteria'][key] = value

        t.append(r)
        i += 1

    with open(filename, 'w') as yamlfile:
        yaml.dump(t, yamlfile, Dumper=Dumper)


483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# Print to stdout
# The fields to write are supplied as a list
def do_print(cross_check, fields):
    logging.debug(f'Print (fields: {fields})')

    # First pass to find the width for each field except the last one
    fm1 = fields[:len(fields) - 1]
    w = {}

    for f in fm1:
        w[f] = len(f)

    for x in cross_check:
        for f in fm1:
            w[f] = max(w[f], len(str(x[f])))

    # Second pass where we print
500
501
    lf = fields[len(fields) - 1]

502
503
    print(' '.join([
        *map(lambda f: f"{f:{w[f]}}", fm1),
504
        lf]))
505
506
507

    for x in cross_check:
        print(' '.join([
508
509
            *map(lambda f: f"{x[f]:{w[f] if f in x else ''}}", fm1),
            x[lf] if lf in x else '']))
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
# Combine or two databases db1 and db2 coming from ekl and seq files
# respectively into a single cross_check database
# Tests in db1, which were not meant to be run according to db2 have their
# results forced to SPURIOUS.
# Tests sets in db2, which were not run according to db1 have an artificial
# test entry created with result DROPPED.
def combine_dbs(db1, db2):
    cross_check = db1

    # Do a pass to verify that all tests in db1 were meant to be run.
    # Otherwise, force the result to SPURIOUS.
    s = set()

    for x in db2:
        s.add(x['guid'])

    n = 0

    for i in range(len(cross_check)):
        if cross_check[i]['set guid'] not in s:
            logging.debug(f"Spurious test {i} `{cross_check[i]['name']}'")
            cross_check[i]['result'] = 'SPURIOUS'
            n += 1

    if n:
        logging.debug(f'{n} spurious test(s)')

    # Do a pass to autodetect all tests fields in case we need to merge dropped
    # tests sets entries
    f = {}

    for x in cross_check:
        for k in x.keys():
            f[k] = ''

    logging.debug(f'Test fields: {f.keys()}')

    # Do a pass to find the test sets that did not run for whatever reason.
    s = set()

    for x in cross_check:
        s.add(x['set guid'])

    n = 0

    for i in range(len(db2)):
        x = db2[i]

        if not x['guid'] in s:
            logging.debug(f"Dropped test set {i} `{x['name']}'")

            # Create an artificial test entry to reflect the dropped test set
            cross_check.append({
                **f,
                'sub set': x['name'],
                'set guid': x['guid'],
                'revision': x['rev'],
                'group': 'Unknown',
                'result': 'DROPPED',
            })

            n += 1

    if n:
        logging.debug(f'{n} dropped test set(s)')

    return cross_check


581
def main():
Vincent Stehlé's avatar
Vincent Stehlé committed
582
583
584
585
    parser = argparse.ArgumentParser(
        description='Process SCT results.'
                    ' This program takes the SCT summary and sequence files,'
                    ' and generates a nice report in mardown format.',
Vincent Stehlé's avatar
Vincent Stehlé committed
586
587
588
589
590
        epilog='When sorting is requested, tests data are sorted'
               ' according to the first sort key, then the second, etc.'
               ' Sorting happens after update by the configuration rules.'
               ' Useful example: --sort'
               ' "group,descr,set guid,test set,sub set,guid,name,log"',
Vincent Stehlé's avatar
Vincent Stehlé committed
591
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
Vincent Stehlé's avatar
Vincent Stehlé committed
592
    parser.add_argument('--csv', help='Output .csv filename')
Vincent Stehlé's avatar
Vincent Stehlé committed
593
    parser.add_argument('--json', help='Output .json filename')
Vincent Stehlé's avatar
Vincent Stehlé committed
594
595
    parser.add_argument(
        '--md', help='Output .md filename', default='result.md')
Vincent Stehlé's avatar
Vincent Stehlé committed
596
597
    parser.add_argument(
        '--debug', action='store_true', help='Turn on debug messages')
Vincent Stehlé's avatar
Vincent Stehlé committed
598
599
    parser.add_argument(
        '--sort', help='Comma-separated list of keys to sort output on')
600
    parser.add_argument('--filter', help='Python expression to filter results')
601
602
    parser.add_argument(
        '--fields', help='Comma-separated list of fields to write')
603
604
    parser.add_argument(
        '--uniq', action='store_true', help='Collapse duplicates')
605
606
    parser.add_argument(
        '--print', action='store_true', help='Print results to stdout')
Vincent Stehlé's avatar
Vincent Stehlé committed
607
608
609
610
611
612
613
614
    parser.add_argument(
        'log_file', nargs='?', default='sample.ekl',
        help='Input .ekl filename')
    parser.add_argument(
        'seq_file', nargs='?', default='sample.seq',
        help='Input .seq filename')
    parser.add_argument('find_key', nargs='?', help='Search key')
    parser.add_argument('find_value', nargs='?', help='Search value')
Vincent Stehlé's avatar
Vincent Stehlé committed
615
616
617
618
619
620

    # A few command line switches depend on yaml. We enable those only if we
    # could actually import yaml.
    if 'yaml' in sys.modules:
        parser.add_argument(
            '--config', help='Input .yaml configuration filename')
621
        parser.add_argument('--yaml', help='Output .yaml filename')
622
623
        parser.add_argument(
            '--template', help='Output .yaml config template filename')
Vincent Stehlé's avatar
Vincent Stehlé committed
624

Vincent Stehlé's avatar
Vincent Stehlé committed
625
626
    args = parser.parse_args()

Vincent Stehlé's avatar
Vincent Stehlé committed
627
628
629
630
    logging.basicConfig(
        format='%(levelname)s %(funcName)s: %(message)s',
        level=logging.DEBUG if args.debug else logging.INFO)

Vincent Stehlé's avatar
Vincent Stehlé committed
631
    #Command line argument 1, ekl file to open
632
    db1 = list() #"database 1" all tests.
Vincent Stehlé's avatar
Vincent Stehlé committed
633
634
    logging.debug(f'Read {args.log_file}')

Vincent Stehlé's avatar
Vincent Stehlé committed
635
    with open(args.log_file,"r",encoding="utf-16") as f: #files are encoded in utf-16
Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
636
637
        db1 = ekl_parser(f.readlines())

Vincent Stehlé's avatar
Vincent Stehlé committed
638
639
    logging.debug('{} test(s)'.format(len(db1)))

Vincent Stehlé's avatar
Vincent Stehlé committed
640
    #Command line argument 2, seq file to open
641
    db2 = dict() #"database 2" all test sets that should run
Vincent Stehlé's avatar
Vincent Stehlé committed
642
643
    logging.debug(f'Read {args.seq_file}')

Vincent Stehlé's avatar
Vincent Stehlé committed
644
    with open(args.seq_file,"r",encoding="utf-16") as f: #files are encoded in utf-16
645
        db2 = seq_parser(f)
Vincent Stehlé's avatar
Vincent Stehlé committed
646

Vincent Stehlé's avatar
Vincent Stehlé committed
647
648
    logging.debug('{} test set(s)'.format(len(db2)))

649
650
    # Produce a single cross_check database from our two db1 and db2 databases.
    cross_check = combine_dbs(db1, db2)
651

Vincent Stehlé's avatar
Vincent Stehlé committed
652
653
654
655
    # Take configuration file into account. This can perform transformations on
    # the tests results.
    if 'config' in args and args.config is not None:
        use_config(cross_check, args.config)
Vincent Stehlé's avatar
Vincent Stehlé committed
656

657
658
659
660
    # Filter tests data, if requested
    if args.filter is not None:
        cross_check = filter_data(cross_check, args.filter)

Vincent Stehlé's avatar
Vincent Stehlé committed
661
662
663
664
    # Sort tests data in-place, if requested
    if args.sort is not None:
        sort_data(cross_check, args.sort)

665
666
667
    # search for failures, warnings, passes & others
    # We detect all present keys in additions to the expected ones. This is
    # handy with config rules overriding the result field with arbitrary values.
668
    res_keys = set(['DROPPED', 'FAILURE', 'WARNING', 'PASS'])
Vincent Stehlé's avatar
Vincent Stehlé committed
669

670
671
672
673
674
675
676
677
678
679
    for x in cross_check:
        res_keys.add(x['result'])

    # Now we fill some bins with tests according to their result
    bins = {}

    for k in res_keys:
        bins[k] = key_value_find(cross_check, "result", k)

    # Print a one-line summary
680
    s = map(
681
682
683
684
        lambda k: '{} {}(s)'.format(len(bins[k]), k.lower()),
        sorted(res_keys))

    logging.info(', '.join(s))
685
686

    # generate MD summary
Vincent Stehlé's avatar
Vincent Stehlé committed
687
688
    logging.debug(f'Generate {args.md}')

Vincent Stehlé's avatar
Vincent Stehlé committed
689
    with open(args.md, 'w') as resultfile:
690
691
692
        resultfile.write("# SCT Summary \n\n")
        resultfile.write("|  |  |\n")
        resultfile.write("|--|--|\n")
693
694
695
696
697
698

        # Loop on all the result values we found for the summary
        for k in sorted(res_keys):
            resultfile.write(
                "|{}:|{}|\n".format(k.title(), len(bins[k])))

699
700
        resultfile.write("\n\n")

701
702
        # Loop on all the result values we found (except PASS) for the sections
        # listing the tests by group
703
        n = 1
704
705
        res_keys_np = set(res_keys)
        res_keys_np.remove('PASS')
Vincent Stehlé's avatar
Vincent Stehlé committed
706

707
708
709
710
        for k in sorted(res_keys_np):
            resultfile.write("## {}. {} by group\n\n".format(n, k.title()))
            key_tree_2_md(bins[k], resultfile, "group")
            n += 1
711

712
713
714
715
716
717
718
719
720
    # Generate yaml config template if requested
    if 'template' in args and args.template is not None:
        gen_template(cross_check, args.template)

    # Filter fields before writing any other type of output
    # Do not rely on specific fields being present after this step
    if args.fields is not None:
        keep_fields(cross_check, args.fields)

721
722
723
724
    # Do a `uniq` pass if requested
    if args.uniq:
        cross_check = uniq(cross_check)

725
726
727
    # Auto-discover the fields and take the option into account
    fields = discover_fields(cross_check, args.fields)

Vincent Stehlé's avatar
Vincent Stehlé committed
728
729
    # Generate csv if requested
    if args.csv is not None:
730
        gen_csv(cross_check, args.csv, fields)
Vincent Stehlé's avatar
Vincent Stehlé committed
731

Vincent Stehlé's avatar
Vincent Stehlé committed
732
733
734
735
    # Generate json if requested
    if args.json is not None:
        gen_json(cross_check, args.json)

736
737
738
739
    # Generate yaml if requested
    if 'yaml' in args and args.yaml is not None:
        gen_yaml(cross_check, args.yaml)

740
741
742
743
    # Print if requested
    if args.print:
        do_print(cross_check, fields)

744
745
    # command line argument 3&4, key are to support a key & value search.
    # these will be displayed in CLI
Vincent Stehlé's avatar
Vincent Stehlé committed
746
747
    if args.find_key is not None and args.find_value is not None:
        found = key_value_find(db1, args.find_key, args.find_value)
Jeff Booher-Kaeding's avatar
V1.0?    
Jeff Booher-Kaeding committed
748
749
750
        #print the dict
        print("found:",len(found),"items with search constraints")
        for x in found:
Vincent Stehlé's avatar
Vincent Stehlé committed
751
752
753
754
            print(
                x["guid"], ":", x["name"], "with", args.find_key, ":",
                x[args.find_key])

755

756
main()