diff --git a/vmware_nsxlib/tests/unit/v3/test_resources.py b/vmware_nsxlib/tests/unit/v3/test_resources.py index ef5942ea..08764c84 100644 --- a/vmware_nsxlib/tests/unit/v3/test_resources.py +++ b/vmware_nsxlib/tests/unit/v3/test_resources.py @@ -1135,6 +1135,30 @@ class TestNsxSearch(nsxlib_testcase.NsxClientTestCase): self.nsxlib.search_by_tags(tags=user_tags) search.assert_called_with('search?query=%s' % query) + def test_nsx_search_tags_scope_only(self): + """Test search of resources with the specified tag.""" + with mock.patch.object(self.nsxlib.client, 'url_get') as search: + user_tags = [{'scope': 'user'}] + query = self.nsxlib._build_query(tags=user_tags) + self.nsxlib.search_by_tags(tags=user_tags) + search.assert_called_with('search?query=%s' % query) + + def test_nsx_search_tags_tag_only(self): + """Test search of resources with the specified tag.""" + with mock.patch.object(self.nsxlib.client, 'url_get') as search: + user_tags = [{'tag': 'k8s'}] + query = self.nsxlib._build_query(tags=user_tags) + self.nsxlib.search_by_tags(tags=user_tags) + search.assert_called_with('search?query=%s' % query) + + def test_nsx_search_tags_tag_and_scope(self): + """Test search of resources with the specified tag.""" + with mock.patch.object(self.nsxlib.client, 'url_get') as search: + user_tags = [{'tag': 'k8s'}, {'scope': 'user'}] + query = self.nsxlib._build_query(tags=user_tags) + self.nsxlib.search_by_tags(tags=user_tags) + search.assert_called_with('search?query=%s' % query) + def test_nsx_search_tags_and_resource_type(self): """Test search of specified resource with the specified tag.""" with mock.patch.object(self.nsxlib.client, 'url_get') as search: diff --git a/vmware_nsxlib/v3/__init__.py b/vmware_nsxlib/v3/__init__.py index 5a34d3f3..239eac99 100644 --- a/vmware_nsxlib/v3/__init__.py +++ b/vmware_nsxlib/v3/__init__.py @@ -188,13 +188,22 @@ class NsxLibBase(object): operation=msg, details='') - def _build_query(self, tags): - try: - return " AND ".join(['tags.scope:%(scope)s AND ' - 'tags.tag:%(tag)s' % item for item in tags]) - except KeyError as e: - reason = _('Missing key:%s in tags') % str(e) + def _build_tag_query(self, tag): + # Validate that the correct keys are used + if set(tag.keys()) - set(('scope', 'tag')): + reason = _("Only 'scope' and 'tag' keys are supported") raise exceptions.NsxSearchInvalidQuery(reason=reason) + _scope = tag.get('scope') + _tag = tag.get('tag') + if _scope and _tag: + return 'tags.scope:%s AND tags.tag:%s' % (_scope, _tag) + elif _scope: + return 'tags.scope:%s' % _scope + else: + return 'tags.tag:%s' % _tag + + def _build_query(self, tags): + return " AND ".join([self._build_tag_query(item) for item in tags]) def get_tag_limits(self): try: