From 801ed2fea3b231498f616ae0cd8425a6a6624044 Mon Sep 17 00:00:00 2001 From: Federico Ressi Date: Tue, 20 Jul 2021 14:57:05 +0200 Subject: [PATCH] Allow to select objects using regular expressions Change-Id: I39d644f9244cfea1fbc50a354a9cc5cfe1e8be9c --- tobiko/common/_select.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/tobiko/common/_select.py b/tobiko/common/_select.py index 219b0422a..978f0a4bc 100644 --- a/tobiko/common/_select.py +++ b/tobiko/common/_select.py @@ -13,6 +13,7 @@ # under the License. from __future__ import absolute_import +import re import typing from tobiko import _exception @@ -88,8 +89,8 @@ def equal_attributes(obj, attributes: typing.Dict[str, typing.Any], inverse=False) \ -> bool: - for key, value in attributes.items(): - matching = value == getattr(obj, key) + for key, matcher in attributes.items(): + matching = match(matcher, getattr(obj, key)) if matching is inverse: return False return True @@ -98,13 +99,23 @@ def equal_attributes(obj, def equal_items(obj: typing.Dict, items: typing.Dict, inverse=False) -> bool: - for key, value in items.items(): - matching = value == obj[key] + for key, matcher in items.items(): + matching = match(matcher, obj[key]) if matching is inverse: return False return True +PatternType = type(re.compile("", 0)) + + +def match(matcher: typing.Any, value: typing.Any) -> bool: + if isinstance(matcher, PatternType): + return matcher.match(value) is not None + else: + return matcher == value + + class ObjectNotFound(_exception.TobikoException): message = "Object not found"