-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
test_plots.py
395 lines (308 loc) · 13.6 KB
/
test_plots.py
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# External imports
import mock
from mock import patch
# Bokeh imports
from bokeh.core.validation import check_integrity
from bokeh.models import (
CategoricalScale,
CustomJS,
DataRange1d,
FactorRange,
GlyphRenderer,
Label,
LinearAxis,
LinearScale,
LogScale,
PanTool,
Plot,
Range1d,
)
from bokeh.plotting import figure
# Module under test
import bokeh.models.plots as bmp # isort:skip
#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------
_LEGEND_EMPTY_WARNING = """
You are attempting to set `plot.legend.location` on a plot that has zero legends added, this will have no effect.
Before legend properties can be set, you must add a Legend explicitly, or call a glyph method with a legend parameter set.
"""
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
class TestPlotLegendProperty(object):
def test_basic(self):
plot = figure(tools='')
x = plot.legend
assert isinstance(x, bmp._list_attr_splat)
assert len(x) == 0
plot.circle([1,2], [3,4], legend_label="foo")
x = plot.legend
assert isinstance(x, bmp._list_attr_splat)
assert len(x) == 1
def test_warnign(self):
plot = figure(tools='')
with pytest.warns(UserWarning) as warns:
plot.legend.location = "above"
assert len(warns) == 1
assert warns[0].message.args[0] == _LEGEND_EMPTY_WARNING
class TestPlotSelect(object):
def setup_method(self):
self._plot = figure(tools='pan')
self._plot.circle([1,2,3], [3,2,1], name='foo')
@patch('bokeh.models.plots.find')
def test_string_arg(self, mock_find):
self._plot.select('foo')
assert mock_find.called
assert mock_find.call_args[0][1] == dict(name='foo')
@patch('bokeh.models.plots.find')
def test_type_arg(self, mock_find):
self._plot.select(PanTool)
assert mock_find.called
assert mock_find.call_args[0][1] == dict(type=PanTool)
@patch('bokeh.models.plots.find')
def test_kwargs(self, mock_find):
kw = dict(name='foo', type=GlyphRenderer)
self._plot.select(**kw)
assert mock_find.called
assert mock_find.call_args[0][1] == kw
@patch('bokeh.models.plots.find')
def test_single_selector_kwarg(self, mock_find):
kw = dict(name='foo', type=GlyphRenderer)
self._plot.select(selector=kw)
assert mock_find.called
assert mock_find.call_args[0][1] == kw
def test_selector_kwarg_and_extra_kwargs(self):
with pytest.raises(TypeError) as exc:
self._plot.select(selector=dict(foo='foo'), bar='bar')
assert "when passing 'selector' keyword arg, not other keyword args may be present" == str(exc.value)
def test_bad_arg_type(self):
with pytest.raises(TypeError) as exc:
self._plot.select(10)
assert "selector must be a dictionary, string or plot object." == str(exc.value)
def test_too_many_args(self):
with pytest.raises(TypeError) as exc:
self._plot.select('foo', 'bar')
assert 'select accepts at most ONE positional argument.' == str(exc.value)
def test_no_input(self):
with pytest.raises(TypeError) as exc:
self._plot.select()
assert 'select requires EITHER a positional argument, OR keyword arguments.' == str(exc.value)
def test_arg_and_kwarg(self):
with pytest.raises(TypeError) as exc:
self._plot.select('foo', type=PanTool)
assert 'select accepts EITHER a positional argument, OR keyword arguments (not both).' == str(exc.value)
class TestPlotValidation(object):
def test_missing_renderers(self):
p = figure()
p.renderers = []
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.warning.call_count == 1
assert mock_logger.warning.call_args[0][0].startswith("W-1000 (MISSING_RENDERERS): Plot has no renderers")
def test_missing_scale(self):
p = figure()
p.x_scale = None
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith("E-1008 (REQUIRED_SCALE): A required Scale object is missing: x_scale")
p.y_scale = None
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith("E-1008 (REQUIRED_SCALE): A required Scale object is missing: x_scale, y_scale")
def test_missing_range(self):
p = figure()
p.x_range = None
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith("E-1004 (REQUIRED_RANGE): A required Range object is missing: x_range")
p.y_range = None
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith("E-1004 (REQUIRED_RANGE): A required Range object is missing: x_range, y_range")
def test_bad_extra_range_name(self):
p = figure()
p.xaxis.x_range_name="junk"
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith(
"E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [LinearAxis"
)
p = figure()
p.extra_x_ranges['foo'] = Range1d()
p.grid.x_range_name="junk"
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 1
assert mock_logger.error.call_args[0][0].startswith(
"E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [Grid"
)
assert mock_logger.error.call_args[0][0].count("Grid") == 2
# test whether adding a figure (*and* it's extra ranges)
# to another's references doesn't create a false positive
p, dep = figure(), figure()
dep.extra_x_ranges['foo'] = Range1d()
dep.grid.x_range_name="foo"
p.x_range.callback = CustomJS(code = "", args = {"dep": dep})
assert dep in p.references()
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
check_integrity([p])
assert mock_logger.error.call_count == 0
def test_plot_add_layout_raises_error_if_not_render():
plot = figure()
with pytest.raises(ValueError):
plot.add_layout(Range1d())
def test_plot_add_layout_adds_label_to_plot_renderers():
plot = figure()
label = Label()
plot.add_layout(label)
assert label in plot.center
def test_plot_add_layout_adds_axis_to_renderers_and_side_renderers():
plot = figure()
axis = LinearAxis()
plot.add_layout(axis, 'left')
assert axis in plot.left
def test_sizing_mode_property_is_fixed_by_default():
plot = figure()
assert plot.sizing_mode is None
class BaseTwinAxis(object):
"""Base class for testing extra ranges"""
def verify_axis(self, axis_name):
plot = Plot()
range_obj = getattr(plot, 'extra_{}_ranges'.format(axis_name))
range_obj['foo_range'] = self.get_range_instance()
assert range_obj['foo_range']
def test_x_range(self):
self.verify_axis('x')
def test_y_range(self):
self.verify_axis('y')
@staticmethod
def get_range_instance():
raise NotImplementedError
class TestCategoricalTwinAxis(BaseTwinAxis, object):
"""Test whether extra x and y ranges can be categorical"""
@staticmethod
def get_range_instance():
return FactorRange('foo', 'bar')
class TestLinearTwinAxis(BaseTwinAxis, object):
"""Test whether extra x and y ranges can be Range1d"""
@staticmethod
def get_range_instance():
return Range1d(0, 42)
def test_plot_with_no_title_specified_creates_an_empty_title():
plot = Plot()
assert plot.title.text == ""
def test_plot__scale_classmethod():
assert isinstance(Plot._scale("auto"), LinearScale)
assert isinstance(Plot._scale("linear"), LinearScale)
assert isinstance(Plot._scale("log"), LogScale)
assert isinstance(Plot._scale("categorical"), CategoricalScale)
with pytest.raises(ValueError):
Plot._scale("malformed_type")
def test__check_required_scale_has_scales():
plot = Plot()
check = plot._check_required_scale()
assert check == []
def test__check_required_scale_missing_scales():
plot = Plot(x_scale=None, y_scale=None)
check = plot._check_required_scale()
assert check != []
def test__check_compatible_scale_and_ranges_compat_numeric():
plot = Plot(x_scale=LinearScale(), x_range=Range1d())
check = plot._check_compatible_scale_and_ranges()
assert check == []
plot = Plot(y_scale=LogScale(), y_range=DataRange1d())
check = plot._check_compatible_scale_and_ranges()
assert check == []
def test__check_compatible_scale_and_ranges_compat_factor():
plot = Plot(x_scale=CategoricalScale(), x_range=FactorRange())
check = plot._check_compatible_scale_and_ranges()
assert check == []
def test__check_compatible_scale_and_ranges_incompat_numeric_scale_and_factor_range():
plot = Plot(x_scale=LinearScale(), x_range=FactorRange())
check = plot._check_compatible_scale_and_ranges()
assert check != []
def test__check_compatible_scale_and_ranges_incompat_factor_scale_and_numeric_range():
plot = Plot(x_scale=CategoricalScale(), x_range=DataRange1d())
check = plot._check_compatible_scale_and_ranges()
assert check != []
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
class Test_list_attr_splat(object):
def test_set(self):
obj = bmp._list_attr_splat([DataRange1d(), DataRange1d()])
assert len(obj) == 2
assert obj[0].start == None
assert obj[1].start == None
obj.start = 10
assert obj[0].start == 10
assert obj[1].start == 10
def test_set_empty(self):
obj = bmp._list_attr_splat([])
assert len(obj) == 0
obj.start = 10
assert len(obj) == 0
def test_get_set_single(self):
p = figure()
assert len(p.xaxis) == 1
# check both ways to access
assert p.xaxis.formatter.power_limit_low != 100
assert p.xaxis[0].formatter.power_limit_low != 100
p.axis.formatter.power_limit_low = 100
assert p.xaxis.formatter.power_limit_low == 100
assert p.xaxis[0].formatter.power_limit_low == 100
def test_get_set_multi(self):
p = figure()
assert len(p.axis) == 2
# check both ways to access
assert p.axis[0].formatter.power_limit_low != 100
assert p.axis[1].formatter.power_limit_low != 100
assert p.axis.formatter[0].power_limit_low != 100
assert p.axis.formatter[1].power_limit_low != 100
p.axis.formatter.power_limit_low = 100
assert p.axis[0].formatter.power_limit_low == 100
assert p.axis[1].formatter.power_limit_low == 100
assert p.axis.formatter[0].power_limit_low == 100
assert p.axis.formatter[1].power_limit_low == 100
def test_get_set_multi_mismatch(self):
obj = bmp._list_attr_splat([LinearAxis(), FactorRange()])
with pytest.raises(AttributeError) as e:
obj.formatter.power_limit_low == 10
assert str(e.value).endswith("list items have no %r attribute" % "formatter")
def test_get_empty(self):
obj = bmp._list_attr_splat([])
with pytest.raises(AttributeError) as e:
obj.start
assert str(e.value).endswith("Trying to access %r attribute on an empty 'splattable' list" % "start")
def test_get_index(self):
obj = bmp._list_attr_splat([1, 2, 3])
assert obj.index(2) == 1
def test_pop_value(self):
obj = bmp._list_attr_splat([1, 2, 3])
obj.pop(1)
assert obj == [1, 3]
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------