def assert_code_snippet_runs_and_prints_expected(
    snippet: str, state: dict, line_number: int | None = None
):
    """Executes a snippet and compares captured output to annotated output."""
    output_lines: list[str] = []
    expected_outputs = find_expected_outputs(snippet)

    def print_capture(*values, sep=' '):
        output_lines.extend(sep.join(str(e) for e in values).split('\n'))

    state['print'] = print_capture
    try:
        exec(snippet, state)

        assert_expected_lines_present_in_order(expected_outputs, output_lines)
    except AssertionError as ex:
        # pylint: disable=consider-using-f-string
        new_msg = ex.args[0] + '\n\nIn snippet{}:\n{}'.format(
            "" if line_number is None else " (line {})".format(line_number), _indent([snippet])
        )
        ex.args = (new_msg,) + tuple(ex.args[1:])
        raise
Executes a snippet and compares captured output to annotated output.
dev_tools/snippets_test.py