def test_boolean_columns(): "Regression: recognize boolean columns (issue #64)" xortable = [[False, True], [True, False]] expected = "\n".join(["False True", "True False"]) result = tabulate(xortable, tablefmt="plain") assert_equal(result, expected)
def test_moinmoin(): "Output: moinmoin with headers" expected = "\n".join(['|| \'\'\' strings \'\'\' ||<style="text-align: right;"> \'\'\' numbers \'\'\' ||', '|| spam ||<style="text-align: right;"> 41.9999 ||', '|| eggs ||<style="text-align: right;"> 451 ||',]) result = tabulate(_test_table, _test_table_headers, tablefmt="moinmoin") assert_equal(expected, result)
def test_align_long_integers(): "Regression: long integers should be aligned as integers (issue #61)" table = [[_long_type(1)], [_long_type(234)]] result = tabulate(table, tablefmt="plain") expected = "\n".join([" 1", "234"]) assert_equal(result, expected)
def test_pipe_headerless(): "Output: pipe without headers" expected = '\n'.join(['|:-----|---------:|', '| spam | 41.9999 |', '| eggs | 451 |',]) result = tabulate(_test_table, tablefmt="pipe") assert_equal(expected, result)
def test_plain(): "Output: plain with headers" expected = "\n".join(['strings numbers', 'spam 41.9999', 'eggs 451',]) result = tabulate(_test_table, _test_table_headers, tablefmt="plain") assert_equal(expected, result)
def test_jira_headerless(): "Output: jira without headers" expected = '\n'.join(['| spam | 41.9999 |', '| eggs | 451 |',]) result = tabulate(_test_table, tablefmt="jira") assert_equal(expected, result)
def test_column_alignment(): "Output: custom alignment for text and numbers" expected = '\n'.join(['----- ---', 'Alice 1', ' Bob 333', '----- ---',]) result = tabulate([['Alice', 1],['Bob', 333]], stralign="right", numalign="center") assert_equal(expected, result)
def test_simple_headerless(): "Output: simple without headers" expected = "\n".join(['---- --------', 'spam 41.9999', 'eggs 451', '---- --------',]) result = tabulate(_test_table, tablefmt="simple") assert_equal(expected, result)
def test_simple_separated_format(): "Regression: simple_separated_format() accepts any separator (issue #12)" from tabulate import simple_separated_format fmt = simple_separated_format("!") expected = 'spam!eggs' formatted = tabulate([["spam", "eggs"]], tablefmt=fmt) print("expected: %r\n\ngot: %r\n" % (expected, formatted)) assert_equal(expected, formatted)
def test_textile_with_center_align(): "Output: textile with center align" result = tabulate(_test_table, tablefmt="textile", stralign='center') expected = """\ |=. spam |>. 41.9999 | |=. eggs |>. 451 |""" assert_equal(expected, result)
def test_rst_headerless(): "Output: rst without headers" expected = '\n'.join(['==== ========', 'spam 41.9999', 'eggs 451', '==== ========',]) result = tabulate(_test_table, tablefmt="rst") assert_equal(expected, result)
def test_textile(): "Output: textile without header" result = tabulate(_test_table, tablefmt="textile") expected = """\ |<. spam |>. 41.9999 | |<. eggs |>. 451 |""" assert_equal(expected, result)
def test_script_from_stdin_to_stdout(): """Command line utility: read from stdin, print to stdout""" cmd = ["python", "tabulate.py"] out = run_and_capture_stdout(cmd, input=sample_input()) expected = SAMPLE_SIMPLE_FORMAT print("got: ",repr(out)) print("expected:",repr(expected)) assert_equal(out.splitlines(), expected.splitlines())
def test_jira(): "Output: jira with headers" expected = '\n'.join(['|| strings || numbers ||', '| spam | 41.9999 |', '| eggs | 451 |',]) result = tabulate(_test_table, _test_table_headers, tablefmt="jira") assert_equal(expected, result)
def test_orgtbl(): "Output: orgtbl with headers" expected = '\n'.join(['| strings | numbers |', '|-----------+-----------|', '| spam | 41.9999 |', '| eggs | 451 |',]) result = tabulate(_test_table, _test_table_headers, tablefmt="orgtbl") assert_equal(expected, result)
def test_psql_headerless(): "Output: psql without headers" expected = '\n'.join(['+------+----------+', '| spam | 41.9999 |', '| eggs | 451 |', '+------+----------+',]) result = tabulate(_test_table, tablefmt="psql") assert_equal(expected, result)
def test_textile_with_header(): "Output: textile with header" result = tabulate(_test_table, ['strings', 'numbers'], tablefmt="textile") expected = """\ |_. strings |_. numbers | |<. spam |>. 41.9999 | |<. eggs |>. 451 |""" assert_equal(expected, result)
def test_html_headerless(): "Output: html without headers" expected = '\n'.join([ '<table>', '<tr><td>spam</td><td style="text-align: right;"> 41.9999</td></tr>', '<tr><td>eggs</td><td style="text-align: right;">451 </td></tr>', '</table>',]) result = tabulate(_test_table, tablefmt="html") assert_equal(expected, result)
def test_ansi_color_for_decimal_numbers(): "Regression: ANSI colors for decimal numbers (issue #36)" table = [["Magenta", "\033[95m" + "1.1" + "\033[0m"]] expected = "\n".join([ '------- ---', 'Magenta \x1b[95m1.1\x1b[0m', '------- ---']) result = tabulate(table) assert_equal(result, expected)
def test_fancy_grid_headerless(): "Output: fancy_grid without headers" expected = '\n'.join([ '╒══════╤══════════╕', '│ spam │ 41.9999 │', '├──────┼──────────┤', '│ eggs │ 451 │', '╘══════╧══════════╛',]) result = tabulate(_test_table, tablefmt="fancy_grid") assert_equal(expected, result)
def test_rst(): "Output: rst with headers" expected = '\n'.join(['========= =========', 'strings numbers', '========= =========', 'spam 41.9999', 'eggs 451', '========= =========',]) result = tabulate(_test_table, _test_table_headers, tablefmt="rst") assert_equal(expected, result)
def test_script_sep_option(): """Command line utility: -s, --sep option""" for option in ["-s", "--sep"]: cmd = ["python", "tabulate.py", option, ","] raw_table = sample_input(sep=",") out = run_and_capture_stdout(cmd, input=raw_table) expected = SAMPLE_SIMPLE_FORMAT print("got: ",repr(out)) print("expected:",repr(expected)) assert_equal(out.splitlines(), expected.splitlines())
def test_latex_headerless(): "Output: latex without headers" result = tabulate(_test_table, tablefmt="latex") expected = "\n".join([r"\begin{tabular}{lr}", r"\hline", r" spam & 41.9999 \\", r" eggs & 451 \\", r"\hline", r"\end{tabular}"]) assert_equal(expected, result)
def test_list_of_lists_firstrow(): "Input: a list of lists with the first row as headers." ll = [["string","number"],["a","one",1],["b","two",None]] expected = "\n".join([ ' string number', '-- -------- --------', 'a one 1', 'b two']) result = tabulate(ll, headers="firstrow") assert_equal(expected, result)
def test_iterable_of_iterables(): "Input: an interable of iterables." ii = iter(map(lambda x: iter(x), [range(5), range(5,0,-1)])) expected = "\n".join( ['- - - - -', '0 1 2 3 4', '5 4 3 2 1', '- - - - -']) result = tabulate(ii) assert_equal(expected, result)
def test_iterable_of_iterables_firstrow(): "Input: an interable of iterables with the first row as headers" ii = iter(map(lambda x: iter(x), ["abcde", range(5), range(5,0,-1)])) expected = "\n".join( [' a b c d e', '--- --- --- --- ---', ' 0 1 2 3 4', ' 5 4 3 2 1']) result = tabulate(ii, "firstrow") assert_equal(expected, result)
def test_unaligned_separated(): "Output: non-aligned data columns" expected = '\n'.join(['name|score', 'Alice|1', 'Bob|333']) fmt = simple_separated_format("|") result = tabulate([['Alice', 1],['Bob', 333]], ["name", "score"], tablefmt=fmt, stralign=None, numalign=None) assert_equal(expected, result)
def test_script_floatfmt_option(): """Command line utility: -F, --float option""" for option in ["-F", "--float"]: cmd = ["python", "tabulate.py", option, ".1e", "--format", "grid"] raw_table = sample_input() out = run_and_capture_stdout(cmd, input=raw_table) expected = SAMPLE_GRID_FORMAT_WITH_DOT1E_FLOATS print("got: ",repr(out)) print("expected:",repr(expected)) assert_equal(out.splitlines(), expected.splitlines())
def test_latex_booktabs_headerless(): "Output: latex without headers, using the booktabs format" result = tabulate(_test_table, tablefmt="latex_booktabs") expected = "\n".join([r"\begin{tabular}{lr}", r"\toprule", r" spam & 41.9999 \\", r" eggs & 451 \\", r"\bottomrule", r"\end{tabular}"]) assert_equal(expected, result)
def test_list_of_lists_keys(): "Input: a list of lists with column indices as headers." ll = [["a","one",1],["b","two",None]] expected = "\n".join([ '0 1 2', '--- --- ---', 'a one 1', 'b two']) result = tabulate(ll, headers="keys") assert_equal(expected, result)
def test_plain_multiline_with_empty_cells(): "Output: plain with multiline cells and empty cells with headers" table = [ ["hdr", "data", "fold"], ["1", "", ""], ["2", "very long data", "fold\nthis"], ] expected = "\n".join([ " hdr data fold", " 1", " 2 very long data fold", " this", ]) result = tabulate(table, headers="firstrow", tablefmt="plain") assert_equal(expected, result)
def test_wrap_full_line_color(): """TextWrapper: Wrap a line when the full thing is enclosed in color tags""" # This has both a text color and a background color data = ( "\033[31m\033[104mThis is a test string for testing TextWrap with colors\033[0m" ) expected = [ "\033[31m\033[104mThis is a test\033[0m", "\033[31m\033[104mstring for testing\033[0m", "\033[31m\033[104mTextWrap with colors\033[0m", ] wrapper = CTW(width=20) result = wrapper.wrap(data) assert_equal(expected, result)
def test_numpy_2d_keys(): "Input: a two-dimensional NumPy array with column indices as headers." try: import numpy na = (numpy.arange(1, 10, dtype=numpy.float32).reshape( (3, 3))**3) * 0.5 expected = "\n".join([ ' 0 1 2', '----- ----- -----', ' 0.5 4 13.5', ' 32 62.5 108', '171.5 256 364.5' ]) result = tabulate(na, headers="keys") assert_equal(expected, result) except ImportError: print("test_numpy_2d_keys is skipped") pass # this test is optional
def test_pandas(): "Input: a Pandas DataFrame." try: import pandas df = pandas.DataFrame([["one",1],["two",None]], index=["a","b"]) expected = "\n".join([ ' string number', '-- -------- --------', 'a one 1', 'b two nan']) result = tabulate(df, headers=["string", "number"]) assert_equal(expected, result) except ImportError: print("test_pandas is skipped") pass # this test is optional
def test_mediawiki(): "Output: mediawiki with headers" expected = '\n'.join([ '{| class="wikitable" style="text-align: left;"', '|+ <!-- caption -->', '|-', '! strings !! align="right"| numbers', '|-', '| spam || align="right"| 41.9999', '|-', '| eggs || align="right"| 451', '|}', ]) result = tabulate(_test_table, _test_table_headers, tablefmt="mediawiki") assert_equal(expected, result)
def test_psql_multiline_with_empty_cells(): "Output: psql with multiline cells and empty cells with headers" table = [['hdr', 'data', 'fold'], ['1', '', ''], ['2', 'very long data', 'fold\nthis']] expected = "\n".join([ "+-------+----------------+--------+", "| hdr | data | fold |", "|-------+----------------+--------|", "| 1 | | |", "| 2 | very long data | fold |", "| | | this |", "+-------+----------------+--------+" ]) result = tabulate(table, headers="firstrow", tablefmt="psql") assert_equal(expected, result)
def test_numpy_2d_firstrow(): "Input: a two-dimensional NumPy array with the first row as headers." try: import numpy na = (numpy.arange(1,10, dtype=numpy.int32).reshape((3,3))**3) expected = "\n".join([ ' 1 8 27', '--- --- ----', ' 64 125 216', '343 512 729']) result = tabulate(na, headers="firstrow") assert_equal(expected, result) except ImportError: print("test_numpy_2d_firstrow is skipped") pass # this test is optional
def test_ansi_color_bold_and_fgcolor(): "Regression: set ANSI color and bold face together (issue #65)" table = [["1", "2", "3"], ["4", "\x1b[1;31m5\x1b[1;m", "6"], ["7", "8", "9"]] result = tabulate(table, tablefmt="grid") expected = "\n".join([ "+---+---+---+", "| 1 | 2 | 3 |", "+---+---+---+", "| 4 | \x1b[1;31m5\x1b[1;m | 6 |", "+---+---+---+", "| 7 | 8 | 9 |", "+---+---+---+", ]) assert_equal(result, expected)
def test_colorclass_colors(): "Regression: ANSI colors in a unicode/str subclass (issue #49)" try: import colorclass s = colorclass.Color("{magenta}3.14{/magenta}") result = tabulate([[s]], tablefmt="plain") expected = "\x1b[35m3.14\x1b[39m" assert_equal(result, expected) except ImportError: class textclass(_text_type): pass s = textclass("\x1b[35m3.14\x1b[39m") result = tabulate([[s]], tablefmt="plain") expected = "\x1b[35m3.14\x1b[39m" assert_equal(result, expected)
def test_grid_multiline_headerless(): "Output: grid with multiline cells without headers" table = [["foo bar\nbaz\nbau", "hello"], ["", "multiline\nworld"]] expected = "\n".join([ "+---------+-----------+", "| foo bar | hello |", "| baz | |", "| bau | |", "+---------+-----------+", "| | multiline |", "| | world |", "+---------+-----------+", ]) result = tabulate(table, stralign="center", tablefmt="grid") assert_equal(expected, result)
def test_rst_multiline(): "Output: rst with multiline cells with headers" table = [[2, "foo\nbar"]] headers = ("more\nspam \x1b[31meggs\x1b[0m", "more spam\n& eggs") expected = "\n".join([ "=========== ===========", " more more spam", " spam \x1b[31meggs\x1b[0m & eggs", "=========== ===========", " 2 foo", " bar", "=========== ===========", ]) result = tabulate(table, headers, tablefmt="rst") assert_equal(expected, result)
def test_html(): "Output: html with headers" expected = '\n'.join([ '<table>', '<thead>', '<tr><th>strings </th><th style="text-align: right;"> numbers</th></tr>', '</thead>', '<tbody>', '<tr><td>spam </td><td style="text-align: right;"> 41.9999</td></tr>', '<tr><td>eggs </td><td style="text-align: right;"> 451 </td></tr>', '</tbody>', '</table>', ]) result = tabulate(_test_table, _test_table_headers, tablefmt="html") assert_equal(expected, result)
def test_grid_multiline(): "Output: grid with multiline cells with headers" table = [[2, "foo\nbar"]] headers = ("more\nspam \x1b[31meggs\x1b[0m", "more spam\n& eggs") expected = "\n".join([ "+-------------+-------------+", "| more | more spam |", "| spam \x1b[31meggs\x1b[0m | & eggs |", "+=============+=============+", "| 2 | foo |", "| | bar |", "+-------------+-------------+", ]) result = tabulate(table, headers, tablefmt="grid") assert_equal(expected, result)
def test_numpy_2d(): "Input: a 2D NumPy array with headers." try: import numpy na = (numpy.arange(1, 10, dtype=numpy.float32).reshape( (3, 3))**3) * 0.5 expected = "\n".join([ ' a b c', '----- ----- -----', ' 0.5 4 13.5', ' 32 62.5 108', '171.5 256 364.5' ]) result = tabulate(na, ["a", "b", "c"]) assert_equal(expected, result) except ImportError: print("test_numpy_2d is skipped") raise SkipTest() # this test is optional
def test_fancy_grid_multiline_headerless(): "Output: fancy_grid with multiline cells without headers" table = [["foo bar\nbaz\nbau", "hello"], ["", "multiline\nworld"]] expected = "\n".join([ "╒═════════╤═══════════╕", "│ foo bar │ hello │", "│ baz │ │", "│ bau │ │", "├─────────┼───────────┤", "│ │ multiline │", "│ │ world │", "╘═════════╧═══════════╛", ]) result = tabulate(table, stralign="center", tablefmt="fancy_grid") assert_equal(expected, result)
def test_fancy_grid_multiline(): "Output: fancy_grid with multiline cells with headers" table = [[2, "foo\nbar"]] headers = ("more\nspam \x1b[31meggs\x1b[0m", "more spam\n& eggs") expected = "\n".join([ "╒═════════════╤═════════════╕", "│ more │ more spam │", "│ spam \x1b[31meggs\x1b[0m │ & eggs │", "╞═════════════╪═════════════╡", "│ 2 │ foo │", "│ │ bar │", "╘═════════════╧═════════════╛", ]) result = tabulate(table, headers, tablefmt="fancy_grid") assert_equal(expected, result)
def test_wrap_wide_char_longword(): """TextWrapper: wrapping wide char word that needs to be broken up""" try: import wcwidth # noqa except ImportError: skip("test_wrap_wide_char_longword is skipped") data = "약간감싸면더잘보일수있" expected = ["약간", "감싸", "면더", "잘보", "일수", "있"] # Explicit odd number to ensure the 2 width is taken into account wrapper = CTW(width=5) result = wrapper.wrap(data) assert_equal(expected, result)
def test_disable_numparse_list(): "Output: Default table output, but with number parsing selectively disabled" table_headers = ['h1', 'h2', 'h3'] test_table = [['foo', 'bar', '42992e1']] expected = "\n".join(['h1 h2 h3', '---- ---- -------', 'foo bar 42992e1',]) result = tabulate(test_table, table_headers, disable_numparse=[2]) assert_equal(expected, result) expected = "\n".join(['h1 h2 h3', '---- ---- ------', 'foo bar 429920',]) result = tabulate(test_table, table_headers, disable_numparse=[0, 1]) assert_equal(expected, result)
def test_wrap_text_to_colwidths_single_ansi_colors_full_cell(): """Internal: autowrapped text can retain a single ANSI colors when it is at the beginning and end of full cell""" data = [[("\033[31mThis is a rather long description that might" " look better if it is wrapped a bit\033[0m")]] result = T._wrap_text_to_colwidths(data, [30]) expected = [[ "\n".join([ "\033[31mThis is a rather long\033[0m", "\033[31mdescription that might look\033[0m", "\033[31mbetter if it is wrapped a bit\033[0m", ]) ]] assert_equal(expected, result)
def test_wrap_text_to_colwidths_multi_ansi_colors_in_subset(): """Internal: autowrapped text can retain multiple ANSI colors when they are around subsets of the cell""" data = [[("This is a rather \033[31mlong description\033[0m that" " might look better \033[93mif it is wrapped\033[0m a bit")]] result = T._wrap_text_to_colwidths(data, [30]) expected = [[ "\n".join([ "This is a rather \033[31mlong\033[0m", "\033[31mdescription\033[0m that might look", "better \033[93mif it is wrapped\033[0m a bit", ]) ]] assert_equal(expected, result)
def test_pandas_firstrow(): "Input: a Pandas DataFrame with the first row as headers." try: import pandas df = pandas.DataFrame([["one", 1], ["two", None]], columns=["string", "number"], index=["a", "b"]) expected = "\n".join( ["a one 1.0", "--- ----- -----", "b two nan"]) result = tabulate(df, headers="firstrow") assert_equal(expected, result) except ImportError: print("test_pandas_firstrow is skipped") raise SkipTest() # this test is optional
def test_escape_empty_cell_in_first_column_in_rst(): "Regression: escape empty cells of the first column in RST format (issue #82)" table = [["foo", 1], ["", 2], ["bar", 3]] headers = ["", "val"] expected = "\n".join([ "==== =====", ".. val", "==== =====", "foo 1", ".. 2", "bar 3", "==== =====", ]) result = tabulate(table, headers, tablefmt="rst") assert_equal(result, expected)
def test_simple_multiline(): "Output: simple with multiline cells" expected = "\n".join([ " key value", "----- ---------", " foo bar", "spam multiline", " world", ]) table = [["key", "value"], ["foo", "bar"], ["spam", "multiline\nworld"]] result = tabulate(table, headers='firstrow', stralign="center", tablefmt="simple") assert_equal(expected, result)
def test_datetime_values(): "Regression: datetime, date, and time values in cells (issue #10)." import datetime dt = datetime.datetime(1991, 2, 19, 17, 35, 26) d = datetime.date(1991, 2, 19) t = datetime.time(17, 35, 26) formatted = tabulate([[dt, d, t]]) expected = "\n".join([ "------------------- ---------- --------", "1991-02-19 17:35:26 1991-02-19 17:35:26", "------------------- ---------- --------", ]) print("expected: %r\n\ngot: %r\n" % (expected, formatted)) assert_equal(expected, formatted)
def test_latex_escape_special_chars(): "Regression: escape special characters in LaTeX output (issue #32)" expected = "\n".join( [ r"\begin{tabular}{l}", r"\hline", r" foo\^{}bar \\", r"\hline", r" \&\%\^{}\_\$\#\{\}\ensuremath{<}\ensuremath{>}\textasciitilde{} \\", r"\hline", r"\end{tabular}", ] ) result = tabulate([["&%^_$#{}<>~"]], ["foo^bar"], tablefmt="latex") assert_equal(result, expected)
def test_numpy_2d_firstrow(): "Input: a 2D NumPy array with the first row as headers." try: import numpy na = numpy.arange(1, 10, dtype=numpy.int32).reshape((3, 3))**3 expected = "\n".join([ " 1 8 27", "--- --- ----", " 64 125 216", "343 512 729" ]) result = tabulate(na, headers="firstrow") assert_equal(expected, result) except ImportError: print("test_numpy_2d_firstrow is skipped") raise SkipTest() # this test is optional
def test_custom_tablefmt(): "Regression: allow custom TableFormat that specifies with_header_hide (github issue #20)" tablefmt = TableFormat( lineabove=Line("", "-", " ", ""), linebelowheader=Line("", "-", " ", ""), linebetweenrows=None, linebelow=Line("", "-", " ", ""), headerrow=DataRow("", " ", ""), datarow=DataRow("", " ", ""), padding=0, with_header_hide=["lineabove", "linebelow"], ) rows = [["foo", "bar"], ["baz", "qux"]] expected = "\n".join(["A B", "--- ---", "foo bar", "baz qux"]) result = tabulate(rows, headers=["A", "B"], tablefmt=tablefmt) assert_equal(result, expected)
def test_latex(): "Output: latex with headers and replaced characters" raw_test_table_headers = list(_test_table_headers) raw_test_table_headers[-1] += " ($N_0$)" result = tabulate(_test_table, raw_test_table_headers, tablefmt="latex") expected = "\n".join([ r"\begin{tabular}{lr}", r"\hline", r" strings & numbers (\$N\_0\$) \\", r"\hline", r" spam & 41.9999 \\", r" eggs & 451 \\", r"\hline", r"\end{tabular}", ]) assert_equal(expected, result)
def test_latex_booktabs(): "Output: latex with headers, using the booktabs format" result = tabulate(_test_table, _test_table_headers, tablefmt="latex_booktabs") expected = "\n".join([ r"\begin{tabular}{lr}", r"\toprule", r" strings & numbers \\", r"\midrule", r" spam & 41.9999 \\", r" eggs & 451 \\", r"\bottomrule", r"\end{tabular}", ]) assert_equal(expected, result)
def test_presto_multiline_with_empty_cells(): "Output: presto with multiline cells and empty cells with headers" table = [ ["hdr", "data", "fold"], ["1", "", ""], ["2", "very long data", "fold\nthis"], ] expected = "\n".join([ " hdr | data | fold", "-------+----------------+--------", " 1 | |", " 2 | very long data | fold", " | | this", ]) result = tabulate(table, headers="firstrow", tablefmt="presto") assert_equal(expected, result)