nydok 0.0.1a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of nydok might be problematic. Click here for more details.

nydok-0.0.1a1/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2023 Nykode Therapeutics
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
nydok-0.0.1a1/PKG-INFO ADDED
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: nydok
3
+ Version: 0.0.1a1
4
+ Summary: Documentation and specification testing framework
5
+ License: MIT
6
+ Author: Nykode Therapeutics
7
+ Author-email: insaid@nykode.com
8
+ Requires-Python: >=3.8,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Requires-Dist: PyYAML (>=6.0,<7.0)
16
+ Requires-Dist: click (>=8.1.3,<9.0.0)
17
+ Requires-Dist: lxml (>=4.9.1,<5.0.0)
18
+ Requires-Dist: pytest (>=6.2.3,<7.0.0)
19
+ Requires-Dist: requests (>=2.28.1,<3.0.0)
@@ -0,0 +1 @@
1
+ from .plugin.testcase import testcase # noqa: F401
@@ -0,0 +1,219 @@
1
+ import json
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import click
6
+
7
+ from .report import (
8
+ create_codereview_report,
9
+ create_pipeline_logs_report,
10
+ create_risk_report,
11
+ create_test_overview_report,
12
+ create_test_case_report,
13
+ create_traceability_matrix,
14
+ )
15
+ from .schema import Requirement, RiskAssessment, TestCase
16
+
17
+
18
+ @click.group()
19
+ def cli():
20
+ pass
21
+
22
+
23
+ @cli.group()
24
+ def report():
25
+ pass
26
+
27
+
28
+ def _load_json(path: Path):
29
+ data = json.loads(path.read_text())
30
+ return {
31
+ "test_cases": {_id: TestCase(**test_case) for _id, test_case in data["test_cases"].items()},
32
+ "requirements": {
33
+ _id: Requirement(**requirement) for _id, requirement in data["requirements"].items()
34
+ },
35
+ "risk_assessments": {
36
+ _id: RiskAssessment.from_dict(_id, risk_assessment)
37
+ for _id, risk_assessment in data["risk_assessments"].items()
38
+ },
39
+ }
40
+
41
+
42
+ @report.command(help="Create traceability matrix.")
43
+ @click.argument("result", type=click.Path(exists=True))
44
+ @click.option("--base-prefix", type=str, help="Prefix to use as basis (filter).")
45
+ @click.option(
46
+ "--categories",
47
+ type=str,
48
+ help="Categories for traceability (title,prefix). Repeat for multiple.",
49
+ )
50
+ @click.option(
51
+ "--output",
52
+ "-o",
53
+ type=click.Path(writable=True),
54
+ default="-",
55
+ help="Output path (default: stdout).",
56
+ )
57
+ def traceability_matrix(result, base_prefix, categories, output):
58
+
59
+ if categories:
60
+ assert len(categories.split(",")) % 2 == 0, "Categories must be in pairs."
61
+ categories = list(zip(categories.split(",")[::2], categories.split(",")[1::2]))
62
+
63
+ data = _load_json(Path(result))
64
+ report = create_traceability_matrix(
65
+ data["requirements"].values(),
66
+ data["test_cases"].values(),
67
+ base_prefix=base_prefix,
68
+ categories=categories,
69
+ )
70
+ if output == "-":
71
+ sys.stdout.write(report + "\n")
72
+ else:
73
+ Path(output).write_text(report)
74
+
75
+
76
+ @report.command(help="Create risk assessment tables.")
77
+ @click.argument("result", type=click.Path(exists=True))
78
+ @click.option(
79
+ "--output",
80
+ "-o",
81
+ type=click.Path(writable=True),
82
+ default="-",
83
+ help="Output path (default: stdout).",
84
+ )
85
+ def risk_assessment(result, output):
86
+
87
+ data = _load_json(Path(result))
88
+ report = create_risk_report(data["risk_assessments"])
89
+
90
+ if output == "-":
91
+ sys.stdout.write(report)
92
+ else:
93
+ Path(output).write_text(report)
94
+
95
+
96
+ @report.command(help="Create test overview table.")
97
+ @click.argument("result", type=click.Path(exists=True))
98
+ @click.option(
99
+ "--output",
100
+ "-o",
101
+ type=click.Path(writable=True),
102
+ default="-",
103
+ help="Output path (default: stdout).",
104
+ )
105
+ def test_overview(result, output):
106
+
107
+ data = _load_json(Path(result))
108
+ report = create_test_overview_report(
109
+ data["requirements"].values(),
110
+ data["test_cases"].values(),
111
+ )
112
+ if output == "-":
113
+ sys.stdout.write(report)
114
+ else:
115
+ Path(output).write_text(report)
116
+
117
+
118
+ @report.command(help="Create test case report.")
119
+ @click.argument("result", type=click.Path(exists=True))
120
+ @click.option(
121
+ "--output",
122
+ "-o",
123
+ type=click.Path(writable=True),
124
+ default="-",
125
+ help="Output path (default: stdout).",
126
+ )
127
+ def test_cases(result, output):
128
+
129
+ data = _load_json(Path(result))
130
+ report = create_test_case_report(
131
+ data["requirements"].values(),
132
+ data["test_cases"].values(),
133
+ )
134
+ if output == "-":
135
+ sys.stdout.write(report)
136
+ else:
137
+ Path(output).write_text(report)
138
+
139
+
140
+ @report.command(help="Create code review table.")
141
+ @click.option(
142
+ "--repo-path",
143
+ "-r",
144
+ type=str,
145
+ required=True,
146
+ help="Gitlab repository path. E.g. my-group/my-project.",
147
+ )
148
+ @click.option(
149
+ "--to-ref",
150
+ "-c",
151
+ type=str,
152
+ default="main",
153
+ help="Git ref for end of commit range. Default is default branch configured for repository.",
154
+ )
155
+ @click.option(
156
+ "--from-ref",
157
+ "-f",
158
+ type=str,
159
+ help="Git ref for start of commit range. Default is all history.",
160
+ )
161
+ @click.option(
162
+ "--output",
163
+ "-o",
164
+ type=click.Path(writable=True),
165
+ default="-",
166
+ help="Output path (default: stdout).",
167
+ )
168
+ def code_review(repo_path, to_ref, from_ref, output):
169
+
170
+ report = create_codereview_report(
171
+ repo_path=repo_path,
172
+ to_ref=to_ref,
173
+ from_ref=from_ref,
174
+ )
175
+ if output == "-":
176
+ sys.stdout.write(report)
177
+ else:
178
+ Path(output).write_text(report)
179
+
180
+
181
+ @report.command(help="Create pipeline logs report.")
182
+ @click.option(
183
+ "--repo-path",
184
+ "-r",
185
+ type=str,
186
+ required=True,
187
+ help="Gitlab repository path. E.g. my-group/my-project.",
188
+ )
189
+ @click.option(
190
+ "--pipeline-id",
191
+ "-p",
192
+ type=click.INT,
193
+ required=True,
194
+ help="Pipeline ID in Gitlab from which to retrieve job logs.",
195
+ )
196
+ @click.option(
197
+ "--job-names",
198
+ "-j",
199
+ type=str,
200
+ help="Job names in pipeline for only including certain jobs. Default is all jobs.",
201
+ )
202
+ @click.option(
203
+ "--output",
204
+ "-o",
205
+ type=click.Path(writable=True),
206
+ default="-",
207
+ help="Output path (default: stdout).",
208
+ )
209
+ def pipeline_logs(repo_path, pipeline_id, job_names, output):
210
+
211
+ job_names = job_names.split(",") if job_names else None
212
+
213
+ report = create_pipeline_logs_report(
214
+ repo_path=repo_path, pipeline_id=pipeline_id, job_names=job_names
215
+ )
216
+ if output == "-":
217
+ sys.stdout.write(report)
218
+ else:
219
+ Path(output).write_text(report)
@@ -0,0 +1,14 @@
1
+ class DuplicateRequirementException(Exception):
2
+ ...
3
+
4
+
5
+ class FailedTestCaseException(Exception):
6
+ ...
7
+
8
+
9
+ class MissingTestCaseException(Exception):
10
+ ...
11
+
12
+
13
+ class RiskPriorityExceedsThresholdException(Exception):
14
+ ...
@@ -0,0 +1,137 @@
1
+ import os
2
+ from typing import Any, Dict, List, Optional
3
+ from urllib.parse import quote_plus
4
+
5
+ import requests # type: ignore
6
+
7
+
8
+ def get_api_url() -> str:
9
+ if not os.environ.get("GITLAB_URL"):
10
+ raise RuntimeError("Environment variable GITLAB_URL is required, but not set")
11
+ return os.environ["GITLAB_URL"] + "/api/v4"
12
+
13
+
14
+ def get_graphql_url() -> str:
15
+ return os.environ["GITLAB_URL"] + "/api/graphql"
16
+
17
+
18
+ def get_gitlab_token() -> str:
19
+ if not os.environ.get("GITLAB_TOKEN"):
20
+ raise RuntimeError("Environment variable GITLAB_TOKEN is required, but not set")
21
+ return os.environ["GITLAB_TOKEN"]
22
+
23
+
24
+ def _get_paginated_results(url: str, params: Dict[str, Any]) -> List[Any]:
25
+
26
+ params = dict(params)
27
+ params.setdefault("per_page", 100)
28
+
29
+ def _get_results(next_page: Optional[str] = None):
30
+ fetch_url = next_page if next_page else url
31
+ resp = requests.get(
32
+ fetch_url,
33
+ params=params,
34
+ headers={"Authorization": f"Bearer {get_gitlab_token()}"},
35
+ )
36
+ assert (
37
+ resp.status_code == 200
38
+ ), f"Resource {fetch_url} returned status code {resp.status_code}.\n{resp.text}"
39
+
40
+ return resp.json(), resp.links.get("next", {}).get("url")
41
+
42
+ api_results, next_page = _get_results()
43
+ while next_page:
44
+ next_jobs, next_page = _get_results(next_page)
45
+ api_results.extend(next_jobs)
46
+ return api_results
47
+
48
+
49
+ def get_commit_for_tag(repo_path: str, tag: str) -> str:
50
+ url_encoded_repo_path = quote_plus(repo_path)
51
+
52
+ fetch_url = get_api_url() + f"/projects/{url_encoded_repo_path}/repository/tags/{tag}"
53
+ resp = requests.get(
54
+ fetch_url,
55
+ headers={"Authorization": f"Bearer {get_gitlab_token()}"},
56
+ )
57
+ assert (
58
+ resp.status_code == 200
59
+ ), f"Resource {fetch_url} returned status code {resp.status_code}.\n{resp.text}"
60
+ return resp.json()["commit"]["id"]
61
+
62
+
63
+ def get_commits_for_ref(
64
+ repo_path: str, to_ref: Optional[str] = None, from_ref: Optional[str] = None
65
+ ) -> List[str]:
66
+ """Fetches all commit ids for given branch"""
67
+
68
+ url_encoded_repo_path = quote_plus(repo_path)
69
+
70
+ params = {}
71
+ if from_ref or to_ref:
72
+ from_ref = from_ref or ""
73
+ to_ref = to_ref or ""
74
+ params["ref_name"] = f"{from_ref}...{to_ref}"
75
+
76
+ api_commits = _get_paginated_results(
77
+ get_api_url() + f"/projects/{url_encoded_repo_path}/repository/commits",
78
+ {"ref_name": f"{from_ref}...{to_ref}" if from_ref else to_ref},
79
+ )
80
+
81
+ commits = [c["id"] for c in api_commits]
82
+ return commits
83
+
84
+
85
+ def fetch_mergerequests(repo_path: str) -> List[Dict[str, str]]:
86
+
87
+ url_encoded_repo_path = quote_plus(repo_path)
88
+
89
+ api_mrs = _get_paginated_results(
90
+ get_api_url() + f"/projects/{url_encoded_repo_path}/merge_requests",
91
+ {
92
+ "state": "merged",
93
+ },
94
+ )
95
+
96
+ merge_requests = []
97
+ for mr in api_mrs:
98
+ merge_requests.append(
99
+ {
100
+ "merge_commit_sha": mr["merge_commit_sha"],
101
+ "title": mr["title"],
102
+ "merged_at": mr["merged_at"],
103
+ "author": mr["author"]["name"],
104
+ "approved_by": ",".join(sorted(r["name"] for r in mr["reviewers"])),
105
+ }
106
+ )
107
+ return merge_requests
108
+
109
+
110
+ def get_pipeline_logs(
111
+ repo_path: str, pipeline_id: int, job_names: Optional[List[str]] = None
112
+ ) -> Dict[str, str]:
113
+
114
+ url_encoded_repo_path = quote_plus(repo_path)
115
+
116
+ api_jobs = _get_paginated_results(
117
+ get_api_url() + f"/projects/{url_encoded_repo_path}/pipelines/{str(pipeline_id)}/jobs",
118
+ {
119
+ "scope": ["failed", "success"],
120
+ },
121
+ )
122
+
123
+ logs: Dict[str, str] = {}
124
+ for job in api_jobs:
125
+ if job_names and job["name"] not in job_names:
126
+ continue
127
+
128
+ resp = requests.get(
129
+ get_api_url() + f"/projects/{url_encoded_repo_path}/jobs/{str(job['id'])}/trace",
130
+ headers={"Authorization": f"Bearer {get_gitlab_token()}"},
131
+ )
132
+ if resp.status_code != 200:
133
+ raise RuntimeError(f"Failed to obtain log for job {job['id']}")
134
+
135
+ logs[job["name"]] = resp.text
136
+
137
+ return logs
@@ -0,0 +1 @@
1
+ from .markdown_nydok import NydokExtension as nydok # noqa: F401
@@ -0,0 +1,65 @@
1
+ import re
2
+ import xml.etree.ElementTree as etree
3
+
4
+ from markdown.blockprocessors import BlockProcessor
5
+ from markdown.extensions import Extension
6
+
7
+
8
+ class NydokRequirementProcessor(BlockProcessor):
9
+ """Process nydok requirements in format:
10
+
11
+ - FR001 [UR001]: The system must be able to do something
12
+ """
13
+
14
+ REQ_PATTERN = r"- (?P<req_id>[A-Z]+[0-9]+)( \[(?P<refs>[A-Z,0-9]+)\])?: (?P<desc>.*)"
15
+
16
+ def __init__(self, parser):
17
+ super().__init__(parser)
18
+ self.RE = re.compile(self.REQ_PATTERN)
19
+
20
+ def test(self, parent, block):
21
+ return bool(self.RE.match(block))
22
+
23
+ def run(self, parent, blocks):
24
+
25
+ # Check fr multiple items in one block.
26
+ items = self.get_items(blocks.pop(0))
27
+
28
+ # This is a new list so create parent with appropriate tag.
29
+ req_table = etree.SubElement(parent, "table")
30
+ req_table.attrib["class"] = "nydok-requirements"
31
+
32
+ # Loop through items in block, recursively parsing each with the
33
+ # appropriate parent.
34
+
35
+ has_refs = any(item.get("refs") for item in items)
36
+ for item in items:
37
+ # New item. Create li and parse with it as parent
38
+ tr = etree.SubElement(req_table, "tr")
39
+ req_td = etree.SubElement(tr, "td")
40
+ req_td.text = item["req_id"]
41
+ req_td.attrib["class"] = "req-id"
42
+ if has_refs:
43
+ ref_td = etree.SubElement(tr, "td")
44
+ ref_td.text = " ".join(item["refs"].split(","))
45
+ ref_td.attrib["class"] = "req-refs"
46
+ desc_td = etree.SubElement(tr, "td")
47
+ desc_td.text = item["desc"]
48
+ desc_td.attrib["class"] = "req-desc"
49
+
50
+ def get_items(self, block):
51
+ """Break a block into list items."""
52
+ items = []
53
+ for line in block.split("\n"):
54
+ m = self.RE.match(line)
55
+ if m:
56
+ items.append(m.groupdict())
57
+ return items
58
+
59
+
60
+ class NydokExtension(Extension):
61
+ """Nydok extension for Python-Markdown."""
62
+
63
+ def extendMarkdown(self, md):
64
+ md.parser.blockprocessors.register(NydokRequirementProcessor(md.parser), "nydok", 100)
65
+ md.registerExtension(self)
@@ -0,0 +1,27 @@
1
+ table.nydok-requirements {
2
+ margin-top: 1rem;
3
+ margin-bottom: 1rem;
4
+ width: 90%;
5
+ margin-left: auto;
6
+ margin-right: auto;
7
+ }
8
+
9
+ table.nydok-requirements td.req-id {
10
+ background-color: rgba(240, 158, 120, 0.4);
11
+ background-color: #FD8143;
12
+ color: #fff;
13
+ font-weight: bold;
14
+ width: 1%;
15
+ }
16
+
17
+ table.nydok-requirements td.req-refs {
18
+ background-color: rgba(240, 158, 120, 0.7);
19
+ background-color: #FF9864;
20
+ color: #fff;
21
+ width: 1%;
22
+ }
23
+
24
+ table.nydok-requirements td.req-desc {
25
+ background-color: rgba(240, 158, 120, 0.15);
26
+ width: 98%;
27
+ }
File without changes
@@ -0,0 +1,114 @@
1
+ import re
2
+ from typing import Dict, List
3
+
4
+ import lxml.etree # type: ignore
5
+ import pytest
6
+
7
+ from ..exception import FailedTestCaseException
8
+ from ..schema import TestCase
9
+
10
+ JUNIT_PATTERN = r"(?P<req_id>[A-Z,0-9]+)( \[(?P<refs>[A-Z,0-9]+)\])?: (?P<desc>.*)"
11
+
12
+
13
+ class JUnitFile(pytest.File):
14
+ def collect(self):
15
+
16
+ with open(self.fspath) as f:
17
+
18
+ xml_data = lxml.etree.parse(f)
19
+ testsuites = xml_data.getroot()
20
+
21
+ pattern = re.compile(
22
+ self.session.config.getoption("specs-junit-regex")
23
+ or self.session.config.getini("specs-junit-regex")
24
+ or JUNIT_PATTERN
25
+ )
26
+
27
+ for testsuite in testsuites.findall("testsuite"):
28
+ testcases = testsuite.findall("testcase")
29
+
30
+ # We allow several results for a testcase within a single testsuite
31
+ # If there are no failures, we select the first test case.
32
+ # If there are failures, we select the first failure.
33
+ chosen_testcases: Dict[str, JUnitItem] = {}
34
+ for testcase in testcases:
35
+
36
+ name = testcase.attrib["name"]
37
+ classname = testcase.attrib.get("classname", "")
38
+ # file = testcase.attrib.get("file", "")
39
+ # line_no = testcase.attrib.get("line", "")
40
+
41
+ failures: List[str] = []
42
+ for failure in testcase.findall("failure"):
43
+ failures.append(failure.text)
44
+
45
+ skipped: List[str] = []
46
+ for skip in testcase.findall("skipped"):
47
+ skipped.append(skip.text)
48
+
49
+ # testcase_data = {
50
+ # "path": self.fspath,
51
+ # "name": name,
52
+ # "file": file,
53
+ # "line_no": line_no,
54
+ # "failures": failures,
55
+ # "skipped": skipped,
56
+ # }
57
+
58
+ # Parse out references
59
+ for re_result in re.finditer(pattern, name):
60
+
61
+ matches = re_result.groupdict()
62
+ refs = []
63
+ if matches.get("refs"):
64
+ refs = matches["refs"].split(",")
65
+ test_case = TestCase(
66
+ matches["req_id"].split(","),
67
+ None,
68
+ matches.get("desc"),
69
+ None,
70
+ classname,
71
+ None,
72
+ refs,
73
+ False,
74
+ not bool(failures),
75
+ )
76
+ if name not in chosen_testcases or (
77
+ failures and not chosen_testcases[name].failures
78
+ ):
79
+ chosen_testcases[name] = JUnitItem.from_parent(
80
+ self, name=name, test_case=test_case, failures=failures
81
+ )
82
+
83
+ yield from chosen_testcases.values()
84
+
85
+
86
+ class JUnitItem(pytest.Item):
87
+ def __init__(
88
+ self,
89
+ name,
90
+ parent,
91
+ test_case: TestCase,
92
+ failures: List[str],
93
+ ):
94
+ super().__init__(name, parent)
95
+ self.test_case: TestCase = test_case
96
+ self.failures: List[str] = failures
97
+
98
+ def runtest(self):
99
+
100
+ if not self.test_case.passed:
101
+ raise FailedTestCaseException()
102
+
103
+ def repr_failure(self, excinfo):
104
+ """Called when self.runtest() raises an exception."""
105
+
106
+ if isinstance(excinfo.value, FailedTestCaseException):
107
+ return f"JUnit testcase '{self.test_case.desc}' is reported as failed: \n" + "\n".join(
108
+ self.failures
109
+ )
110
+
111
+ return super().repr_failure(excinfo)
112
+
113
+ def reportinfo(self):
114
+ return self.fspath, None, f"JUnitTestCase: {self.name}"