Skip to content

Commit 3624533

Browse files
authored
Refactor generate tests to use assertion helper (#3047)
* Refactor generate tests to use assertion helper * Refactor more generate tests to use assertion helper * Add coverage for generate test helper * Fix generate helper coverage and relative path test * Fix generate helper edge cases * Add coverage for omitted input file type
1 parent c48bdb2 commit 3624533

3 files changed

Lines changed: 248 additions & 227 deletions

File tree

tests/main/conftest.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010
from argparse import Namespace
1111
from collections.abc import Callable, Generator, Sequence
1212
from pathlib import Path
13-
from typing import Literal
13+
from typing import Any, Literal
1414

1515
import black
1616
import pytest
1717
from packaging import version
1818

19+
from datamodel_code_generator import InputFileType, generate
1920
from datamodel_code_generator.__main__ import Exit, main
2021
from datamodel_code_generator.arguments import arg_parser
2122
from tests.conftest import (
@@ -240,6 +241,53 @@ def run_main_with_args(
240241
return return_code
241242

242243

244+
def run_generate_file_and_assert(
245+
*,
246+
input_path: Path,
247+
output_path: Path,
248+
input_file_type: InputFileType | None = None,
249+
assert_func: AssertFileContent,
250+
expected_file: str | Path | None = None,
251+
transform: Callable[[str], str] | None = None,
252+
**generate_kwargs: Any,
253+
) -> None:
254+
"""Execute generate() for a file input and assert the generated output."""
255+
__tracebackhide__ = True
256+
257+
input_: Path = input_path
258+
if input_path.is_absolute():
259+
try:
260+
input_ = input_path.relative_to(Path.cwd())
261+
except ValueError:
262+
input_ = input_path
263+
else:
264+
assert not input_.is_absolute()
265+
266+
generate_options: dict[str, Any] = {
267+
"output": output_path,
268+
**generate_kwargs,
269+
}
270+
if input_file_type is not None:
271+
generate_options["input_file_type"] = input_file_type
272+
273+
generate(
274+
input_=input_,
275+
**generate_options,
276+
)
277+
278+
if expected_file is None:
279+
frame = inspect.currentframe()
280+
assert frame is not None
281+
assert frame.f_back is not None
282+
func_name = frame.f_back.f_code.co_name
283+
del frame
284+
for prefix in ("test_main_", "test_"):
285+
func_name = func_name.removeprefix(prefix)
286+
expected_file = f"{func_name}.py"
287+
288+
assert_func(output_path, expected_file, transform=transform)
289+
290+
243291
def run_main_and_assert( # noqa: PLR0912
244292
*,
245293
input_path: Path | None = None,

0 commit comments

Comments
 (0)