|
| 1 | +from contextlib import asynccontextmanager |
| 2 | +from urllib.parse import urljoin |
| 3 | +from functools import partial |
| 4 | +import datetime |
| 5 | +import aiofiles |
| 6 | +import json |
| 7 | +import re |
| 8 | +import os |
| 9 | + |
| 10 | +from fastmcp.exceptions import ToolError |
| 11 | +from flexmock import flexmock |
| 12 | + |
| 13 | +async def _get_transitions(): |
| 14 | + return {"transitions": [{"to": {"name": "In Progress"}, "id": 1}, {"to": {"name": "Closed"}, "id": 2}]} |
| 15 | + |
| 16 | + |
| 17 | +async def _get_verified_user(): |
| 18 | + return {"groups": {"items": [{"name": "Red Hat Employee"}]}} |
| 19 | + |
| 20 | + |
| 21 | +async def _get_unverified_user(): |
| 22 | + return {"groups": {"items": []}} |
| 23 | + |
| 24 | + |
| 25 | +async def _read_jira_mock(issue_key: str, remote_link = False) -> dict: |
| 26 | + try: |
| 27 | + async with aiofiles.open(f"{os.environ['JIRA_MOCK_FILES']}/{issue_key}", "r") as jira_file: |
| 28 | + if remote_link: |
| 29 | + return json.loads(await jira_file.read())["remote_links"] |
| 30 | + return json.loads(await jira_file.read()) |
| 31 | + except (FileNotFoundError, json.JSONDecodeError, IOError) as e: |
| 32 | + raise ToolError(f"Error while reading mock up Jira issue {e}") from e |
| 33 | + |
| 34 | + |
| 35 | +async def _write_jira_mock(issue_key: str, data: dict): |
| 36 | + try: |
| 37 | + async with aiofiles.open(f"{os.environ['JIRA_MOCK_FILES']}/{issue_key}", "w") as jira_file: |
| 38 | + await jira_file.write(json.dumps(data, indent=2)) |
| 39 | + except IOError as e: |
| 40 | + raise ToolError(f"Error while writing mock up Jira issue {e}") from e |
| 41 | + |
| 42 | + |
| 43 | +class aiohttpClientSessionMock: |
| 44 | + # mocking endpoint providing information about issue |
| 45 | + issue_get_regex = re.compile( |
| 46 | + re.escape(urljoin(os.getenv("JIRA_URL"), f"rest/api/2/issue"))+"/([A-Z0-9-]+)") |
| 47 | + # mocking endpoint providing available transitions |
| 48 | + transitions_get_regex = re.compile( |
| 49 | + re.escape(urljoin(os.getenv("JIRA_URL"), f"rest/api/2/issue"))+"/([A-Z0-9-]+)/transitions") |
| 50 | + # mocking endpoint providing remote links present in issues |
| 51 | + remote_link_get_regex = re.compile( |
| 52 | + re.escape(urljoin(os.getenv("JIRA_URL"), f"rest/api/2/issue"))+"/([A-Z0-9-]+)/remotelink") |
| 53 | + # mocking endpoint for posting comments |
| 54 | + comment_post_regex = re.compile( |
| 55 | + re.escape(urljoin(os.getenv("JIRA_URL"), f"rest/api/2/issue"))+"/([A-Z0-9-]+)/comment") |
| 56 | + # mocking endpoint for retrieval of information about users |
| 57 | + user_get_regex = re.compile( |
| 58 | + re.escape(urljoin(os.getenv("JIRA_URL"), f"rest/api/2/user"))) |
| 59 | + |
| 60 | + async def __aenter__(self): |
| 61 | + return self |
| 62 | + |
| 63 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 64 | + pass |
| 65 | + |
| 66 | + @asynccontextmanager |
| 67 | + async def get(self, *args, **kwargs): |
| 68 | + if match_data := self.issue_get_regex.fullmatch(args[0]): |
| 69 | + yield flexmock(raise_for_status=lambda: None, |
| 70 | + json=partial(_read_jira_mock, |
| 71 | + issue_key=match_data.group(1), |
| 72 | + remote_link = False)) |
| 73 | + elif match_data:= self.remote_link_get_regex.fullmatch(args[0]): |
| 74 | + yield flexmock(raise_for_status=lambda: None, |
| 75 | + json=partial(_read_jira_mock, |
| 76 | + issue_key=match_data.group(1)), |
| 77 | + remote_link=True) |
| 78 | + elif match_data:= self.transitions_get_regex.fullmatch(args[0]): |
| 79 | + yield flexmock(raise_for_status=lambda: None, |
| 80 | + json=_get_transitions) |
| 81 | + elif match_data:= self.user_get_regex.fullmatch(args[0]): |
| 82 | + if (kwargs["params"].get("key") == "verified_user" or |
| 83 | + kwargs["params"].get("accountId") == "verified_user"): |
| 84 | + yield flexmock(raise_for_status=lambda: None, |
| 85 | + json=_get_verified_user) |
| 86 | + yield flexmock(raise_for_status=lambda: None, |
| 87 | + json=_get_unverified_user) |
| 88 | + else: |
| 89 | + raise NotImplementedError() |
| 90 | + |
| 91 | + @asynccontextmanager |
| 92 | + async def put(self, *args, **kwargs): |
| 93 | + if match_data := self.issue_get_regex.fullmatch(args[0]): |
| 94 | + issue_data = await _read_jira_mock(match_data.group(1), remote_link=False) |
| 95 | + if "fields" in kwargs["json"]: |
| 96 | + issue_data["fields"].update(kwargs["json"]["fields"]) |
| 97 | + elif "update" in kwargs["json"]: |
| 98 | + current_labels = set(issue_data["fields"]["labels"]) |
| 99 | + labels_to_add = [action_dict["add"] for action_dict |
| 100 | + in kwargs["json"]["update"]["labels"] |
| 101 | + if "add" in action_dict] |
| 102 | + labels_to_remove = [action_dict["remove"] for action_dict |
| 103 | + in kwargs["json"]["update"]["labels"] |
| 104 | + if "remove" in action_dict] |
| 105 | + if labels_to_remove: |
| 106 | + current_labels.difference_update(labels_to_remove) |
| 107 | + if labels_to_add: |
| 108 | + current_labels.update(labels_to_add) |
| 109 | + issue_data["fields"]["labels"] = list(current_labels) |
| 110 | + else: |
| 111 | + raise NotImplementedError() |
| 112 | + await _write_jira_mock(match_data.group(1), issue_data) |
| 113 | + yield flexmock(raise_for_status=lambda: None) |
| 114 | + else: |
| 115 | + raise NotImplementedError() |
| 116 | + |
| 117 | + @asynccontextmanager |
| 118 | + async def post(self, *args, **kwargs): |
| 119 | + if match_data := self.comment_post_regex.fullmatch(args[0]): |
| 120 | + current_issue = await _read_jira_mock(match_data.group(1)) |
| 121 | + comment_dict = kwargs["json"] |
| 122 | + comment_dict["created"] = datetime.datetime.now(datetime.timezone.utc).isoformat() |
| 123 | + comment_dict["updated"] = datetime.datetime.now(datetime.timezone.utc).isoformat() |
| 124 | + comment_dict["author"] = {"name": "jotnar-project", |
| 125 | + "key": "JIRAUSER288184", |
| 126 | + "displayName": "Jotnar Project"} |
| 127 | + current_issue["fields"]["comment"]["comments"].append(comment_dict) |
| 128 | + current_issue["fields"]["comment"]["maxResults"] += 1 |
| 129 | + current_issue["fields"]["comment"]["total"] += 1 |
| 130 | + await _write_jira_mock(match_data.group(1), current_issue) |
| 131 | + yield flexmock(raise_for_status=lambda: None) |
| 132 | + elif match_data := self.transitions_get_regex.fullmatch(args[0]): |
| 133 | + jira_data = await _read_jira_mock(match_data.group(1)) |
| 134 | + if kwargs["json"]["transition"]["id"] == 1: |
| 135 | + jira_data["fields"]["status"] = {"name": "In Progress"} |
| 136 | + jira_data["fields"]["status"]["description"] = "Work has started" |
| 137 | + elif kwargs["json"]["transition"]["id"] == 2: |
| 138 | + jira_data["fields"]["status"] = {"name": "Closed"} |
| 139 | + jira_data["fields"]["status"]["description"] = "The issue is closed. See the" \ |
| 140 | + "resolution for context regarding why" \ |
| 141 | + "(for example Done, Abandoned, Duplicate, etc)" |
| 142 | + else: |
| 143 | + raise NotImplementedError() |
| 144 | + await _write_jira_mock(match_data.group(1), jira_data) |
| 145 | + yield flexmock(raise_for_status=lambda: None) |
| 146 | + else: |
| 147 | + raise NotImplementedError() |
0 commit comments