Unverified Commit 61f9e91c authored by Jerry Jiarui XU's avatar Jerry Jiarui XU Committed by GitHub
Browse files

Add syntax check in .py config (#330)

* Add syntax check in .py config

* rename validate
parent 2aa7712c
# Copyright (c) Open-MMLab. All rights reserved. # Copyright (c) Open-MMLab. All rights reserved.
import ast
import os.path as osp import os.path as osp
import shutil import shutil
import sys import sys
...@@ -80,6 +81,16 @@ class Config(object): ...@@ -80,6 +81,16 @@ class Config(object):
""" """
@staticmethod
def _validate_py_syntax(filename):
with open(filename) as f:
content = f.read()
try:
ast.parse(content)
except SyntaxError:
raise SyntaxError('There are syntax errors in config '
f'file {filename}')
@staticmethod @staticmethod
def _file2dict(filename): def _file2dict(filename):
filename = osp.abspath(osp.expanduser(filename)) filename = osp.abspath(osp.expanduser(filename))
...@@ -93,6 +104,7 @@ class Config(object): ...@@ -93,6 +104,7 @@ class Config(object):
osp.join(temp_config_dir, temp_config_name)) osp.join(temp_config_dir, temp_config_name))
temp_module_name = osp.splitext(temp_config_name)[0] temp_module_name = osp.splitext(temp_config_name)[0]
sys.path.insert(0, temp_config_dir) sys.path.insert(0, temp_config_dir)
Config._validate_py_syntax(filename)
mod = import_module(temp_module_name) mod = import_module(temp_module_name)
sys.path.pop(0) sys.path.pop(0)
cfg_dict = { cfg_dict = {
......
...@@ -272,3 +272,17 @@ def test_reserved_key(): ...@@ -272,3 +272,17 @@ def test_reserved_key():
cfg_file = osp.join(osp.dirname(__file__), 'data/config/g.py') cfg_file = osp.join(osp.dirname(__file__), 'data/config/g.py')
with pytest.raises(KeyError): with pytest.raises(KeyError):
Config.fromfile(cfg_file) Config.fromfile(cfg_file)
def test_syntax_error():
temp_cfg_file = tempfile.NamedTemporaryFile(suffix='.py')
temp_cfg_path = temp_cfg_file.name
# write a file with syntax error
with open(temp_cfg_path, 'w') as f:
f.write('a=0b=dict(c=1)')
with pytest.raises(
SyntaxError,
match='There are syntax errors in config '
f'file {temp_cfg_path}'):
Config.fromfile(temp_cfg_path)
temp_cfg_file.close()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment