def test_nested_getattr_multi_level(): class Obj(object): class foo(object): # noqa class bar(object): # noqa lol = 'heh' assert nested_getattr(Obj, 'foo.bar.lol') == 'heh' assert nested_getattr(Obj, ['foo', 'bar', 'lol']) == 'heh'
def test_nested_getattr_multi_level(): class Obj: class foo: # noqa class bar: # noqa lol = "heh" assert nested_getattr(Obj, "foo.bar.lol") == "heh" assert nested_getattr(Obj, ["foo", "bar", "lol"]) == "heh"
def test_nested_getattr_wrong_type(): with pytest.raises(TypeError): nested_getattr(object(), 654)
def test_nested_getattr_single_level(): class Obj(object): x = 1 assert nested_getattr(Obj, 'x') == 1 assert nested_getattr(Obj, ['x']) == 1
def test_nested_getattr_empty(): with pytest.raises(ValueError): nested_getattr(object(), '')
def __get__(self, o, t): if o is None: return self condition_arg_cache = {} for condition, cls_or_descriptor in self.registered_views: if not callable(condition): # Compare it to a known value (if present) if self.reference is None: # No reference to check against raise TypeError( 'reference= not set so you cannot use non-callables as conditions' ) else: if self.reference not in condition_arg_cache: try: ref_o = nested_getattr(o, self.reference) if isinstance(ref_o, Widget): ref_value = ref_o.read() else: ref_value = ref_o condition_arg_cache[self.reference] = ref_value except AttributeError: raise TypeError( 'Wrong widget name specified as reference=: {}' .format(self.reference)) except NoSuchElementException: if self.ignore_bad_reference: # reference is not displayed? We are probably aware of this so skip. continue else: raise if condition == condition_arg_cache[self.reference]: view_object = cls_or_descriptor break else: # Parse the callable's args and inject the correct args c_args, c_varargs, c_keywords, c_defaults = inspect.getargspec( condition) if c_varargs or c_keywords or c_defaults: raise TypeError( 'You can only use simple arguments in lambda conditions' ) arg_values = [] for arg in c_args: if arg not in condition_arg_cache: try: condition_arg_cache[arg] = getattr(o, arg).read() except AttributeError: raise TypeError( 'Wrong widget name specified as parameter {}'. format(arg)) arg_values.append(condition_arg_cache[arg]) if condition(*arg_values): view_object = cls_or_descriptor break else: if self.default_view is not None: view_object = self.default_view else: raise ValueError( 'Could not find a corresponding registered view.') if inspect.isclass(view_object): view_class = view_object else: view_class = type(view_object) o.logger.info('Picked %s', view_class.__name__) if isinstance(view_object, Widgetable): # We init the widget descriptor here return view_object.__get__(o, t) else: return view_object(o, additional_context=o.context)
def test_nested_getattr_single_level(): class Obj: x = 1 assert nested_getattr(Obj, "x") == 1 assert nested_getattr(Obj, ["x"]) == 1