forked from psyplot/psyplot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_main.py
More file actions
201 lines (184 loc) · 7.69 KB
/
Copy pathtest_main.py
File metadata and controls
201 lines (184 loc) · 7.69 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""Test the :mod:`psyplot.__main__` module."""
# Disclaimer
# ----------
#
# Copyright (C) 2021 Helmholtz-Zentrum Hereon
# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht
# Copyright (C) 2016-2021 University of Lausanne
#
# This file is part of psyplot and is released under the GNU LGPL-3.O license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3.0 as
# published by the Free Software Foundation.
#
# 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 LGPL-3.0 license for more details.
#
# You should have received a copy of the GNU LGPL-3.0 license
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import os
import os.path as osp
import subprocess as spr
import yaml
import shutil
import tempfile
import unittest
from itertools import product
import six
import _base_testing as bt
import psyplot.__main__ as main
import psyplot.project as psy
import psyplot
import matplotlib.pyplot as plt
import test_plotter as tp
import inspect
remove_temp_files = True
class TestCommandLine(unittest.TestCase):
"""Test the command line utitliy of psyplot"""
_created_files = set()
def setUp(self):
psy.close('all')
plt.close('all')
self._created_files = set()
def tearDown(self):
for identifier in list(psy.registered_plotters):
psy.unregister_plotter(identifier)
psy.close('all')
plt.close('all')
tp.results.clear()
if remove_temp_files:
for f in self._created_files:
if osp.exists(f) and osp.isdir(f):
shutil.rmtree(f)
elif osp.exists(f):
os.remove(f)
self._created_files.clear()
def _create_and_save_test_project(self):
psy.register_plotter('test_plotter', module='test_plotter',
plotter_name='TestPlotter')
sp = psy.plot.test_plotter(bt.get_file('test-t2m-u-v.nc'),
name=['t2m', 'u'], time=[0, 1])
self.assertEqual(len(sp), 4, sp)
fname = tempfile.NamedTemporaryFile(
suffix='.pkl', prefix='test_psyplot_').name
self._created_files.add(fname)
sp.save_project(fname, use_rel_paths=False)
return sp, fname
def test_get_parser(self):
parser = main.get_parser()
args = inspect.getfullargspec(main.make_plot)[0]
for arg in args:
self.assertIn(arg, parser.unfinished_arguments,
msg='Missing ' + arg)
def test_main_01_from_project(self):
"""Test the :func:`psyplot.__main__.main` function"""
if not six.PY2:
with self.assertRaisesRegex(ValueError, 'filename'):
main.main(['-o', 'test.pdf'])
sp, fname1 = self._create_and_save_test_project()
fname2 = tempfile.NamedTemporaryFile(
suffix='.pdf', prefix='test_psyplot_').name
self._created_files.add(fname2)
sp.save_project(fname1, use_rel_paths=False)
psy.close('all')
if six.PY2:
main.main(['-p', fname1, '-o', fname2])
else:
with self.assertWarnsRegex(UserWarning, 'ignored'):
main.main(['-p', fname1, '-o', fname2, '-n', 't2m'])
self.assertTrue(osp.exists(fname2), msg='Missing ' + fname2)
self.assertEqual(len(psy.gcp(True)), 4)
def test_main_02_alternative_ds(self):
sp, fname1 = self._create_and_save_test_project()
fname2 = tempfile.NamedTemporaryFile(
suffix='.pdf', prefix='test_psyplot_').name
self._created_files.add(fname2)
sp.save_project(fname1, use_rel_paths=False)
psy.close('all')
main.main([bt.get_file('circumpolar_test.nc'), '-p', fname1,
'-o', fname2])
self.assertTrue(osp.exists(fname2), msg='Missing ' + fname2)
mp = psy.gcp(True)
self.assertEqual(len(mp), 4)
self.assertEqual(
set(t[0] for t in mp._get_dsnames(mp.array_info(
dump=False, use_rel_paths=False))),
{bt.get_file('circumpolar_test.nc')})
def test_main_03_dims(self):
import yaml
psy.register_plotter('test_plotter', module='test_plotter',
plotter_name='TestPlotter')
fname2 = tempfile.NamedTemporaryFile(
suffix='.pdf', prefix='test_psyplot_').name
self._created_files.add(fname2)
# create a formatoptions file
fmt_file = tempfile.NamedTemporaryFile(
suffix='.yml', prefix='test_psyplot_').name
self._created_files.add(fmt_file)
with open(fmt_file, 'w') as f:
yaml.dump({'fmt1': 'fmt1', 'fmt2': 'fmt2'}, f)
if not six.PY2:
with self.assertRaisesRegex(ValueError, 'plotting method'):
main.main([bt.get_file('test-t2m-u-v.nc'), '-o', fname2,
'-d', 'time,1,2', 'y,3,4', '-n', 'u', 'v'])
main.main([bt.get_file('test-t2m-u-v.nc'), '-o', fname2,
'-d', 'time,1,2', 'y,3,4', '-n', 'u', 'v',
'-pm', 'test_plotter', '-fmt', fmt_file])
mp = psy.gcp(True)
self.assertEqual(len(mp), 2*2*2, msg=mp)
all_dims = set(product((1, 2), (3, 4), ('u', 'v')))
for arr in mp:
idims = arr.psy.idims
all_dims -= {(idims['time'], idims['lat'], arr.name)}
self.assertFalse(all_dims)
for i, plotter in enumerate(mp.plotters):
self.assertEqual(plotter['fmt1'], 'fmt1',
msg='Wrong value for fmt1 of plotter %i!' % i)
self.assertEqual(plotter['fmt2'], 'fmt2',
msg='Wrong value for fmt2 of plotter %i!' % i)
def test_all_versions(self):
"""Test to display all versions"""
ref = psyplot.get_versions()
proc = spr.Popen([sys.executable, '-m', 'psyplot', '-aV'],
stdout=spr.PIPE, stderr=spr.PIPE)
proc.wait()
self.assertFalse(proc.poll(), msg=proc.stderr.read())
d = yaml.load(proc.stdout.read(), yaml.Loader)
d.pop('psyplot_gui', None)
ref.pop('psyplot_gui', None)
# make sure the version does not end with .dirty
d["psyplot"]["version"] = d["psyplot"]["version"].replace(".dirty", "")
ref["psyplot"]["version"] = ref["psyplot"]["version"].replace(
".dirty", ""
)
self.assertEqual(d, ref)
def test_list_plugins(self):
"""Test to display all versions"""
ref = psyplot.rcParams._plugins
proc = spr.Popen([sys.executable, '-m', 'psyplot', '-lp'],
stdout=spr.PIPE, stderr=spr.PIPE)
proc.wait()
self.assertFalse(proc.poll(), msg=proc.stderr.read())
d = yaml.load(proc.stdout.read(), yaml.Loader)
self.assertEqual(d, ref)
def test_list_plot_methods(self):
"""Test to display all versions"""
proc = spr.Popen([sys.executable, '-m', 'psyplot', '-lpm'],
stdout=spr.PIPE, stderr=spr.PIPE)
proc.wait()
self.assertFalse(proc.poll(), msg=proc.stderr.read())
import psyplot.project as psy
for pm, d in psyplot.rcParams['project.plotters'].items():
try:
psy.register_plotter(pm, **d)
except:
pass
ref = psy.plot._plot_methods
d = yaml.load(proc.stdout.read(), yaml.Loader)
self.assertEqual(d, ref)