plain-parser 0.2.1.dev22__py3-none-any.whl → 1.0.0.dev1__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.
plain_parser/project.py CHANGED
@@ -1,54 +1,67 @@
1
- """A module with its requires chain and the test plain files bound to its functionalities."""
1
+ """Discovery of test plain files and binding of their scenarios to the functionalities of a requires chain."""
2
2
 
3
3
  import os
4
4
  from dataclasses import dataclass
5
5
 
6
6
  import frontmatter
7
+ import yaml # type: ignore[import-untyped]
7
8
 
8
- from plain_parser import concept_utils, loaders, plain_file, plain_spec, test_plain_file
9
+ from plain_parser.concept_utils import collect_concepts
9
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
13
+ from plain_parser.test_plain_file import (
14
+ TestPlainFile,
15
+ is_test_plain_file,
16
+ parse_test_plain_file_source,
17
+ validate_scenario_concepts,
18
+ )
10
19
 
11
20
 
12
21
  @dataclass
13
22
  class BoundTestPlainFile:
14
- path: str # The file on disk.
15
- name: str # The path relative to the entry module's directory, with `/` as separator.
16
- parsed: test_plain_file.TestPlainFile
23
+ path: str
24
+ name: str
25
+ parsed: TestPlainFile
17
26
 
18
27
 
19
28
  @dataclass
20
29
  class ProjectParseResult:
21
- # As parse_module_chain returns it, with the scenarios of the test plain files merged into the functionalities.
22
30
  chain: list[tuple[str, dict]]
23
31
  test_plain_files: list[BoundTestPlainFile]
24
32
 
25
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
43
+
44
+
26
45
  def discover_test_plain_files(tests_folders: list[str], entry_dir: str) -> list[tuple[str, str]]:
27
- """(path, name) of every .plain file under the tests folders: tests folder by tests folder, and within one by path. A
28
- tests folder that does not exist is skipped."""
29
- found = []
30
- for tests_folder in tests_folders:
31
- if not os.path.isdir(tests_folder):
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
+ for folder in tests_folders:
49
+ if not os.path.isdir(folder):
32
50
  continue
33
- for root, dirs, files in os.walk(tests_folder):
34
- dirs.sort()
35
- for file_name in sorted(files):
36
- if file_name.endswith(plain_file.PLAIN_SOURCE_FILE_EXTENSION):
37
- found.append(
38
- (os.path.join(root, file_name), loaders.relative_resource_path(entry_dir, root, file_name))
39
- )
51
+ for path in _walk(folder):
52
+ name = os.path.relpath(path, entry_dir).replace(os.sep, "/")
53
+ found.append((path, name))
40
54
  return found
41
55
 
42
56
 
43
- def read_test_plain_file_text(path: str, name: str) -> str:
44
- with open(path, "rb") as f:
45
- raw = f.read()
57
+ def _read_text(path: str, name: str) -> str:
58
+ with open(path, "rb") as handle:
59
+ data = handle.read()
46
60
  try:
47
- text = raw.decode("utf-8")
48
- except UnicodeDecodeError:
49
- raise PlainSyntaxError(f"Plain syntax error: File '{name}' under a tests folder is not a text file.")
50
-
51
- blob = loaders.find_large_base64_blob(text)
61
+ text = data.decode("utf-8")
62
+ except UnicodeDecodeError as error:
63
+ raise PlainSyntaxError(f"Plain syntax error: File '{name}' under a tests folder is not a text file.") from error
64
+ blob = find_large_base64_blob(text)
52
65
  if blob is not None:
53
66
  raise UnsupportedBase64Content(
54
67
  f"Test plain file '{name}' contains a base64-encoded blob ({len(blob)} characters) inlined in the "
@@ -60,101 +73,83 @@ def read_test_plain_file_text(path: str, name: str) -> str:
60
73
  def bind_test_plain_files(
61
74
  chain: list[tuple[str, dict]], tests_folders: list[str], template_dirs: list[str], entry_dir: str
62
75
  ) -> list[BoundTestPlainFile]:
63
- """Read every test plain file under the tests folders and add its scenarios to the functionality it binds to.
64
-
65
- A file whose `module:` names a module outside the chain is passed over, so that one tests folder can serve
66
- several self-standing specs. A `.plain` file under a tests folder without the `module:` and `func_id:` keys is
67
- an error, as is a file that binds to a func-id the module does not have. The concepts of the scenarios must be
68
- visible to the bound module. Files bound to one functionality are merged in discovery order; a scenario-id is
69
- unique across that merged set.
70
- """
76
+ """Parse the discovered test plain files and append their scenarios to the functionalities they bind to."""
71
77
  trees = dict(chain)
72
- bound = []
73
- scenario_places: dict[tuple[str, str], dict[str, str]] = {} # (module, func-id) -> scenario-id -> place
78
+ bound: list[BoundTestPlainFile] = []
74
79
  for path, name in discover_test_plain_files(tests_folders, entry_dir):
75
- text = read_test_plain_file_text(path, name)
80
+ text = _read_text(path, name)
76
81
  try:
77
- metadata = frontmatter.loads(text).metadata
78
- except Exception as e:
82
+ metadata = frontmatter.loads(text.replace("\r\n", "\n").replace("\r", "\n")).metadata
83
+ except (yaml.YAMLError, ValueError) as error:
79
84
  raise PlainSyntaxError(
80
- f"Plain syntax error: File '{name}' under a tests folder has invalid frontmatter: {e}"
81
- )
82
- if not test_plain_file.is_test_plain_file(metadata):
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):
83
88
  raise PlainSyntaxError(
84
- f"Plain syntax error: File '{name}' is under a tests folder but is not a test plain file: its "
85
- f"frontmatter needs the keys `module:` and `func_id:`."
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:`."
86
91
  )
87
-
88
- if metadata[test_plain_file.MODULE_KEY] not in trees:
89
- # The file belongs to a module this render does not build. One tests folder may serve
90
- # several self-standing specs, so such a file is passed over, not read. A module name
91
- # that is a typo binds the file to nothing, and the functionality it was written for
92
- # then has no test plain file, which check_test_plain_files reports.
92
+ if metadata["module"] not in trees:
93
93
  continue
94
-
95
- parsed = test_plain_file.parse_test_plain_file_source(text, name, template_dirs, {})
96
- tree = trees[parsed.module]
97
- functionalities = tree.get(plain_spec.FUNCTIONAL_REQUIREMENTS) or []
98
- functionality = next((item for item in functionalities if item["id"] == parsed.func_id), None)
99
- if functionality is None:
94
+ 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:
100
98
  raise PlainSyntaxError(
101
99
  f"Plain syntax error: Test plain file '{name}' binds to functionality "
102
100
  f"'{parsed.module}:{parsed.func_id}', which module '{parsed.module}' does not have."
103
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)
104
+ bound.append(BoundTestPlainFile(path, name, parsed))
105
+ return bound
104
106
 
105
- concepts, _ = concept_utils.collect_concepts(tree)
106
- errors = test_plain_file.validate_scenario_concepts(parsed, set(concepts))
107
+
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))
107
116
  if errors:
108
117
  raise PlainSyntaxError(
109
- f"Plain syntax error: Found {len(errors)} errors in test plain file '{name}':\n" + "\n".join(errors)
118
+ f"Plain syntax error: Found {len(errors)} errors in test plain file '{item.name}':\n"
119
+ + "\n".join(errors)
110
120
  )
111
-
112
- places = scenario_places.setdefault((parsed.module, parsed.func_id), {})
113
- for key, scenarios in (
114
- (plain_spec.CONFORMANCE_TESTS, parsed.conformance_tests),
115
- (plain_spec.ACCEPTANCE_TESTS, parsed.acceptance_tests),
116
- ):
117
- for scenario in scenarios:
118
- if scenario.id in places:
119
- raise PlainSyntaxError(
120
- f"Plain syntax error: Syntax error at line {scenario.line_number} in test plain file "
121
- f"'{name}': Duplicate scenario-id `{scenario.id}` for functionality "
122
- f"'{parsed.module}:{parsed.func_id}'; it is first used {places[scenario.id]}."
123
- )
124
- places[scenario.id] = f"at line {scenario.line_number} in test plain file '{name}'"
125
- functionality[key].append(scenario.to_dict())
126
-
127
- bound.append(BoundTestPlainFile(path, name, parsed))
128
-
129
- return bound
121
+ seen = first_use.setdefault((parsed.module, parsed.func_id), {})
122
+ for scenario in parsed.scenarios:
123
+ if scenario.id in seen:
124
+ line, first_name = seen[scenario.id]
125
+ raise PlainSyntaxError(
126
+ 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 "
129
+ f"'{first_name}'."
130
+ )
131
+ seen[scenario.id] = (scenario.line_number, item.name)
130
132
 
131
133
 
132
- def check_test_plain_files(chain: list[tuple[str, dict]], bound: list[BoundTestPlainFile]) -> None:
133
- """Raise for the first functionality of the chain, in render order, that has no test plain file bound to it.
134
-
135
- The sections of the file may be empty; the file itself is what the check asks for.
136
- """
137
- bound_functionalities = {(item.parsed.module, item.parsed.func_id) for item in bound}
138
- for module_name, tree in chain:
139
- for functionality in tree.get(plain_spec.FUNCTIONAL_REQUIREMENTS) or []:
140
- func_id = functionality["id"]
141
- if (module_name, func_id) not in bound_functionalities:
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}
136
+ for module, tree in chain:
137
+ for functionality in tree.get("functional specs", []):
138
+ if (module, functionality["id"]) not in bound_keys:
142
139
  raise MissingTestPlainFileError(
143
- f"Functionality {module_name}:{func_id} has no test plain file. Add one, by convention "
144
- f"tests/{module_name}/{func_id}.plain, with the add-test-scenarios skill."
140
+ f"Functionality {module}:{functionality['id']} has no test plain file. Add one, by convention "
141
+ f"tests/{module}/{functionality['id']}.plain, with the add-test-scenarios skill."
145
142
  )
146
143
 
147
144
 
148
145
  def parse_project(
149
146
  plain_file_name: str, template_dirs: list[str], tests_folders: list[str], require_test_plain_files: bool
150
147
  ) -> ProjectParseResult:
151
- """Parse a module with its requires chain and bind the test plain files under ``tests_folders`` to its functionalities.
152
-
153
- ``template_dirs[0]`` is the entry module's directory; test plain files are named relative to it. With
154
- ``require_test_plain_files``, every functionality of every module in the chain needs a test plain file.
155
- """
156
- chain = plain_file.parse_module_chain(plain_file_name, template_dirs)
157
- bound = bind_test_plain_files(chain, tests_folders, template_dirs, template_dirs[0])
148
+ """Parse the requires chain, bind and check test plain files, optionally requiring one per functionality."""
149
+ chain = parse_module_chain(plain_file_name, template_dirs)
150
+ entry_dir = template_dirs[0]
151
+ bound = bind_test_plain_files(chain, tests_folders, template_dirs, entry_dir)
152
+ check_test_plain_files(chain, bound)
158
153
  if require_test_plain_files:
159
- check_test_plain_files(chain, bound)
154
+ _require_test_plain_files(chain, bound)
160
155
  return ProjectParseResult(chain, bound)