-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
help_test.py
472 lines (376 loc) · 14.5 KB
/
help_test.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
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
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""st.help unit test."""
import inspect
import unittest
from unittest.mock import patch
import numpy as np
import streamlit as st
from streamlit.elements.doc_string import _get_variable_name_from_code_str
from tests.delta_generator_test_case import DeltaGeneratorTestCase
def patch_varname_getter():
"""Patches streamlit.elements.doc_string so _get_variable_name() works outside ScriptRunner."""
parent_frame_filename = inspect.getouterframes(inspect.currentframe())[2].filename
return patch(
"streamlit.elements.doc_string.SCRIPTRUNNER_FILENAME", parent_frame_filename
)
class StHelpTest(DeltaGeneratorTestCase):
"""Test st.help."""
def test_no_arg(self):
"""When st.help is called with no arguments, show Streamlit docs."""
with patch_varname_getter():
st.help()
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("", ds.name)
self.assertEqual("streamlit", ds.value)
self.assertEqual("module", ds.type)
self.assertTrue(ds.doc_string.startswith("Streamlit."))
def test_none_arg(self):
"""When st.help is called with None as an argument, don't show Streamlit docs."""
with patch_varname_getter():
st.help(None)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("", ds.name)
self.assertEqual("None", ds.value)
self.assertEqual("NoneType", ds.type)
self.assertEqual("", ds.doc_string)
def test_basic_func_with_doc(self):
"""Test basic function with docstring."""
def my_func(some_param, another_param=123):
"""This is the doc"""
pass
with patch_varname_getter():
st.help(my_func)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("my_func", ds.name)
self.assertEqual(
"tests.streamlit.elements.help_test.StHelpTest."
"test_basic_func_with_doc.<locals>.my_func(some_param, another_param=123)",
ds.value,
)
self.assertEqual("function", ds.type)
self.assertEqual("This is the doc", ds.doc_string)
def test_basic_func_without_doc(self):
"""Test basic function without docstring."""
def my_func(some_param, another_param=123):
pass
with patch_varname_getter():
st.help(my_func)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("my_func", ds.name)
self.assertEqual(
"tests.streamlit.elements.help_test.StHelpTest."
"test_basic_func_without_doc.<locals>.my_func(some_param, another_param=123)",
ds.value,
)
self.assertEqual("function", ds.type)
self.assertEqual("", ds.doc_string)
def test_deltagenerator_func(self):
"""Test Streamlit DeltaGenerator function."""
with patch_varname_getter():
st.help(st.audio)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("st.audio", ds.name)
self.assertEqual("method", ds.type)
signature = "(data: 'MediaData', format: 'str' = 'audio/wav', start_time: 'MediaTime' = 0, *, sample_rate: 'int | None' = None, end_time: 'MediaTime | None' = None, loop: 'bool' = False) -> 'DeltaGenerator'"
self.assertEqual(
f"streamlit.delta_generator.MediaMixin.audio{signature}", ds.value
)
self.assertTrue(ds.doc_string.startswith("Display an audio player"))
def test_builtin_func(self):
"""Test a built-in function."""
with patch_varname_getter():
st.help(dir)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("dir", ds.name)
self.assertEqual("builtins.dir(...)", ds.value)
self.assertEqual("builtin_function_or_method", ds.type)
self.assertTrue(len(ds.doc_string) > 0)
def test_varname(self):
"""Test a named variable."""
myvar = 123
with patch_varname_getter():
st.help(myvar)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("myvar", ds.name)
self.assertEqual("123", ds.value)
self.assertEqual("int", ds.type)
self.assertTrue(len(ds.doc_string) > 0)
def test_walrus(self):
"""Test a named variable using walrus operator."""
with patch_varname_getter():
st.help(myvar := 123)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("myvar", ds.name)
self.assertEqual("123", ds.value)
self.assertEqual("int", ds.type)
self.assertTrue(len(ds.doc_string) > 0)
def test_complex_var(self):
"""Test complex dict-list-object combination."""
myvar = {"foo": [None, {"bar": "baz"}]}
with patch_varname_getter():
st.help(myvar["foo"][1]["bar"].strip)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual('myvar["foo"][1]["bar"].strip', ds.name)
self.assertEqual(r"str.strip(chars=None, /)", ds.value)
self.assertEqual("builtin_function_or_method", ds.type)
self.assertTrue(len(ds.doc_string) > 0)
def test_builtin_obj(self):
"""Test a built-in function."""
with patch_varname_getter():
st.help(123)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("", ds.name)
self.assertEqual("123", ds.value)
self.assertEqual("int", ds.type)
self.assertTrue(len(ds.doc_string) > 0)
def test_doc_defined_for_type(self):
"""When the docs are defined for the type on an object, but not
the object, we expect the docs of the type. This is the case
of ndarray generated as follow.
"""
array = np.arange(1)
with patch_varname_getter():
st.help(array)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual("array", ds.name)
self.assertEqual("array([0])", ds.value)
self.assertEqual("ndarray", ds.type)
self.assertTrue("ndarray" in ds.doc_string)
def test_passing_a_class(self):
"""When the object is a class and no docs are defined,
we expect docs to be None."""
class MyClass(object):
pass
with patch_varname_getter():
st.help(MyClass)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual(type(MyClass), type)
self.assertEqual("MyClass", ds.name)
self.assertEqual(
"tests.streamlit.elements.help_test.StHelpTest."
"test_passing_a_class.<locals>.MyClass()",
ds.value,
)
self.assertEqual("class", ds.type)
self.assertEqual("", ds.doc_string)
def test_passing_an_instance(self):
"""When the type of the object is type and no docs are defined,
we expect docs to be None."""
class MyClass(object):
pass
with patch_varname_getter():
st.help(MyClass)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual(type(MyClass), type)
self.assertEqual("MyClass", ds.name)
self.assertEqual(
"tests.streamlit.elements.help_test.StHelpTest."
"test_passing_an_instance.<locals>.MyClass()",
ds.value,
)
self.assertEqual("class", ds.type)
self.assertEqual("", ds.doc_string)
def test_class_members(self):
class MyClass(object):
a = 1
b = 2
def __init__(self):
self.c = 3
self.d = 4
@property
def e(self):
"Property e"
return 5
@staticmethod
def staticmethod1(self, x=10):
"Static method 1"
@classmethod
def classmethod1(self, y=20):
"Class method 1"
with patch_varname_getter():
st.help(MyClass)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual(len(ds.members), 5)
expected_outputs = [
("a", "1", "", "int"),
("b", "2", "", "int"),
("e", "", "Property e", "property"),
("classmethod1", "", "Class method 1", "method"),
("staticmethod1", "", "Static method 1", "function"),
]
for i, expected in enumerate(expected_outputs):
self.assertEqual(ds.members[i].name, expected[0])
self.assertEqual(ds.members[i].value, expected[1])
self.assertEqual(ds.members[i].doc_string, expected[2])
self.assertEqual(ds.members[i].type, expected[3])
def test_instance_members(self):
class MyClass(object):
a = 1
b = 2
def __init__(self):
self.c = 3
self.d = 4
@property
def e(self):
"Property e"
return 5
@staticmethod
def staticmethod1(self, x=10):
"Static method 1"
@classmethod
def classmethod1(self, y=20):
"Class method 1"
my_instance = MyClass()
with patch_varname_getter():
st.help(my_instance)
ds = self.get_delta_from_queue().new_element.doc_string
self.assertEqual(len(ds.members), 7)
expected_outputs = [
("a", "1", "", "int"),
("b", "2", "", "int"),
("c", "3", "", "int"),
("d", "4", "", "int"),
("e", "", "Property e", "property"),
("classmethod1", "", "Class method 1", "method"),
("staticmethod1", "", "Static method 1", "function"),
]
for i, expected in enumerate(expected_outputs):
self.assertEqual(ds.members[i].name, expected[0])
self.assertEqual(ds.members[i].value, expected[1])
self.assertEqual(ds.members[i].doc_string, expected[2])
self.assertEqual(ds.members[i].type, expected[3])
st_calls = [
"st.help({0})",
"st.write({0})",
]
class GetVariableNameFromCodeStrTest(unittest.TestCase):
def test_st_help_no_arg(self):
actual = _get_variable_name_from_code_str("st.help()")
self.assertEqual(actual, None)
def test_variable_should_match_own_name(self):
tests = [
"a",
"a_b",
"a.b",
"a[b]",
"a[0]",
"a[0].c",
"a[0].c.foo()",
]
for test in tests:
for st_call in st_calls:
# Wrap test in an st call.
code = st_call.format(test)
actual = _get_variable_name_from_code_str(code)
self.assertEqual(actual, test)
def test_constant_should_have_no_name(self):
tests = [
"None",
"0",
"1",
"123",
"False",
"True",
"'some string'",
"b'some bytes'",
"...",
]
for test in tests:
for st_call in st_calls:
# Wrap test in an st call.
code = st_call.format(test)
actual = _get_variable_name_from_code_str(code)
self.assertEqual(actual, None)
def test_walrus_should_return_var_name(self):
for st_call in st_calls:
# Wrap test in an st call.
code = st_call.format("a := 123")
actual = _get_variable_name_from_code_str(code)
self.assertEqual(actual, "a")
def test_magic_should_just_echo(self):
tests = [
"a",
"a_b",
"a.b",
"a[b]",
"a[0]",
"a[0].c",
"a[0].c.foo()",
"None",
"0",
"1",
"123",
"False",
"True",
"'some string'",
"b'some bytes'",
"...",
"f'some {f} string'",
"[x for x in range(10)]",
"(x for x in range(10))",
"{x: None for x in range(10)}",
]
for code in tests:
actual = _get_variable_name_from_code_str(code)
self.assertEqual(actual, code)
# Testing with comma at the end
tests += [
"foo()",
]
for code in tests:
actual = _get_variable_name_from_code_str(code + ",")
self.assertEqual(actual, code)
def test_if_dont_know_just_echo(self):
tests = [
(
"foo()",
"foo()",
),
(
"[x for x in range(10)]",
"[x for x in range(10)]",
),
(
"(x for x in range(10))",
"(x for x in range(10))",
),
(
"x for x in range(10)",
# Python >= 3.8 has its own bug here (because of course) where the
# column offsets are off by one in different directions, leading to parentheses
# appearing around the generator expression. This leads to syntactically correct
# code, though, so not so bad!
"(x for x in range(10))",
),
(
"{x: None for x in range(10)}",
"{x: None for x in range(10)}",
),
]
for test, expected in tests:
for st_call in st_calls:
# Wrap test in an st call.
code = st_call.format(test)
actual = _get_variable_name_from_code_str(code)
self.assertEqual(actual, expected)
def test_multiline_gets_linearized(self):
test = """foo(
"bar"
)"""
for st_call in st_calls:
# Wrap test in an st call.
code = st_call.format(test)
actual = _get_variable_name_from_code_str(code)
self.assertEqual(actual, "foo(")