diff --git a/pillar/api/projects/utils.py b/pillar/api/projects/utils.py index 1a8c74b1..7ae591b1 100644 --- a/pillar/api/projects/utils.py +++ b/pillar/api/projects/utils.py @@ -1,10 +1,10 @@ import logging from bson import ObjectId -from flask import current_app from werkzeug import exceptions as wz_exceptions from werkzeug.exceptions import abort +from pillar import current_app from pillar.auth import current_user log = logging.getLogger(__name__) @@ -133,3 +133,14 @@ def get_node_type(project, node_type_name): return next((nt for nt in project['node_types'] if nt['name'] == node_type_name), None) + + +def project_id(project_url: str) -> ObjectId: + """Returns the object ID, or raises a ValueError when not found.""" + + proj_coll = current_app.db('projects') + proj = proj_coll.find_one({'url': project_url}, projection={'_id': True}) + + if not proj: + raise ValueError(f'project with url={project_url!r} not found') + return proj['_id'] diff --git a/tests/test_api/test_project_utils.py b/tests/test_api/test_project_utils.py new file mode 100644 index 00000000..546ddad8 --- /dev/null +++ b/tests/test_api/test_project_utils.py @@ -0,0 +1,29 @@ +# -*- encoding: utf-8 -*- + +"""Unit tests for pillar.api.project.utils.""" + +import logging + +from bson import ObjectId +from pillar.tests import AbstractPillarTest + +log = logging.getLogger(__name__) + + +class ProjectUtilsTest(AbstractPillarTest): + def test_project_id_from_url(self): + self.enter_app_context() + + self.ensure_project_exists({'_id': ObjectId(24 * 'a'), 'url': 'project1'}) + self.ensure_project_exists({'_id': ObjectId(24 * 'b'), 'url': 'project2'}) + self.ensure_project_exists({'_id': ObjectId(24 * 'c'), 'url': 'project3'}) + + from pillar.api.projects.utils import project_id + + pid1 = project_id('project1') + pid2 = project_id('project2') + pid3 = project_id('project3') + + self.assertEqual(ObjectId(24 * 'a'), pid1) + self.assertEqual(ObjectId(24 * 'b'), pid2) + self.assertEqual(ObjectId(24 * 'c'), pid3)