我有一个命令行应用程序,它可以接受命令行参数--input_files或--unigrams,但不能同时接受两者:
import click
import pathlib
from typing import Optional
@click.command()
@click.option(
"--input_files",
default=None,
type=str,
help="Comma-separated list of one-sentence-per-line raw corpus files",
)
@click.option("--unigrams", default=None, type=str, help="Comma-separated list of unigrams")
@click.option(
"--model_path",
default="spm/models",
type=click.Path(file_okay=False, path_type=pathlib.Path),
help="Output model path",
)
def minimal(
model_path: pathlib.Path,
input_files: Optional[str],
unigrams: Optional[str]
) -> str:
if input_files and unigrams:
raise ValueError("Only one of input_files or unigrams can be specified.")
if input_files:
click.echo(f"input_files: {input_files}")
if unigrams:
click.echo(f"Unigrams: {unigrams}")我编写了一个测试,用于使用文件系统隔离传递两个参数的情况,并期望引发ValueError:
from click.testing import CliRunner
def test_minimal(tmp_path: str) -> None:
runner = CliRunner()
with runner.isolated_filesystem(temp_dir=tmp_path):
result = runner.invoke(
minimal,
["--model_path", tmp_path, "--input-files", "test.txt", "--unigrams", "a,b"],
)
assert isinstance(result.exception, ValueError)
assert "Only one of input_files or unigrams can be specified." in str(result.exception)但是,由于引发了SystemExit,此测试失败:
=================================================================================== FAILURES ====================================================================================
_________________________________________________________________________________ test_minimal __________________________________________________________________________________
tmp_path = PosixPath('/tmp/pytest-of-biogeek/pytest-2/test_minimal0')
def test_minimal(tmp_path: str) -> None:
runner = CliRunner()
with runner.isolated_filesystem(temp_dir=tmp_path):
result = runner.invoke(
train_spm.minimal,
["--model_path", tmp_path, "--input-files", "test.txt", "--unigrams", "a,b"],
)
> assert isinstance(result.exception, ValueError)
E assert False
E + where False = isinstance(SystemExit(2), ValueError)
E + where SystemExit(2) = <Result SystemExit(2)>.exception
stackoverflow_test.py:20: AssertionError
============================================================================ short test summary info ============================================================================
FAILED projects/stackoverflow_test.py::test_minimal - assert False我做错了什么?
发布于 2022-10-10 16:02:52
SystemExit(2)是这个答案引用的UsageError。这意味着命令行脚本中可能有不正确的地方。
在检查原始文件时,可以将参数标志定义为--input_files。但是,测试脚本正在调用--input-files。
用下划线代替破折号可以解决问题,并通过测试。
https://stackoverflow.com/questions/74013952
复制相似问题