def test_custom_class(
    content_view: Tuple[str, ContentView],
    serialization_format: Tuple[str, SerializationFormat],
):
    """Ensure an error is provided when something can't be serialized.

    A typing error does not exist here because the content is Dict[str, Any].

    :param content_view: The content view
    :param serialization_format: The serialization format
    """

    class CustomClass:
        """An empty custom class."""

    content = {"foo": CustomClass()}
    serialized = serialize(
        content=content,
        content_view=content_view[1],
        serialization_format=serialization_format[1],
    )
    assert (
        f"The requested content could not be converted to {serialization_format[0]!s}."
        in serialized
    )
def test_basic_success_no_color():
    """Ensure scope ``no_color`` return just lines."""
    sample = serialize(**SAMPLE_JSON)
    colorized = Colorize(grammar_dir=GRAMMAR_DIR,
                         theme_path=THEME_PATH).render(
                             doc=sample,
                             scope="no_color",
                         )
    assert not any(part.color for line in colorized for part in line)
def test_graceful_failure(mocked_func, caplog):
    """Ensure a tokenization error returns the original one line json string
    w/o color and the log reflects the critical error
    """
    mocked_func.side_effect = ValueError()
    sample = serialize(**SAMPLE_JSON)

    _result = Colorize(grammar_dir=GRAMMAR_DIR, theme_path=THEME_PATH).render(
        doc=sample,
        scope="source.json",
    )
    assert "rendered without color" in caplog.text
def test_basic_success_json():
    """Ensure the json string is returned as 1 lines, 5 parts and can be reassembled
    to the json string"""
    sample = serialize(**SAMPLE_JSON) + "\n"
    colorized = Colorize(grammar_dir=GRAMMAR_DIR,
                         theme_path=THEME_PATH).render(
                             doc=sample,
                             scope="source.json",
                         )
    assert len(colorized) == 3
    serialized_lines = sample.splitlines(keepends=True)
    colorized_lines = [
        "".join(part.chars for part in line) for line in colorized
    ]
    assert serialized_lines == colorized_lines
    assert "".join(serialized_lines) == sample
def test_basic_success_yaml():
    """Ensure the yaml string is returned as 2 lines, with 1 and 3 parts
    respectively, ensure the parts of the second line can be reassembled to
    the second line of the yaml string
    """
    sample = serialize(**SAMPLE_YAML)
    result = Colorize(grammar_dir=GRAMMAR_DIR, theme_path=THEME_PATH).render(
        doc=sample,
        scope="source.yaml",
    )
    assert len(result) == 2
    assert len(result[0]) == 1
    assert result[0][0].chars == sample.splitlines(keepends=True)[0]
    assert len(result[1]) == 4
    assert ("".join(
        line_part.chars
        for line_part in result[1]) == sample.splitlines(keepends=True)[1])
def test_anchor_alias(aliases_allowed: bool):
    """Test for anchors and aliases in yaml output.

    :param aliases_allowed: Indicates if aliases and anchors should be found
    """
    data = {"integer": 42}
    many_data = [data, data, data]
    yaml_string = serialize.serialize(
        content=many_data,
        content_view=ContentView.NORMAL,
        serialization_format=serialize.SerializationFormat.YAML,
    )
    assert isinstance(yaml_string, str), "Unexpected value from human_dump"
    found_alias = "&id" in yaml_string
    assert found_alias is aliases_allowed
    found_anchor = "*id" in yaml_string
    assert found_anchor is aliases_allowed
def test_deque(
    content_view: Tuple[str, ContentView],
    serialization_format: Tuple[str, SerializationFormat],
):
    """Ensure an error is provided when something can't be serialized.

    A typing error exists here, because tuple is not a ``utils.serialize.ContentType``.

    :param content_view: The content view
    :param serialization_format: The serialization format
    """
    content = deque([1, 2, 3])
    serialized = serialize(
        content=content,  # type:ignore[arg-type]
        content_view=content_view[1],
        serialization_format=serialization_format[1],
    )
    assert (
        f"The requested content could not be converted to {serialization_format[0]!s}."
        in serialized
    )
Example #8
0
def print_to_stdout(
    content: ContentType,
    content_format: ContentFormat,
    share_directory: str,
    use_color: bool,
) -> None:
    """Print some colored output to stdout.

    :param content: The content to print out.
    :param content_format: The content_format
    :param share_directory: the current share directory
    :param use_color: Indicates if color should be used
    """
    serialization_format = content_format.value.serialization
    if serialization_format:
        serialized = serialize(
            content=content,
            content_view=ContentView.NORMAL,
            serialization_format=serialization_format,
        )
        output = serialized
    else:
        output = str(content)

    if use_color and not stdout.isatty():
        logger.debug("Color requested, but device is not a TTY")
        use_color = False

    if use_color:
        tokenized = tokenize(
            content_format=content_format,
            serialized=output,
            share_directory=share_directory,
        )
        terminal_color_bits = color_bits()
        output = color_lines(terminal_color_bits, tokenized)

    print(output)