plain-parser 1.0.0.dev1__py3-none-any.whl → 1.0.0.dev2__py3-none-any.whl

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.
@@ -1,37 +1,26 @@
1
- """Helpers over the plain source tree."""
1
+ """Helpers over the plain source tree: func-id navigation, specification collection, linked resources, hashing."""
2
2
 
3
3
  import hashlib
4
4
  import json
5
5
  import re
6
6
  import uuid
7
- from typing import Any, Iterator
8
-
9
- from plain_parser.exceptions import InvalidFridArgument, InvalidLiquidVariableName
10
-
11
- __all__ = [
12
- "FUNCTIONAL_REQUIREMENTS",
13
- "ACCEPTANCE_TESTS",
14
- "SEMANTIC_ID_PATTERN",
15
- "InvalidFridArgument",
16
- "InvalidLiquidVariableName",
17
- "is_semantic_id",
18
- "has_acceptance_tests",
19
- "get_frids",
20
- "get_first_frid",
21
- "get_next_frid",
22
- "get_previous_frid",
23
- "get_frids_before",
24
- "get_frids_range",
25
- "get_specification_item_markdown",
26
- "get_specifications_for_frid",
27
- "collect_specification_linked_resources",
28
- "collect_linked_resources",
29
- "hash_text",
30
- "get_hash_value",
31
- ]
7
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
32
8
 
9
+ from liquid2.filter import with_context
10
+
11
+ from plain_parser.exceptions import InvalidFridArgument, InvalidLiquidVariableName # noqa: F401
12
+
13
+ DEFINITIONS = "definitions"
14
+ NON_FUNCTIONAL_REQUIREMENTS = "implementation reqs"
15
+ TEST_REQUIREMENTS = "test reqs"
33
16
  FUNCTIONAL_REQUIREMENTS = "functional specs"
17
+ CONFORMANCE_TESTS = "conformance_tests"
34
18
  ACCEPTANCE_TESTS = "acceptance_tests"
19
+ CONFORMANCE_TEST_HEADING = "conformance tests"
20
+ ACCEPTANCE_TEST_HEADING = "acceptance tests"
21
+ LIST_SECTION_HEADINGS = [DEFINITIONS, NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS]
22
+ ALLOWED_SPECIFICATION_HEADINGS = [*LIST_SECTION_HEADINGS, FUNCTIONAL_REQUIREMENTS]
23
+ ALLOWED_IMPORT_SPECIFICATION_HEADINGS = LIST_SECTION_HEADINGS
35
24
  SEMANTIC_ID_PATTERN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
36
25
 
37
26
 
@@ -39,66 +28,66 @@ def is_semantic_id(text: str) -> bool:
39
28
  return SEMANTIC_ID_PATTERN.fullmatch(text) is not None
40
29
 
41
30
 
42
- def has_acceptance_tests(plain_source_tree: dict[str, Any]) -> bool:
43
- return any(f.get(ACCEPTANCE_TESTS) for f in plain_source_tree.get(FUNCTIONAL_REQUIREMENTS, []))
31
+ def _functionalities(plain_source_tree) -> List[Dict[str, Any]]:
32
+ return list(plain_source_tree.get(FUNCTIONAL_REQUIREMENTS, []))
33
+
44
34
 
35
+ def has_acceptance_tests(plain_source_tree) -> bool:
36
+ return any(f.get(ACCEPTANCE_TESTS) for f in _functionalities(plain_source_tree))
45
37
 
46
- def get_frids(plain_source_tree: dict[str, Any]) -> Iterator[str]:
47
- for functionality in plain_source_tree.get(FUNCTIONAL_REQUIREMENTS, []):
38
+
39
+ def get_frids(plain_source_tree) -> Iterator[str]:
40
+ for functionality in _functionalities(plain_source_tree):
48
41
  yield functionality["id"]
49
42
 
50
43
 
51
- def get_first_frid(plain_source_tree: dict[str, Any]) -> str | None:
44
+ def get_first_frid(plain_source_tree) -> Optional[str]:
52
45
  return next(get_frids(plain_source_tree), None)
53
46
 
54
47
 
55
- def _neighbour(plain_source_tree: dict[str, Any], frid: str, step: int) -> str | None:
48
+ def get_next_frid(plain_source_tree, frid) -> Optional[str]:
56
49
  frids = list(get_frids(plain_source_tree))
57
50
  if frid not in frids:
58
51
  raise Exception(f"Functionality {frid} does not exist.")
59
- index = frids.index(frid) + step
60
- return frids[index] if 0 <= index < len(frids) else None
61
-
62
-
63
- def get_next_frid(plain_source_tree: dict[str, Any], frid: str) -> str | None:
64
- return _neighbour(plain_source_tree, frid, 1)
52
+ position = frids.index(frid) + 1
53
+ return frids[position] if position < len(frids) else None
65
54
 
66
55
 
67
- def get_previous_frid(plain_source_tree: dict[str, Any], frid: str) -> str | None:
68
- return _neighbour(plain_source_tree, frid, -1)
56
+ def get_previous_frid(plain_source_tree, frid) -> Optional[str]:
57
+ frids = list(get_frids(plain_source_tree))
58
+ if frid not in frids:
59
+ raise Exception(f"Functionality {frid} does not exist.")
60
+ position = frids.index(frid) - 1
61
+ return frids[position] if position >= 0 else None
69
62
 
70
63
 
71
- def get_frids_before(plain_source_tree: dict[str, Any], target_frid: str) -> list[str]:
72
- result: list[str] = []
64
+ def get_frids_before(plain_source_tree, target_frid: str) -> List[str]:
65
+ before: List[str] = []
73
66
  for frid in get_frids(plain_source_tree):
74
67
  if frid == target_frid:
75
68
  break
76
- result.append(frid)
77
- return result
69
+ before.append(frid)
70
+ return before
78
71
 
79
72
 
80
- def get_frids_range(plain_source: dict[str, Any], start: str, end: str | None = None) -> list[str]:
73
+ def get_frids_range(plain_source, start, end=None) -> List[str]:
81
74
  frids = list(get_frids(plain_source))
82
75
  if start not in frids:
83
76
  raise InvalidFridArgument(f"Invalid start functionality ID: {start}. Valid IDs are: {frids}.")
84
77
  if end is not None and end not in frids:
85
78
  raise InvalidFridArgument(f"Invalid end functionality ID: {end}. Valid IDs are: {frids}.")
86
- first = frids.index(start)
79
+ start_position = frids.index(start)
87
80
  if end is None:
88
- return frids[first:]
89
- last = frids.index(end)
90
- if first > last:
81
+ return frids[start_position:]
82
+ end_position = frids.index(end)
83
+ if start_position > end_position:
91
84
  raise InvalidFridArgument(f"Start functionality ID: {start} must be before end functionality ID: {end}.")
92
- return frids[first : last + 1]
85
+ return frids[start_position : end_position + 1]
93
86
 
94
87
 
95
- def get_specification_item_markdown(
96
- specification_item: dict[str, Any],
97
- code_variables: dict[str, str],
98
- replace_code_variables: bool,
99
- key: str = "markdown",
100
- ) -> str:
101
- text: str = specification_item[key]
88
+ def get_specification_item_markdown(specification_item, code_variables, replace_code_variables, key="markdown") -> str:
89
+ """Return the text of an item, recording its code variables and, when asked, replacing their placeholders."""
90
+ text = specification_item[key]
102
91
  for variable in specification_item.get("code_variables", []):
103
92
  name, value = variable["name"], variable["value"]
104
93
  if name in code_variables and code_variables[name] != value:
@@ -109,115 +98,127 @@ def get_specification_item_markdown(
109
98
  return text
110
99
 
111
100
 
112
- def get_specifications_for_frid(
113
- plain_source_tree: dict[str, Any], frid: str, replace_code_variables: bool = True
114
- ) -> tuple[dict[str, Any], dict[str, str] | None]:
115
- functionalities = plain_source_tree.get(FUNCTIONAL_REQUIREMENTS, [])
116
- ids = [f["id"] for f in functionalities]
117
- if frid not in ids:
101
+ def get_specifications_for_frid(plain_source_tree, frid, replace_code_variables=True) -> Tuple[dict, Optional[dict]]:
102
+ """Return the specification texts that build one functionality, and the code variables they use."""
103
+ functionalities = _functionalities(plain_source_tree)
104
+ if frid not in [f["id"] for f in functionalities]:
118
105
  raise Exception(f"Functionality {frid} does not exist.")
119
- code_variables: dict[str, str] = {}
120
-
121
- def texts(items: list[dict[str, Any]], key: str = "markdown") -> list[str]:
122
- return [get_specification_item_markdown(i, code_variables, replace_code_variables, key) for i in items]
123
-
124
- specs: dict[str, Any] = {}
125
- for section in ("definitions", "implementation reqs", "test reqs"):
126
- specs[section] = texts(plain_source_tree.get(section, []))
127
- index = ids.index(frid)
128
- specs[FUNCTIONAL_REQUIREMENTS] = texts(functionalities[: index + 1])
129
- current = functionalities[index]
130
- for tests in ("conformance_tests", ACCEPTANCE_TESTS):
131
- scenarios = current.get(tests, [])
132
- specs[tests] = [{"id": s["id"], "text": t} for s, t in zip(scenarios, texts(scenarios, "text"))]
133
- return specs, (code_variables or None)
134
-
135
-
136
- def collect_specification_linked_resources(
137
- specification: dict[str, Any], specification_heading: str, linked_resources_list: list[dict[str, Any]]
138
- ) -> None:
139
- for link in specification.get("linked_resources", []):
140
- text, target = link["text"], link["target"]
141
- same = [e for e in linked_resources_list if e["text"] == text and e["target"] == target]
142
- if len(same) > 1:
143
- raise Exception(f"Duplicate linked resource found: {text} ({target})")
144
- if same:
145
- same[0]["sections"].append(specification_heading)
146
- continue
147
- for entry in linked_resources_list:
148
- if entry["text"] == text:
149
- raise Exception(f"The file {target} is linked to multiple linked resources with the same text: {text}")
150
- if entry["target"] == target:
151
- raise Exception(f"The linked resource {text} is linked to multiple files: {entry['target']}")
152
- linked_resources_list.append({"text": text, "target": target, "sections": [specification_heading]})
106
+ code_variables: Dict[str, str] = {}
107
+ specifications: Dict[str, list] = {}
108
+ for heading in LIST_SECTION_HEADINGS:
109
+ specifications[heading] = [
110
+ get_specification_item_markdown(item, code_variables, replace_code_variables)
111
+ for item in plain_source_tree.get(heading, [])
112
+ ]
113
+ specifications[FUNCTIONAL_REQUIREMENTS] = []
114
+ specifications[CONFORMANCE_TESTS] = []
115
+ specifications[ACCEPTANCE_TESTS] = []
116
+ for functionality in functionalities:
117
+ specifications[FUNCTIONAL_REQUIREMENTS].append(
118
+ get_specification_item_markdown(functionality, code_variables, replace_code_variables)
119
+ )
120
+ if functionality["id"] == frid:
121
+ for key in (CONFORMANCE_TESTS, ACCEPTANCE_TESTS):
122
+ for scenario in functionality.get(key, []):
123
+ text = get_specification_item_markdown(scenario, code_variables, replace_code_variables, "text")
124
+ specifications[key].append({"id": scenario["id"], "text": text})
125
+ break
126
+ return specifications, (code_variables or None)
127
+
128
+
129
+ def collect_specification_linked_resources(specification, specification_heading, linked_resources_list) -> None:
130
+ """Add the links of every item of a section to the registry, sorting it afterwards is the caller's job."""
131
+ for item in specification:
132
+ for link in item.get("linked_resources", []):
133
+ text, target = link["text"], link["target"]
134
+ same = [e for e in linked_resources_list if e["text"] == text and e["target"] == target]
135
+ if len(same) > 1:
136
+ raise Exception(f"Duplicate linked resource found: {text} ({target})")
137
+ if same:
138
+ same[0]["sections"].append(specification_heading)
139
+ continue
140
+ for entry in linked_resources_list:
141
+ if entry["text"] == text:
142
+ raise Exception(
143
+ f"The file {target} is linked to multiple linked resources with the same text: {text}"
144
+ )
145
+ if entry["target"] == target:
146
+ raise Exception(f"The linked resource {text} is linked to multiple files: {target}")
147
+ linked_resources_list.append({"text": text, "target": target, "sections": [specification_heading]})
153
148
 
154
149
 
155
150
  def collect_linked_resources(
156
- plain_source_tree: dict[str, Any],
157
- linked_resources_list: list[dict[str, Any]],
158
- specifications_list: list[str] | None,
159
- include_test_scenarios: bool,
160
- frid: str | None = None,
151
+ plain_source_tree, linked_resources_list, specifications_list, include_test_scenarios, frid=None
161
152
  ) -> bool:
153
+ """Collect the links of a tree into a registry, up to a func-id; true when that func-id was reached."""
162
154
  if not isinstance(plain_source_tree, dict):
163
155
  raise ValueError("plain_source_tree must be a dictionary.")
164
- if frid is not None and frid not in get_frids(plain_source_tree):
156
+ if frid is not None and frid not in list(get_frids(plain_source_tree)):
165
157
  raise ValueError(f"frid {frid} does not exist.")
166
- frid_found = False
167
- for section in ("definitions", "implementation reqs", "test reqs", FUNCTIONAL_REQUIREMENTS):
168
- if specifications_list is not None and section not in specifications_list:
158
+ headings = list(specifications_list) if specifications_list is not None else ALLOWED_SPECIFICATION_HEADINGS
159
+ reached = False
160
+ for heading in ALLOWED_SPECIFICATION_HEADINGS:
161
+ if heading not in headings or heading not in plain_source_tree:
169
162
  continue
170
- for item in plain_source_tree.get(section, []):
171
- collect_specification_linked_resources(item, section, linked_resources_list)
172
- if section != FUNCTIONAL_REQUIREMENTS:
173
- continue
174
- if include_test_scenarios and (frid is None or item["id"] == frid):
175
- for tests in ("conformance_tests", ACCEPTANCE_TESTS):
176
- for scenario in item.get(tests, []):
177
- collect_specification_linked_resources(scenario, section, linked_resources_list)
178
- if frid is not None and item["id"] == frid:
179
- frid_found = True
163
+ if heading != FUNCTIONAL_REQUIREMENTS:
164
+ collect_specification_linked_resources(plain_source_tree[heading], heading, linked_resources_list)
165
+ continue
166
+ for functionality in plain_source_tree[heading]:
167
+ collect_specification_linked_resources([functionality], heading, linked_resources_list)
168
+ is_target = frid is not None and functionality["id"] == frid
169
+ if include_test_scenarios and (frid is None or is_target):
170
+ for key in (CONFORMANCE_TESTS, ACCEPTANCE_TESTS):
171
+ collect_specification_linked_resources(functionality.get(key, []), heading, linked_resources_list)
172
+ if is_target:
173
+ reached = True
180
174
  break
181
- linked_resources_list.sort(key=lambda e: e["text"])
182
- return frid_found
175
+ linked_resources_list.sort(key=lambda entry: entry["text"])
176
+ return reached
183
177
 
184
178
 
185
179
  def hash_text(text: str) -> str:
186
180
  return hashlib.sha256(text.encode("utf-8")).hexdigest()
187
181
 
188
182
 
189
- def get_hash_value(specifications: Any) -> str:
183
+ def get_hash_value(specifications) -> str:
190
184
  return hash_text(json.dumps(specifications, indent=4, ensure_ascii=True))
191
185
 
192
186
 
187
+ _BUILT_IN_VARIABLES = ("now", "today")
188
+
189
+
190
+ def _first_variable_name(context) -> Optional[str]:
191
+ """Name of the first variable in the Liquid scope: the first named argument of the enclosing include tag."""
192
+ for name in context.scope:
193
+ if name not in _BUILT_IN_VARIABLES:
194
+ return name
195
+ return None
196
+
197
+
198
+ @with_context
193
199
  def code_variable_liquid_filter(value, *, context):
194
- """Liquid filter ``code_variable``: records the value under a random token when a mapping was given."""
195
- variable = next(iter(context.scope), None)
196
- if variable is None:
200
+ """Mark a value as a code variable: store it under a random token and output the token."""
201
+ name = _first_variable_name(context)
202
+ if name is None:
197
203
  raise Exception("Invalid use of code_variable filter!")
198
- code_variables = context.globals.get("code_variables")
204
+ code_variables = context.scope.get("code_variables")
199
205
  if not isinstance(code_variables, dict):
200
206
  return value
201
207
  token = uuid.uuid4().hex
202
- code_variables[token] = {variable: value}
208
+ code_variables[token] = {name: value}
203
209
  return token
204
210
 
205
211
 
206
- code_variable_liquid_filter.with_context = True # type: ignore[attr-defined]
207
-
208
-
212
+ @with_context
209
213
  def prohibited_chars_liquid_filter(value, prohibited_chars, *, context):
210
- """Liquid filter ``prohibited_chars``: rejects values holding any of the given characters."""
211
- variable = next(iter(context.scope), None)
212
- if variable is None:
214
+ """Output a value as text, unless it holds one of the prohibited characters."""
215
+ name = _first_variable_name(context)
216
+ if name is None:
213
217
  raise Exception("Invalid use of prohibited_chars filter!")
214
218
  text = str(value)
215
219
  for char in text:
216
220
  if char in str(prohibited_chars):
217
221
  raise InvalidLiquidVariableName(
218
- f"'{char}' is not a valid character for variable '{variable}' (value: '{text}')."
222
+ f"'{char}' is not a valid character for variable '{name}' (value: '{text}')."
219
223
  )
220
224
  return text
221
-
222
-
223
- prohibited_chars_liquid_filter.with_context = True # type: ignore[attr-defined]
plain_parser/project.py CHANGED
@@ -1,16 +1,18 @@
1
- """Discovery of test plain files and binding of their scenarios to the functionalities of a requires chain."""
1
+ """Parsing of a project: an entry module with its requires chain and the test plain files bound to its functionalities."""
2
2
 
3
3
  import os
4
4
  from dataclasses import dataclass
5
+ from typing import Dict, List, Set, Tuple
5
6
 
6
7
  import frontmatter
7
- import yaml # type: ignore[import-untyped]
8
8
 
9
- from plain_parser.concept_utils import collect_concepts
9
+ from plain_parser.concept_utils import extract_concepts_from_definition
10
10
  from plain_parser.exceptions import MissingTestPlainFileError, PlainSyntaxError, UnsupportedBase64Content
11
- from plain_parser.loaders import find_large_base64_blob
12
- from plain_parser.plain_file import PLAIN_SOURCE_FILE_EXTENSION, parse_module_chain
11
+ from plain_parser.loaders import find_large_base64_blob, resolve_linked_resource
12
+ from plain_parser.plain_file import PLAIN_SOURCE_FILE_EXTENSION, normalize_line_endings, parse_module_chain
13
+ from plain_parser.plain_spec import ACCEPTANCE_TESTS, CONFORMANCE_TESTS, DEFINITIONS, FUNCTIONAL_REQUIREMENTS
13
14
  from plain_parser.test_plain_file import (
15
+ MODULE_KEY,
14
16
  TestPlainFile,
15
17
  is_test_plain_file,
16
18
  parse_test_plain_file_source,
@@ -27,38 +29,38 @@ class BoundTestPlainFile:
27
29
 
28
30
  @dataclass
29
31
  class ProjectParseResult:
30
- chain: list[tuple[str, dict]]
31
- test_plain_files: list[BoundTestPlainFile]
32
-
33
-
34
- def _walk(folder: str) -> list[str]:
35
- entries = sorted(os.listdir(folder))
36
- files = [e for e in entries if e.endswith(PLAIN_SOURCE_FILE_EXTENSION) and os.path.isfile(os.path.join(folder, e))]
37
- result = [os.path.join(folder, f) for f in files]
38
- for entry in entries:
39
- sub = os.path.join(folder, entry)
40
- if os.path.isdir(sub):
41
- result.extend(_walk(sub))
42
- return result
32
+ chain: List[Tuple[str, dict]]
33
+ test_plain_files: List[BoundTestPlainFile]
34
+
35
+
36
+ def _walk(directory: str) -> List[str]:
37
+ entries = sorted(os.listdir(directory))
38
+ files = [
39
+ e for e in entries if e.endswith(PLAIN_SOURCE_FILE_EXTENSION) and os.path.isfile(os.path.join(directory, e))
40
+ ]
41
+ directories = [e for e in entries if os.path.isdir(os.path.join(directory, e))]
42
+ found = [os.path.join(directory, name) for name in files]
43
+ for name in directories:
44
+ found.extend(_walk(os.path.join(directory, name)))
45
+ return found
43
46
 
44
47
 
45
- def discover_test_plain_files(tests_folders: list[str], entry_dir: str) -> list[tuple[str, str]]:
46
- """Return (path, name) of every .plain file under the folders; name is relative to entry_dir with '/'."""
47
- found: list[tuple[str, str]] = []
48
+ def discover_test_plain_files(tests_folders: List[str], entry_dir: str) -> List[Tuple[str, str]]:
49
+ """List the `.plain` files under the tests folders as pairs of path and name, in discovery order."""
50
+ discovered: List[Tuple[str, str]] = []
48
51
  for folder in tests_folders:
49
- if not os.path.isdir(folder):
52
+ folder_path = folder if os.path.isabs(folder) else os.path.join(entry_dir, folder)
53
+ if not os.path.isdir(folder_path):
50
54
  continue
51
- for path in _walk(folder):
52
- name = os.path.relpath(path, entry_dir).replace(os.sep, "/")
53
- found.append((path, name))
54
- return found
55
+ for path in _walk(folder_path):
56
+ discovered.append((path, os.path.relpath(path, entry_dir).replace(os.sep, "/")))
57
+ return discovered
55
58
 
56
59
 
57
- def _read_text(path: str, name: str) -> str:
58
- with open(path, "rb") as handle:
59
- data = handle.read()
60
+ def _read_test_file(path: str, name: str) -> Tuple[str, dict]:
60
61
  try:
61
- text = data.decode("utf-8")
62
+ with open(path, "rb") as file:
63
+ text = file.read().decode("utf-8")
62
64
  except UnicodeDecodeError as error:
63
65
  raise PlainSyntaxError(f"Plain syntax error: File '{name}' under a tests folder is not a text file.") from error
64
66
  blob = find_large_base64_blob(text)
@@ -67,74 +69,79 @@ def _read_text(path: str, name: str) -> str:
67
69
  f"Test plain file '{name}' contains a base64-encoded blob ({len(blob)} characters) inlined in the "
68
70
  "scenarios. This is not supported. Remove the base64 data from the file."
69
71
  )
70
- return text
72
+ try:
73
+ metadata = frontmatter.loads(normalize_line_endings(text)).metadata
74
+ except Exception as error:
75
+ raise PlainSyntaxError(
76
+ f"Plain syntax error: File '{name}' under a tests folder has invalid frontmatter: {error}"
77
+ ) from error
78
+ if not is_test_plain_file(metadata):
79
+ raise PlainSyntaxError(
80
+ f"Plain syntax error: File '{name}' is under a tests folder but is not a test plain file: "
81
+ "its frontmatter needs the keys `module:` and `func_id:`."
82
+ )
83
+ return text, metadata
71
84
 
72
85
 
73
- def bind_test_plain_files(
74
- chain: list[tuple[str, dict]], tests_folders: list[str], template_dirs: list[str], entry_dir: str
75
- ) -> list[BoundTestPlainFile]:
76
- """Parse the discovered test plain files and append their scenarios to the functionalities they bind to."""
77
- trees = dict(chain)
78
- bound: list[BoundTestPlainFile] = []
86
+ def bind_test_plain_files(chain, tests_folders, template_dirs, entry_dir) -> List[BoundTestPlainFile]:
87
+ """Add the scenarios of every test plain file of the chain to the functionality it binds to."""
88
+ trees: Dict[str, dict] = dict(chain)
89
+ bound: List[BoundTestPlainFile] = []
79
90
  for path, name in discover_test_plain_files(tests_folders, entry_dir):
80
- text = _read_text(path, name)
81
- try:
82
- metadata = frontmatter.loads(text.replace("\r\n", "\n").replace("\r", "\n")).metadata
83
- except (yaml.YAMLError, ValueError) as error:
84
- raise PlainSyntaxError(
85
- f"Plain syntax error: File '{name}' under a tests folder has invalid frontmatter: {error}"
86
- ) from error
87
- if not is_test_plain_file(metadata):
88
- raise PlainSyntaxError(
89
- f"Plain syntax error: File '{name}' is under a tests folder but is not a test plain file: "
90
- "its frontmatter needs the keys `module:` and `func_id:`."
91
- )
92
- if metadata["module"] not in trees:
91
+ text, metadata = _read_test_file(path, name)
92
+ module = metadata[MODULE_KEY]
93
+ if not isinstance(module, str) or module not in trees:
93
94
  continue
94
95
  parsed = parse_test_plain_file_source(text, name, template_dirs, {})
95
- functionalities = trees[parsed.module].get("functional specs", [])
96
- target = next((f for f in functionalities if f["id"] == parsed.func_id), None)
97
- if target is None:
96
+ functionalities = {f["id"]: f for f in trees[parsed.module].get(FUNCTIONAL_REQUIREMENTS, [])}
97
+ if parsed.func_id not in functionalities:
98
98
  raise PlainSyntaxError(
99
99
  f"Plain syntax error: Test plain file '{name}' binds to functionality "
100
100
  f"'{parsed.module}:{parsed.func_id}', which module '{parsed.module}' does not have."
101
101
  )
102
- target["conformance_tests"].extend(s.to_dict() for s in parsed.conformance_tests)
103
- target["acceptance_tests"].extend(s.to_dict() for s in parsed.acceptance_tests)
102
+ functionality = functionalities[parsed.func_id]
103
+ functionality[CONFORMANCE_TESTS].extend(s.to_dict() for s in parsed.conformance_tests)
104
+ functionality[ACCEPTANCE_TESTS].extend(s.to_dict() for s in parsed.acceptance_tests)
104
105
  bound.append(BoundTestPlainFile(path, name, parsed))
105
106
  return bound
106
107
 
107
108
 
108
- def check_test_plain_files(chain: list[tuple[str, dict]], bound: list[BoundTestPlainFile]) -> None:
109
- """Check concepts and scenario-id uniqueness of bound files against the functionality they join."""
110
- trees = dict(chain)
111
- first_use: dict[tuple[str, str], dict[str, tuple[int, str]]] = {}
112
- for item in bound:
113
- parsed = item.parsed
114
- concepts, _ = collect_concepts(trees[parsed.module])
115
- errors = validate_scenario_concepts(parsed, set(concepts))
116
- if errors:
117
- raise PlainSyntaxError(
118
- f"Plain syntax error: Found {len(errors)} errors in test plain file '{item.name}':\n"
119
- + "\n".join(errors)
120
- )
121
- seen = first_use.setdefault((parsed.module, parsed.func_id), {})
109
+ def _visible_concepts(tree: dict) -> Set[str]:
110
+ concepts: Set[str] = set()
111
+ for item in tree.get(DEFINITIONS, []):
112
+ concepts.update(extract_concepts_from_definition(item["markdown"])[0])
113
+ return concepts
114
+
115
+
116
+ def check_test_plain_files(chain, bound) -> None:
117
+ """Check the scenarios of the bound files: no id used twice for a functionality, no undefined concept."""
118
+ visible = {name: _visible_concepts(tree) for name, tree in chain}
119
+ first_use: Dict[Tuple[str, str, str], Tuple[int, str]] = {}
120
+ for file in bound:
121
+ parsed = file.parsed
122
122
  for scenario in parsed.scenarios:
123
- if scenario.id in seen:
124
- line, first_name = seen[scenario.id]
123
+ key = (parsed.module, parsed.func_id, scenario.id)
124
+ if key in first_use:
125
+ first_line, first_name = first_use[key]
125
126
  raise PlainSyntaxError(
126
127
  f"Plain syntax error: Syntax error at line {scenario.line_number} in test plain file "
127
- f"'{item.name}': Duplicate scenario-id `{scenario.id}` for functionality "
128
- f"'{parsed.module}:{parsed.func_id}'; it is first used at line {line} in test plain file "
128
+ f"'{file.name}': Duplicate scenario-id `{scenario.id}` for functionality "
129
+ f"'{parsed.module}:{parsed.func_id}'; it is first used at line {first_line} in test plain file "
129
130
  f"'{first_name}'."
130
131
  )
131
- seen[scenario.id] = (scenario.line_number, item.name)
132
+ first_use[key] = (scenario.line_number, file.name)
133
+ errors = validate_scenario_concepts(parsed, visible[parsed.module])
134
+ if errors:
135
+ raise PlainSyntaxError(
136
+ f"Plain syntax error: Found {len(errors)} errors in test plain file '{file.name}':\n"
137
+ + "\n".join(errors)
138
+ )
132
139
 
133
140
 
134
- def _require_test_plain_files(chain: list[tuple[str, dict]], bound: list[BoundTestPlainFile]) -> None:
135
- bound_keys = {(b.parsed.module, b.parsed.func_id) for b in bound}
141
+ def _require_test_plain_files(chain, bound) -> None:
142
+ bound_keys = {(file.parsed.module, file.parsed.func_id) for file in bound}
136
143
  for module, tree in chain:
137
- for functionality in tree.get("functional specs", []):
144
+ for functionality in tree.get(FUNCTIONAL_REQUIREMENTS, []):
138
145
  if (module, functionality["id"]) not in bound_keys:
139
146
  raise MissingTestPlainFileError(
140
147
  f"Functionality {module}:{functionality['id']} has no test plain file. Add one, by convention "
@@ -142,12 +149,19 @@ def _require_test_plain_files(chain: list[tuple[str, dict]], bound: list[BoundTe
142
149
  )
143
150
 
144
151
 
152
+ def _entry_dir(plain_file_name: str, template_dirs: List[str]) -> str:
153
+ if os.path.isabs(plain_file_name):
154
+ return os.path.dirname(plain_file_name)
155
+ resolved = resolve_linked_resource(template_dirs, plain_file_name)
156
+ return os.path.dirname(resolved) if resolved else os.path.dirname(os.path.abspath(plain_file_name))
157
+
158
+
145
159
  def parse_project(
146
- plain_file_name: str, template_dirs: list[str], tests_folders: list[str], require_test_plain_files: bool
160
+ plain_file_name: str, template_dirs: List[str], tests_folders: List[str], require_test_plain_files: bool
147
161
  ) -> ProjectParseResult:
148
- """Parse the requires chain, bind and check test plain files, optionally requiring one per functionality."""
162
+ """Parse an entry module with its requires chain and bind the test plain files to its functionalities."""
149
163
  chain = parse_module_chain(plain_file_name, template_dirs)
150
- entry_dir = template_dirs[0]
164
+ entry_dir = _entry_dir(plain_file_name, template_dirs)
151
165
  bound = bind_test_plain_files(chain, tests_folders, template_dirs, entry_dir)
152
166
  check_test_plain_files(chain, bound)
153
167
  if require_test_plain_files: