Skip to content

Commit

Permalink
Merge pull request #1358 from anarkiwi/master
Browse files Browse the repository at this point in the history
 Check for duplicate YAML keys.
  • Loading branch information
anarkiwi committed Dec 4, 2017
2 parents 1582fbf + 73de1c2 commit 53ff3b6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
18 changes: 16 additions & 2 deletions faucet/config_parser_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,20 @@
import os
# pytype: disable=pyi-error
import yaml
from yaml.constructor import ConstructorError


def no_duplicates_constructor(loader, node, deep=False):
"""Check for duplicate YAML keys."""
keys = set()
for key_node, _ in node.value:
key = loader.construct_object(key_node, deep=deep)
if key in keys:
raise ConstructorError('duplicate key %s' % key)
keys.add(key)
return loader.construct_mapping(node, deep)

yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, no_duplicates_constructor)


def get_logger(logname):
Expand All @@ -33,8 +47,8 @@ def read_config(config_file, logname):
logger = get_logger(logname)
try:
with open(config_file, 'r') as stream:
conf = yaml.safe_load(stream)
except (yaml.YAMLError, UnicodeDecodeError, PermissionError) as err:
conf = yaml.load(stream.read())
except (yaml.YAMLError, UnicodeDecodeError, PermissionError) as err: # pytype: disable=name-error
logger.error('Error in file %s (%s)', config_file, str(err))
return None
return conf
Expand Down
19 changes: 19 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,25 @@ def test_invalid_dp_conf(self):
"""
self.check_config_failure(config, cp.dp_parser)

def test_duplicate_keys_conf(self):
"""Test duplicate top level keys."""
config = """
vlans:
office:
vid: 100
vlans:
office:
vid: 100
dps:
sw1:
dp_id: 0x1
interfaces:
testing:
number: 1
native_vlan: office
"""
self.check_config_failure(config, cp.dp_parser)


if __name__ == "__main__":
unittest.main()

0 comments on commit 53ff3b6

Please sign in to comment.