From ce20f5b6875e8d04d57682408e084e182d8288cd Mon Sep 17 00:00:00 2001 From: Philipp Gesang Date: Mon, 5 Nov 2018 09:58:43 +0100 Subject: [PATCH] validate SimpleCnf inputs The cnfvar functions cannot handle ``tuple'' inputs since the inputs are variable length. Make simple_cnf pass a list instead and reject non-list inputs in the ctor. --- src/simple_cnf.py | 12 +++++++----- test/test_simple_cnf.py | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/simple_cnf.py b/src/simple_cnf.py index 96dc5b2..23b5ca4 100644 --- a/src/simple_cnf.py +++ b/src/simple_cnf.py @@ -237,14 +237,16 @@ class SimpleCnf(object): Creates a simple configuration. :param cnf: initial set of conf var data (default: None = empty conf) - :type cnf: list or tuple or anything that :py:func:`get_cnf` can read + :type cnf: list or anything that :py:func:`get_cnf` can read """ - if isinstance(cnf, (list, tuple)): + if cnf is None: + self.__cnfvars = [] + elif isinstance(cnf, list): self.__cnfvars = cnf - elif cnf is not None: + elif isinstance(cnf, dict): self.__cnfvars = get_cnf(cnf) else: - self.__cnfvars = [] + raise InvalidCnf ("cannot handle %s type inputs" % type (cnf)) def _find_new_number(self, cnf_vars): """Recursive helper function to find new unique (line) number.""" @@ -579,7 +581,7 @@ class SimpleCnf(object): else: line_test = lambda test_val: test_val['number'] == line - return SimpleCnf(tuple(entry for entry in self.__cnfvars + return SimpleCnf(list(entry for entry in self.__cnfvars if name_test(entry) and value_test(entry) and instance_test(entry) and line_test(entry))) diff --git a/test/test_simple_cnf.py b/test/test_simple_cnf.py index 92ef9e7..bdc9883 100755 --- a/test/test_simple_cnf.py +++ b/test/test_simple_cnf.py @@ -28,6 +28,7 @@ import os import sys from src.simple_cnf import SimpleCnf +from src.simple_cnf import InvalidCnf TEST_SET = """ 1 USER,1: "admin" @@ -163,6 +164,29 @@ class SimpleCnfTest(unittest.TestCase): # tests + def test_ctor_ok (self): + """ + Test initializer :py:meth:`SimpleCnf.__init__` must succeed on sane + inputs. + """ + self.assertNotEqual (SimpleCnf ({"cnf": []}), None) + self.assertNotEqual (SimpleCnf ([]), None) + self.assertNotEqual (SimpleCnf (), None) + + def test_ctor_fail (self): + """ + Test initializer :py:meth:`SimpleCnf.__init__` must reject inputs that + ``cnfvar.py`` does not handle. + """ + with self.assertRaises (InvalidCnf): + _void = SimpleCnf (b"junk") + with self.assertRaises (InvalidCnf): + _void = SimpleCnf (42) + with self.assertRaises (InvalidCnf): + _void = SimpleCnf (tuple ([1701, 1337])) + with self.assertRaises (InvalidCnf): + _void = SimpleCnf (set (["one", "two"])) + def test_eq(self): """ test method :py:meth:`SimpleCnf.__eq__` """ self.assertEqual(self.cnf[61], self.cnf[61]) -- 1.7.1