source: flex_extract.git/test/Regression/Mars_request/test_cmp_mars_requests.py @ 2f5ca80

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

added comparison test for mars requests with a starter set of control files to test

  • Property mode set to 100644
File size: 6.7 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""Comparison of the created MARS requests of two flex_extract versions.
4
5There will be comparisons for the given standard control files in the
6"Controls" - directory. The result of the comparison is stored in the
7"Log" - directory with an individual timestamp in the format %Y-%m-%d_%H-%M-%S.
8(E.g. log_2018-11-23_12-42-29)
9The MARS request files are named such that it contains the name of the
10corresponding control files "<control-identifier>.csv" (e.g. EA5_mr.csv).
11They are stored in the corresponding version directory and have the same
12name in both versions.
13
14The script should be called like:
15
16    python test_cmp_mars_requests.py <old_version_number> <new_version_number>
17
18Note
19----
20The MARS request files from the older version have to be in place already.
21The request files of the new/current version will be generated automatically
22with the "run_local.sh" script.
23It is necessary to have a directory named after the version number of
24flex_extract. For example: "7.0.3" and "7.1".
25
26Example
27-------
28    python test_cmp_mars_requests.py 7.0.3 7.1
29"""
30
31# ------------------------------------------------------------------------------
32# MODULES
33# ------------------------------------------------------------------------------
34import os
35import sys
36import pandas as pd
37import subprocess
38import shutil
39from datetime import datetime
40
41sys.path.append('../../../source/python')
42import _config
43
44# ------------------------------------------------------------------------------
45# FUNCTION
46# ------------------------------------------------------------------------------
47def test_mr_column_equality(mr_old, mr_new):
48    '''Check if old and new version of MARS requests have the same
49    amount of columns.
50
51    If the number is not equal and/or the column names are not equal
52    an error message is stored in global variable "err_msg".
53
54    Parameters
55    ----------
56    mr_old : :obj:`pandas DataFrame`
57        Contains the mars requests from the old version of
58        flex_extract.
59
60    mr_new : :obj:`pandas DataFrame`
61        Contains the mars requests from the new version of
62        flex_extract.
63
64    Return
65    ------
66    bool
67        True if successful, False otherwise.
68    '''
69    global err_msg
70    if (len(mr_old.columns.values) == len(mr_new.columns.values) and
71        sorted(mr_old.columns.values) == sorted(mr_new.columns.values)):
72        return True
73    else:
74        err_msg = 'Unequal number and/or column names!\n'
75        return False
76
77
78def test_mr_number_equality(mr_old, mr_new):
79    '''Check if old and new version have the same number of requests.
80
81    If the number is not equal an error message is stored in
82    global variable "err_msg".
83
84    Parameters
85    ----------
86    mr_old : :obj:`pandas DataFrame`
87        Contains the mars requests from the old version of
88        flex_extract.
89
90    mr_new : :obj:`pandas DataFrame`
91        Contains the mars requests from the new version of
92        flex_extract.
93
94    Return
95    ------
96    bool
97        True if successful, False otherwise.
98    '''
99    global err_msg
100    if len(mr_new.index) == len(mr_old.index):
101        return True
102    else:
103        err_msg = 'Unequal number of mars requests!\n'
104        return False
105
106def test_mr_content_equality(mr_old, mr_new):
107    '''Check if old and new version have the same request contents.
108
109    If the content in a column is not equal an error message is stored in
110    global variable "err_msg", recording the column.
111
112    Parameters
113    ----------
114    mr_old : :obj:`pandas DataFrame`
115        Contains the mars requests from the old version of
116        flex_extract.
117
118    mr_new : :obj:`pandas DataFrame`
119        Contains the mars requests from the new version of
120        flex_extract.
121
122    Return
123    ------
124    bool
125        True if successful, False otherwise.
126    '''
127    global err_msg
128    lresult = None
129    columns = list(mr_new.columns.values)
130    del columns[columns.index('target')]
131    for col in columns:
132        if mr_new[col].equals(mr_old[col]):
133            lresult = True
134        else:
135            err_msg += 'Unconsistency happend to be in column: ' + col + '\n'
136            return False
137    return lresult
138
139
140if __name__ == '__main__':
141
142    # basic values for paths and versions
143    control_path = 'Controls'
144    log_path = 'Log'
145    old_dir = sys.argv[1] # e.g. '7.0.3'
146    new_dir = sys.argv[2] # e.g. '7.1'
147    mr_filename = 'mars_requests.csv'
148
149    # have to be set to "True" in the beginnning
150    # so it only fails if a test fails
151    lfinal = True
152
153    # prepare log file for this test run
154    currenttime = datetime.now()
155    time_str = currenttime.strftime('%Y-%m-%d_%H-%M-%S')
156    logfile = os.path.join(log_path, 'log_' + time_str)
157    with open(logfile, 'aw') as f:
158        f.write('Compare mars requests between version ' + old_dir +
159                ' and version ' + new_dir + ' : \n')
160
161    # list all controlfiles
162    controls =  os.listdir(control_path)
163
164    # loop over controlfiles
165    for c in controls:
166        # empty error message for every controlfile
167        err_msg = ''
168
169        # start flex_extract with controlfiles to get mars_request files
170        shutil.copy(os.path.join(control_path,c), _config.PATH_CONTROLFILES)
171        subprocess.check_output(['run_local.sh', new_dir, c])
172        os.remove(os.path.join(_config.PATH_CONTROLFILES,c))
173
174        # cut-of "CONTROL_" string and mv mars_reqeust file
175        # to a name including control specific name
176        mr_name = c.split('CONTROL_')[1] + '.csv'
177        shutil.move(os.path.join(new_dir,mr_filename), os.path.join(new_dir,mr_name))
178
179        # read both mr files (old & new)
180        mr_old = pd.read_csv(os.path.join(old_dir, mr_name))
181        mr_new = pd.read_csv(os.path.join(new_dir, mr_name))
182
183        mr_old.columns = mr_old.columns.str.strip()
184        mr_new.columns = mr_new.columns.str.strip()
185
186        # do tests on mr files
187        lcoleq = test_mr_column_equality(mr_old, mr_new)
188        lnoeq = test_mr_number_equality(mr_old, mr_new)
189        lcoeq = test_mr_content_equality(mr_old, mr_new)
190
191        # check results for mr file
192        lfinal = lfinal and lcoleq and lnoeq and lcoeq
193
194        # write out result to logging file
195        with open(logfile, 'aw') as f:
196            if lcoleq and lnoeq and lcoeq:
197                f.write('... ' + c + ' ... OK!' + '\n')
198            else:
199                f.write('... ' + c + ' ... FAILED!' + '\n')
200                if err_msg:
201                    f.write('... \t' + err_msg + '\n')
202
203    # exit with success or error status
204    if lfinal:
205        sys.exit(0) # 'SUCCESS'
206    else:
207        sys.exit(1) # 'FAIL'
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG