I need to test the python dictionary in the python module without running the file. So I've decided to parse it with the ast.parse. I've almost figure out how to build the original dictionary except I can't find a way to get function values working.
config.py
...
config = {
# theese None, booleans and strings I got parsed
user_info: None,
debug: False,
cert_pass: "test",
# the function values I have problem with
project_directory: os.path.join(__file__, 'project')
}
...
test.py
...
# Skiping the AST parsing part, going straight to parsing config dict
def parse_ast_dict(ast_dict):
#ast_dict is instance of ast.Dict
result_dict = {}
# iterating over keys and values
for item in zip(ast_dict.keys, ast_dict.values):
if isinstance(item[1], ast.NameConstant):
result_dict[item[0].s] = item[1].value
elif isinstance(item[1], ast.Str):
result_dict[item[0].s] = item[1].s
elif isinstance(item[1], ast.Num):
result_dict[item[0].s] = item[1].n
# I got stuck here parsing the ast.Call which in my case is os.path.join calls
elif isinstance(item[0].s, ast.Call):
pass
return result_dict
I can't move the config object to a different file so that I can test it in isolation because it's a vendor provided code piece and can't import it to the tests either because it contains a lot of library imports so I stuck with ast.
from How to get the function result from ast.Call object?
No comments:
Post a Comment