From 2468e520fa999e74a3476745b6655b8ea5728cb4 Mon Sep 17 00:00:00 2001 From: Lukas Rychtecky Date: Thu, 5 Jan 2017 21:22:26 +0100 Subject: [PATCH] Added tests for get_class_method --- chamber/utils/__init__.py | 12 ++++--- .../apps/test_chamber/tests/utils/__init__.py | 31 ++++++++++++++++++- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/chamber/utils/__init__.py b/chamber/utils/__init__.py index b873b0e..5185bbf 100644 --- a/chamber/utils/__init__.py +++ b/chamber/utils/__init__.py @@ -7,14 +7,18 @@ def remove_accent(string_with_diacritics): - "Removes a diacritics from a given string" + """ + Removes a diacritics from a given string" + """ return unicodedata.normalize('NFKD', string_with_diacritics).encode('ASCII', 'ignore').decode('ASCII') def get_class_method(cls_or_inst, method_name): - cls = cls_or_inst - if not isinstance(cls, type): - cls = cls_or_inst.__class__ + """ + Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with + properties and cached properties. + """ + cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__ meth = getattr(cls, method_name, None) if isinstance(meth, property): meth = meth.fget diff --git a/example/dj/apps/test_chamber/tests/utils/__init__.py b/example/dj/apps/test_chamber/tests/utils/__init__.py index a992982..16e76d6 100644 --- a/example/dj/apps/test_chamber/tests/utils/__init__.py +++ b/example/dj/apps/test_chamber/tests/utils/__init__.py @@ -4,14 +4,43 @@ from .datastructures import * # NOQA from .decorators import * # NOQA +from django.utils.functional import cached_property from django.test import TestCase -from chamber.utils import remove_accent +from chamber.utils import remove_accent, get_class_method +from germanium.anotations import data_provider from germanium.tools import assert_equal +class TestClass(object): + + def method(self): + pass + + @property + def property_method(self): + pass + + @cached_property + def cached_property_method(self): + pass + + class UtilsTestCase(TestCase): def test_should_remove_accent_from_string(self): assert_equal('escrzyaie', remove_accent('ěščřžýáíé')) + + classes_and_method_names = [ + [TestClass.method, TestClass, 'method'], + [TestClass.method, TestClass(), 'method'], + [TestClass.property_method.fget, TestClass, 'property_method'], + [TestClass.property_method.fget, TestClass(), 'property_method'], + [TestClass.cached_property_method.func, TestClass, 'cached_property_method'], + [TestClass.cached_property_method.func, TestClass(), 'cached_property_method'], + ] + + @data_provider(classes_and_method_names) + def test_should_return_class_method(self, expected_method, cls_or_inst, method_name): + assert_equal(expected_method, get_class_method(cls_or_inst, method_name))