source: flex_extract.git/source/pythontest/TestTools.py @ 96e1533

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

redefined test data dir and completed unittests for tools module

  • Property mode set to 100644
File size: 13.8 KB
Line 
1#!/opt/anaconda/bin/python
2# -*- coding: utf-8 -*-
3
4# for the gateway tests, the env vars of ECUID and ECGID have to be set upfront
5
6import os
7import sys
8import errno
9from exceptions import OSError
10import subprocess
11import pipes
12import pytest
13from mock import patch, call
14#from mock import PropertyMock
15
16
17import _config
18import _config_test
19from classes.ControlFile import ControlFile
20from mods.tools import (none_or_str, none_or_int, get_cmdline_arguments,
21                        read_ecenv, clean_up, my_error, send_mail,
22                        normal_exit, product, silent_remove,
23                        init128, to_param_id, get_list_as_string, make_dir,
24                        put_file_to_ecserver, submit_job_to_ecserver)
25
26class TestTools(object):
27    '''
28    '''
29
30    def setup_method(self):
31        self.testdir = _config_test.PATH_TEST_DIR
32        self.testfilesdir = _config_test.PATH_TESTFILES_DIR
33        self.c = ControlFile(self.testdir+'/Controls/CONTROL.test')
34
35    def test_nonestr_none_or_int(self):
36        assert None == none_or_int('None')
37
38    def test_intstr_none_or_int(self):
39        assert 42 == none_or_int('42')
40
41    def test_nonestr_none_or_str(self):
42        assert None == none_or_str('None')
43
44    def test_anystr_none_or_str(self):
45        assert 'test' == none_or_str('test')
46
47    def test_default_get_cmdline_arguments(self):
48        cmd_dict_control = {'start_date':None,
49                            'end_date':None,
50                            'date_chunk':None,
51                            'basetime':None,
52                            'step':None,
53                            'levelist':None,
54                            'area':None,
55                            'inputdir':None,
56                            'outputdir':None,
57                            'flexpart_root_scripts':None,
58                            'ppid':None,
59                            'job_template':'job.temp',
60                            'queue':None,
61                            'controlfile':'CONTROL.temp',
62                            'debug':None,
63                            'public':None,
64                            'request':None}
65
66        sys.argv = ['dummy.py']
67
68        results = get_cmdline_arguments()
69
70        assert cmd_dict_control == vars(results)
71
72
73    def test_input_get_cmdline_arguments(self):
74        cmd_dict_control = {'start_date':'20180101',
75                            'end_date':'20180101',
76                            'date_chunk':3,
77                            'basetime':12,
78                            'step':'1',
79                            'levelist':'1/to/10',
80                            'area':'50/10/60/20',
81                            'inputdir':'../work',
82                            'outputdir':None,
83                            'flexpart_root_scripts':'../',
84                            'ppid':1234,
85                            'job_template':'job.sh',
86                            'queue':'ecgate',
87                            'controlfile':'CONTROL.WORK',
88                            'debug':1,
89                            'public':None,
90                            'request':0}
91
92        sys.argv = ['dummy.py',
93                    '--start_date=20180101',
94                    '--end_date=20180101',
95                    '--date_chunk=3',
96                    '--basetime=12',
97                    '--step=1',
98                    '--levelist=1/to/10',
99                    '--area=50/10/60/20',
100                    '--inputdir=../work',
101                    '--outputdir=None',
102                    '--flexpart_root_scripts=../',
103                    '--ppid=1234',
104                    '--job_template=job.sh',
105                    '--queue=ecgate',
106                    '--controlfile=CONTROL.WORK',
107                    '--debug=1',
108                    '--public=None',
109                    '--request=0']
110
111        results = get_cmdline_arguments()
112
113        assert cmd_dict_control == vars(results)
114
115    def test_success_init128(self):
116        table128 = init128(_config.PATH_GRIBTABLE)
117        expected_sample = {'078': 'TCLW', '130': 'T', '034': 'SST'}
118        # check a sample of parameters which must have been read in
119        assert all((k in table128 and table128[k]==v)
120                   for k,v in expected_sample.iteritems())
121
122    @patch('__builtin__.open', side_effect=[OSError(errno.EEXIST)])
123    def test_fail_open_init128(self, mock_openfile):
124        with pytest.raises(SystemExit):
125            table128 = init128(_config.PATH_GRIBTABLE)
126
127    @pytest.mark.parametrize(
128        'ipar_str, opar_listint',
129        [('SP/LSP/SSHF', [134, 142, 146]),
130         ('T', [130]),
131         ('', []),
132         (None, []),
133         ('testtest', []),
134         ('130/142', [130, 142]),
135         (130, [130]),
136         (50.56, [])])
137    def test_to_param_id(self, ipar_str, opar_listint):
138        table128 = init128(_config.PATH_GRIBTABLE)
139        ipars = to_param_id(ipar_str, table128)
140        assert sorted(ipars) == sorted(opar_listint)
141
142    @patch('traceback.format_stack', return_value='empty trace')
143    @patch('mods.tools.send_mail', return_value=0)
144    def test_success_my_error(self, mock_mail, mock_trace, capfd):
145        with pytest.raises(SystemExit):
146            my_error(['any_user'], 'Failed!')
147            out, err = capfd.readouterr()
148            assert out == "Failed!\n\nempty_trace\n"
149
150    @patch('subprocess.Popen')
151    @patch('os.getenv', return_value='user')
152    @patch('os.path.expandvars', return_value='user')
153    def test_success_userenv_twouser_send_mail(self, mock_os, mock_env, mock_popen, capfd):
154        mock_popen.return_value = subprocess.Popen(["echo", "Hello Test!"],
155                                                   stdout=subprocess.PIPE)
156        send_mail(['${USER}', 'any_user'], 'ERROR', message='error mail')
157        out, err = capfd.readouterr()
158        assert out == b'Email sent to user\nEmail sent to user\n'
159
160    @patch('subprocess.Popen')
161    @patch('os.path.expandvars', return_value='any_user')
162    def test_success_send_mail(self, mock_os,  mock_popen, capfd):
163        mock_popen.return_value = subprocess.Popen(["echo", "Hello Test!"],
164                                                   stdout=subprocess.PIPE)
165        send_mail(['any-user'], 'ERROR', message='error mail')
166        out, err = capfd.readouterr()
167        assert out == b'Email sent to any_user\n'
168
169    @patch('subprocess.Popen', side_effect=[ValueError, OSError])
170    @patch('os.path.expandvars', return_value='any_user')
171    def test_fail_valueerror_send_mail(self, mock_osvar, mock_popen):
172        with pytest.raises(SystemExit): # ValueError
173            send_mail(['any-user'], 'ERROR', message='error mail')
174        with pytest.raises(SystemExit): # OSError
175            send_mail(['any-user'], 'ERROR', message='error mail')
176
177    def test_success_read_ecenv(self):
178        envs_ref = {'ECUID': 'testuser',
179                    'ECGID': 'testgroup',
180                    'GATEWAY': 'gateway.test.ac.at',
181                    'DESTINATION': 'user@destination'
182                   }
183        envs = read_ecenv(self.testfilesdir + '/ECMWF_ENV.test')
184
185        assert envs_ref == envs
186
187    @patch('__builtin__.open', side_effect=[OSError(errno.EPERM)])
188    def test_fail_read_ecenv(self, mock_open):
189        with pytest.raises(SystemExit):
190            read_ecenv('any_file')
191
192    @patch('glob.glob', return_value=[])
193    @patch('mods.tools.silent_remove')
194    def test_empty_clean_up(self, mock_rm, mock_clean):
195        clean_up(self.c)
196        mock_rm.assert_not_called()
197
198    @patch('glob.glob', return_value=['any_file','EIfile'])
199    @patch('os.remove', return_value=0)
200    def test_success_clean_up(self, mock_rm, mock_glob):
201        # ectrans=0; ecstorage=0; ecapi=None; prefix not in filename
202        clean_up(self.c)
203        mock_rm.assert_has_calls([call('any_file'), call('EIfile')])
204        mock_rm.reset_mock()
205
206        # ectrans=0; ecstorage=0; ecapi=False; prefix in filename
207        self.c.prefix = 'EI'
208        self.c.ecapi = False
209        clean_up(self.c)
210        mock_rm.assert_has_calls([call('any_file')])
211        mock_rm.reset_mock()
212
213        # ectrans=0; ecstorage=0; ecapi=True; prefix in filename
214        self.c.prefix = 'EI'
215        self.c.ecapi = True
216        clean_up(self.c)
217        mock_rm.assert_has_calls([call('any_file')])
218        mock_rm.reset_mock()
219
220        # ectrans=1; ecstorage=0; ecapi=True; prefix in filename
221        self.c.prefix = 'EI'
222        self.c.ecapi = True
223        self.c.ectrans = 1
224        clean_up(self.c)
225        mock_rm.assert_has_calls([call('any_file')])
226        mock_rm.reset_mock()
227
228        # ectrans=1; ecstorage=0; ecapi=False; prefix in filename
229        self.c.prefix = 'EI'
230        self.c.ecapi = False
231        self.c.ectrans = 1
232        clean_up(self.c)
233        mock_rm.assert_has_calls([call('any_file'), call('EIfile')])
234        mock_rm.reset_mock()
235
236        # ectrans=1; ecstorage=1; ecapi=False; prefix in filename
237        self.c.prefix = 'EI'
238        self.c.ecapi = False
239        self.c.ectrans = 1
240        self.c.ecstorage = 1
241        clean_up(self.c)
242        mock_rm.assert_has_calls([call('any_file'), call('EIfile')])
243        mock_rm.reset_mock()
244
245    def test_default_normal_exit(self, capfd):
246        normal_exit()
247        out, err = capfd.readouterr()
248        assert out == 'Done!\n'
249
250    def test_message_normal_exit(self, capfd):
251        normal_exit('Hi there!')
252        out, err = capfd.readouterr()
253        assert out == 'Hi there!\n'
254
255    def test_int_normal_exit(self, capfd):
256        normal_exit(42)
257        out, err = capfd.readouterr()
258        assert out == '42\n'
259
260    @pytest.mark.parametrize(
261        'input1, input2, output_list',
262        [('ABC','xy',[('A','x'),('A','y'),('B','x'),('B','y'),('C','x'),('C','y')]),
263         (range(1), range(1), [(0,0),(0,1),(1,0),(1,1)])])
264    def test_success_product(self, input1, input2, output_list):
265        index = 0
266        for prod in product(input1, input2):
267            assert isinstance(prod, tuple)
268            assert prod == output_list[index]
269            index += 1
270
271    @pytest.mark.parametrize(
272        'input1, input2, output_list',
273        [(1,1,(1,1))])
274    def test_fail_product(self, input1, input2, output_list):
275        index = 0
276        with pytest.raises(SystemExit):
277            for prod in product(input1, input2):
278                assert isinstance(prod, tuple)
279                assert prod == output_list[index]
280                index += 1
281
282    def test_success_silent_remove(self):
283        testfile = self.testfilesdir + 'test.txt'
284        open(testfile, 'w').close()
285        silent_remove(testfile)
286        assert os.path.isfile(testfile) == False
287
288    @patch('os.remove', side_effect=OSError(errno.ENOENT))
289    def test_fail_notexist_silent_remove(self, mock_rm):
290        with pytest.raises(OSError) as pytest_wrapped_e:
291            silent_remove('any_dir')
292            assert pytest_wrapped_e.e.errno == errno.ENOENT
293
294    @patch('os.remove', side_effect=OSError(errno.EEXIST))
295    def test_fail_any_silent_remove(self, mock_rm):
296        with pytest.raises(OSError):
297            silent_remove('any_dir')
298
299    @pytest.mark.parametrize(
300        'input_list, output_list',
301        [([],''),
302         ([1, 2, 3.5, '...', 'testlist'], '1, 2, 3.5, ..., testlist'),
303         ('2', '2')])
304    def test_success_get_list_as_string(self, input_list, output_list):
305        assert output_list == get_list_as_string(input_list)
306
307    @patch('os.makedirs', side_effect=[OSError(errno.EEXIST)])
308    def test_warning_exist_make_dir(self, mock_make):
309        with pytest.raises(OSError) as pytest_wrapped_e:
310            make_dir('existing_dir')
311            assert pytest_wrapped_e.e.errno == errno.EEXIST
312
313    @patch('os.makedirs', side_effect=OSError)
314    def test_fail_any_make_dir(self, mock_makedir):
315        with pytest.raises(OSError):
316            make_dir('any_dir')
317
318    def test_fail_empty_make_dir(self):
319        with pytest.raises(OSError):
320            make_dir('')
321
322    def test_success_make_dir(self):
323        testdir = '/testing_mkdir'
324        make_dir(self.testdir + testdir)
325        assert os.path.exists(self.testdir + testdir) == True
326        os.rmdir(self.testdir + testdir)
327
328
329    @patch('subprocess.check_output', side_effect=[subprocess.CalledProcessError(1,'test')])
330    def test_fail_put_file_to_ecserver(self, mock_co):
331        with pytest.raises(SystemExit):
332            put_file_to_ecserver(self.testfilesdir, 'test_put_to_ecserver.txt',
333                                 'ecgate', 'ex_ECUID', 'ex_ECGID')
334
335    @patch('subprocess.check_output', return_value=0)
336    def test_general_success_put_file_to_ecserver(self, mock_co):
337        result = put_file_to_ecserver(self.testfilesdir, 'test_put_to_ecserver.txt',
338                                      'ecgate', 'ex_ECUID', 'ex_ECGID')
339        assert result == None
340
341    @pytest.mark.msuser_pw
342    @pytest.mark.gateway
343    @pytest.mark.skip(reason="easier to ignore for now - implement in final version")
344    def test_full_success_put_file_to_ecserver(self):
345        ecuid = os.environ['ECUID']
346        ecgid = os.environ['ECGID']
347        put_file_to_ecserver(self.testfilesdir, 'test_put_to_ecserver.txt',
348                             'ecgate', ecuid, ecgid)
349        assert subprocess.call(['ssh', ecuid+'@ecaccess.ecmwf.int' ,
350                                'test -e ' +
351                                pipes.quote('/home/ms/'+ecgid+'/'+ecuid)]) == 0
352
353    @patch('subprocess.check_output', side_effect=[subprocess.CalledProcessError(1,'test'),
354                                                   OSError])
355    def test_fail_submit_job_to_ecserver(self, mock_co):
356        with pytest.raises(SystemExit):
357            job_id = submit_job_to_ecserver('ecgate', 'job.ksh')
358
359    @pytest.mark.msuser_pw
360    @pytest.mark.gateway
361    @pytest.mark.skip(reason="easier to ignore for now - implement in final version")
362    def test_success_submit_job_to_ecserver(self):
363        job_id = submit_job_to_ecserver('ecgate',
364                                        os.path.join(self.testfilesdir,
365                                                     'test_put_to_ecserver.txt'))
366        assert job_id.strip().isdigit() == True
367
368
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG