From 2106585d4c9b343c3d554a480f7e535386599949 Mon Sep 17 00:00:00 2001 From: enkore Date: Wed, 23 Oct 2013 17:13:38 +0200 Subject: [PATCH] ClassFinder: fixed unexpected behaviour, add tests for this --- i3pystatus/core/imputil.py | 9 +++++---- tests/test_core_util.py | 22 ++++++++++++++++++++-- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/i3pystatus/core/imputil.py b/i3pystatus/core/imputil.py index 8fe36a6..4315afe 100644 --- a/i3pystatus/core/imputil.py +++ b/i3pystatus/core/imputil.py @@ -5,7 +5,6 @@ from i3pystatus.core.exceptions import ConfigAmbigiousClassesError, ConfigInvali class ClassFinder: - """Support class to find classes of specific bases in a module""" def __init__(self, baseclass): @@ -20,11 +19,13 @@ class ClassFinder: ) return predicate - def search_module(self, module): - return list(zip(*inspect.getmembers(module, self.predicate_factory(module))))[1] + def get_matching_classes(self, module): + # Transpose [ (name, list), ... ] to ( [name, ...], [list, ...] ) + classes = list(zip(*inspect.getmembers(module, self.predicate_factory(module)))) + return classes[1] if classes else [] def get_class(self, module): - classes = self.search_module(module) + classes = self.get_matching_classes(module) if len(classes) > 1: # If there are multiple Module clases bundled in one module, diff --git a/tests/test_core_util.py b/tests/test_core_util.py index 69aa828..d88c0b8 100644 --- a/tests/test_core_util.py +++ b/tests/test_core_util.py @@ -6,7 +6,8 @@ import string import random import types -from i3pystatus.core import util +from i3pystatus.core.exceptions import ConfigAmbigiousClassesError, ConfigInvalidModuleError +from i3pystatus.core import util, ClassFinder def get_random_string(length=6, chars=string.printable): @@ -170,12 +171,29 @@ class ModuleListTests(unittest.TestCase): pymod.some_class = self._create_module_class("some_class") pymod.some_class.__module__ = "other_module" - with self.assertRaises(IndexError): + with self.assertRaises(ConfigInvalidModuleError): self.ml.append(pymod) assert not pymod.some_class.__init__.called assert not pymod.some_class.registered.called + def test_ambigious_classdef(self): + pymod = types.ModuleType("test_mod") + pymod.some_class = self._create_module_class("some_class") + pymod.some_class.__module__ = "test_mod" + pymod.some_other_class = self._create_module_class("some_other_class") + pymod.some_other_class.__module__ = "test_mod" + + with self.assertRaises(ConfigAmbigiousClassesError): + self.ml.append(pymod) + + def test_invalid_module(self): + pymod = types.ModuleType("test_mod") + + with self.assertRaises(ConfigInvalidModuleError): + self.ml.append(pymod) + + def test_append_class_inheritance(self): in_between = self._create_module_class("in_between") cls = self._create_module_class("cls", (in_between,))