forked from OpenBB-finance/OpenBB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
choices.py
324 lines (267 loc) · 9.6 KB
/
choices.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
from argparse import ArgumentParser
from contextlib import contextmanager
from inspect import isfunction, unwrap
from os import environ
from types import MethodType
from typing import Callable, List
from unittest.mock import patch
from openbb_terminal.helper_funcs import check_file_type_saved, check_positive
from openbb_terminal.rich_config import get_ordered_list_sources
def __mock_parse_known_args_and_warn(
controller,
parser: ArgumentParser,
other_args: List[str],
export_allowed: int = 0,
raw: bool = False,
limit: int = 0,
) -> None:
"""Add the arguments that would have normally added by :
- openbb_terminal.parent_classes.BaseController.parse_known_args_and_warn
Parameters
----------
parser: argparse.ArgumentParser
Parser with predefined arguments
other_args: List[str]
list of arguments to parse
export_allowed: int
Choose from 0, 1,
2 and EXPORT_BOTH_RAW_DATA_AND_FIGURES
raw: bool
Add the --raw flag
limit: int
Add a --limit flag with this number default
"""
_ = other_args
parser.add_argument(
"-h", "--help", action="store_true", help="show this help message"
)
if export_allowed > 0:
choices_export = []
help_export = "Does not export!"
if export_allowed == 1:
choices_export = ["csv", "json", "xlsx"]
help_export = "Export raw data into csv, json, xlsx"
elif export_allowed == 2:
choices_export = ["png", "jpg", "pdf", "svg"]
help_export = "Export figure into png, jpg, pdf, svg "
else:
choices_export = ["csv", "json", "xlsx", "png", "jpg", "pdf", "svg"]
help_export = "Export raw data into csv, json, xlsx and figure into png, jpg, pdf, svg "
parser.add_argument(
"--export",
default="",
type=check_file_type_saved(choices_export),
dest="export",
help=help_export,
choices=choices_export,
)
if raw:
parser.add_argument(
"--raw",
dest="raw",
action="store_true",
default=False,
help="Flag to display raw data",
)
if limit > 0:
parser.add_argument(
"-l",
"--limit",
dest="limit",
default=limit,
help="Number of entries to show in data.",
type=check_positive,
)
sources = get_ordered_list_sources(f"{controller.PATH}{parser.prog}")
# Allow to change source if there is more than one
if len(sources) > 1:
parser.add_argument(
"--source",
action="store",
dest="source",
choices=sources,
default=sources[0], # the first source from the list is the default
help="Data source to select from",
)
def __mock_parse_simple_args(parser: ArgumentParser, other_args: List[str]) -> None:
"""Add the arguments that would have normally added by:
- openbb_terminal.parent_classes.BaseController.parse_simple_args
Parameters
----------
parser: argparse.ArgumentParser
Parser with predefined arguments
other_args: List[str]
List of arguments to parse
"""
parser.add_argument(
"-h", "--help", action="store_true", help="show this help message"
)
_ = other_args
def __get_command_func(controller, command: str):
"""Get the function with the name `f"call_{command}"` from controller object.
Parameters
----------
controller: BaseController
Instance of the Terminal Controller.
command: str
A name from controller.CHOICES_COMMANDS
Returns
-------
Callable: Command function.
"""
if command not in controller.CHOICES_COMMANDS:
raise AttributeError(
f"The following command is not inside `CHOICES_COMMANDS` : '{command}'"
)
command = f"call_{command}"
command_func = getattr(controller, command)
command_func = unwrap(func=command_func)
if isfunction(command_func):
command_func = MethodType(command_func, controller)
return command_func
def contains_functions_to_patch(command_func: Callable) -> bool:
"""Check if a `command_func` actually contains the functions we want to mock, i.e.:
- parse_simple_args
- parse_known_args_and_warn
Parameters
----------
command_func: Callable
Function to check.
Returns
-------
bool: Whether or not `command_func` contains the mocked functions.
"""
co_names = command_func.__code__.co_names
if "parse_simple_args" in co_names:
in_command = True
elif "parse_known_args_and_warn" in co_names:
in_command = True
else:
in_command = False
return in_command
@contextmanager
def __patch_controller_functions(controller):
"""Patch the following function from a BaseController instance:
- parse_simple_args
- parse_known_args_and_warn
These functions take an 'argparse.ArgumentParser' object as parameter.
We want to intercept this 'argparse.ArgumentParser' object.
Parameters
----------
controller: BaseController
BaseController object that needs to be patched.
Returns
-------
List[Callable]: List of mocked functions.
"""
bound_mock_parse_known_args_and_warn = MethodType(
__mock_parse_known_args_and_warn,
controller,
)
rich = patch(
target="openbb_terminal.rich_config.ConsoleAndPanel.print",
return_value=None,
)
patcher_list = [
patch.object(
target=controller,
attribute="parse_simple_args",
side_effect=__mock_parse_simple_args,
return_value=None,
),
patch.object(
target=controller,
attribute="parse_known_args_and_warn",
side_effect=bound_mock_parse_known_args_and_warn,
return_value=None,
),
]
if str(environ.get("DEBUG_MODE", "false")).lower() != "true":
rich.start()
patched_function_list = []
for patcher in patcher_list:
patched_function_list.append(patcher.start())
yield patched_function_list
if str(environ.get("DEBUG_MODE", "false")).lower() != "true":
rich.stop()
for patcher in patcher_list:
patcher.stop()
def _get_argument_parser(
controller,
command: str,
) -> ArgumentParser:
"""Intercept the ArgumentParser instance from the command function.
A command function being a function starting with `call_`, like:
- call_help
- call_overview
- call_load
Parameters
----------
controller: BaseController
Instance of the Terminal Controller.
command: str
A name from `controller.CHOICES_COMMANDS`.
Returns
-------
ArgumentParser: ArgumentParser instance from the command function.
"""
command_func: Callable = __get_command_func(controller=controller, command=command)
if not contains_functions_to_patch(command_func=command_func):
raise AssertionError(
f"One of these functions should be inside `call_{command}`:\n"
" - parse_simple_args\n"
" - parse_known_args_and_warn\n"
)
with __patch_controller_functions(controller=controller) as patched_function_list:
command_func([])
call_count = 0
for patched_function in patched_function_list:
call_count += patched_function.call_count
if patched_function.call_count == 1:
args = patched_function.call_args.args
argument_parser = args[0]
if call_count != 1:
raise AssertionError(
f"One of these functions should be called once inside `call_{command}`:\n"
" - parse_simple_args\n"
" - parse_known_args_and_warn\n"
)
return argument_parser
def _build_command_choice_map(argument_parser: ArgumentParser) -> dict:
choice_map: dict = {}
for action in argument_parser._actions: # pylint: disable=protected-access
if len(action.option_strings) == 1:
long_name = action.option_strings[0]
short_name = ""
elif len(action.option_strings) == 2:
short_name = action.option_strings[0]
long_name = action.option_strings[1]
else:
raise AttributeError(f"Invalid argument_parser: {argument_parser}")
if hasattr(action, "choices") and action.choices:
choice_map[long_name] = {str(c): {} for c in action.choices}
else:
choice_map[long_name] = {}
if short_name and long_name:
choice_map[short_name] = long_name
return choice_map
def build_controller_choice_map(controller) -> dict:
command_list = controller.CHOICES_COMMANDS
controller_choice_map: dict = {c: {} for c in controller.controller_choices}
controller_choice_map["support"] = controller.SUPPORT_CHOICES
controller_choice_map["about"] = controller.ABOUT_CHOICES
for command in command_list:
try:
argument_parser = _get_argument_parser(
controller=controller,
command=command,
)
controller_choice_map[command] = _build_command_choice_map(
argument_parser=argument_parser
)
except Exception as exception:
if str(environ.get("DEBUG_MODE", "false")).lower() == "true":
raise Exception(
f"On command : `{command}`.\n{str(exception)}"
) from exception
return controller_choice_map