Skip to content

Commit

Permalink
feat: Support for disabling ANSI color escape codes via the `NO_COLOR…
Browse files Browse the repository at this point in the history
…` environment variable or the `--no-color` CLI option

Ref: #1153
  • Loading branch information
Stranger6667 committed May 7, 2021
1 parent e362292 commit b78a164
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Changelog
`Unreleased`_ - TBD
-------------------

**Added**

- Support for disabling ANSI color escape codes via the `NO_COLOR <https://no-color.org/>` environment variable or the ``--no-color`` CLI option. `#1153`_

**Changed**

- Generate valid header values for Bearer auth by construction rather than by filtering.
Expand Down Expand Up @@ -1849,6 +1853,7 @@ Deprecated
.. _0.3.0: https://github.com/schemathesis/schemathesis/compare/v0.2.0...v0.3.0
.. _0.2.0: https://github.com/schemathesis/schemathesis/compare/v0.1.0...v0.2.0

.. _#1153: https://github.com/schemathesis/schemathesis/issues/1153
.. _#1134: https://github.com/schemathesis/schemathesis/issues/1134
.. _#1121: https://github.com/schemathesis/schemathesis/issues/1121
.. _#1100: https://github.com/schemathesis/schemathesis/issues/1100
Expand Down
2 changes: 2 additions & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ loaded API schema, processed operations, found errors, and used checks.

By default, Schemathesis refuses to work with schemas that do not conform to the Open API spec, but you can disable this behavior with ``--validate-schema=false``.

.. note:: Schemathesis supports colorless output via the `NO_COLOR <https://no-color.org/>` environment variable or the ``--no-color`` CLI option.

Testing specific operations
---------------------------

Expand Down
15 changes: 15 additions & 0 deletions src/schemathesis/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,8 +450,11 @@ def __init__(self, *args: Any, group: ParameterGroup, **kwargs: Any):
cls=GroupedOption,
group=ParameterGroup.hypothesis,
)
@click.option("--no-color", help="Disable ANSI color escape codes.", type=bool, is_flag=True)
@click.option("--verbosity", "-v", help="Reduce verbosity of error output.", count=True)
@click.pass_context
def run(
ctx: click.Context,
schema: str,
auth: Optional[Tuple[str, str]],
auth_type: str,
Expand Down Expand Up @@ -491,12 +494,14 @@ def run(
hypothesis_seed: Optional[int] = None,
hypothesis_verbosity: Optional[hypothesis.Verbosity] = None,
verbosity: int = 0,
no_color: bool = False,
) -> None:
"""Perform schemathesis test against an API specified by SCHEMA.
SCHEMA must be a valid URL or file path pointing to an Open API / Swagger specification.
"""
# pylint: disable=too-many-locals
maybe_disable_color(ctx, no_color)
check_auth(auth, headers)
selected_targets = tuple(target for target in targets_module.ALL_TARGETS if target.__name__ in targets)

Expand Down Expand Up @@ -822,18 +827,23 @@ def execute(
@click.option("--status", help="Status of interactions to replay.", type=str)
@click.option("--uri", help="A regexp that filters interactions by their request URI.", type=str)
@click.option("--method", help="A regexp that filters interactions by their request method.", type=str)
@click.option("--no-color", help="Disable ANSI color escape codes.", type=bool, is_flag=True)
@click.pass_context
def replay(
ctx: click.Context,
cassette_path: str,
id_: Optional[str],
status: Optional[str] = None,
uri: Optional[str] = None,
method: Optional[str] = None,
no_color: bool = False,
) -> None:
"""Replay a cassette.
Cassettes in VCR-compatible format can be replayed.
For example, ones that are recorded with ``store-network-log`` option of `schemathesis run` command.
"""
maybe_disable_color(ctx, no_color)
click.secho(f"{bold('Replaying cassette')}: {cassette_path}")
with open(cassette_path) as fd:
cassette = yaml.load(fd, Loader=SafeLoader)
Expand All @@ -849,6 +859,11 @@ def bold(message: str) -> str:
return click.style(message, bold=True)


def maybe_disable_color(ctx: click.Context, no_color: bool) -> None:
if no_color or "NO_COLOR" in os.environ:
ctx.color = False


@HookDispatcher.register_spec([HookScope.GLOBAL])
def after_init_cli_run_handlers(
context: HookContext, handlers: List[EventHandler], execution_context: ExecutionContext
Expand Down
15 changes: 15 additions & 0 deletions test/cli/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ def test_commands_run_help(cli):
" --force-schema-version [20|30] Force Schemathesis to parse the input schema",
" with the specified spec version.",
"",
" --no-color Disable ANSI color escape codes.",
" -v, --verbosity Reduce verbosity of error output.",
" -h, --help Show this message and exit.",
]
Expand Down Expand Up @@ -1910,3 +1911,17 @@ def test_response_payload_encoding(cli, cli_args):
assert result.exit_code == ExitCode.TESTS_FAILED, result.stdout
# Then it should be displayed according its actual encoding
assert "Response payload: `Тест`" in result.stdout.splitlines()


@pytest.mark.parametrize("kind", ("env_var", "arg"))
@pytest.mark.parametrize("openapi_version", (OpenAPIVersion("3.0"),))
@pytest.mark.operations("success")
def test_no_color(monkeypatch, cli, schema_url, kind):
args = (schema_url,)
if kind == "env_var":
monkeypatch.setenv("NO_COLOR", "1")
if kind == "arg":
args += ("--no-color",)
result = cli.run(*args, color=True)
assert result.exit_code == ExitCode.OK, result.stdout
assert "[1m" not in result.stdout

0 comments on commit b78a164

Please sign in to comment.