Skip to content

Commit

Permalink
A round of black to pass CI tests
Browse files Browse the repository at this point in the history
  • Loading branch information
DimitriPapadopoulos committed Sep 26, 2024
1 parent ca5a2e6 commit ad49d19
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 60 deletions.
35 changes: 25 additions & 10 deletions tabulate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2202,15 +2202,18 @@ def tabulate(

# align columns
# first set global alignment
if colglobalalign is not None: # if global alignment provided
if colglobalalign is not None: # if global alignment provided
aligns = [colglobalalign] * len(cols)
else: # default
else: # default
aligns = [numalign if ct in [int, float] else stralign for ct in coltypes]
# then specific alignments
if colalign is not None:
assert isinstance(colalign, Iterable)
if isinstance(colalign, str):
warnings.warn(f"As a string, `colalign` is interpreted as {[c for c in colalign]}. Did you mean `colglobalalign = \"{colalign}\"` or `colalign = (\"{colalign}\",)`?", stacklevel=2)
warnings.warn(
f'As a string, `colalign` is interpreted as {[c for c in colalign]}. Did you mean `colglobalalign = "{colalign}"` or `colalign = ("{colalign}",)`?',
stacklevel=2,
)
for idx, align in enumerate(colalign):
if not idx < len(aligns):
break
Expand All @@ -2229,20 +2232,23 @@ def tabulate(
# align headers and add headers
t_cols = cols or [[""]] * len(headers)
# first set global alignment
if headersglobalalign is not None: # if global alignment provided
if headersglobalalign is not None: # if global alignment provided
aligns_headers = [headersglobalalign] * len(t_cols)
else: # default
else: # default
aligns_headers = aligns or [stralign] * len(headers)
# then specific header alignments
if headersalign is not None:
assert isinstance(headersalign, Iterable)
if isinstance(headersalign, str):
warnings.warn(f"As a string, `headersalign` is interpreted as {[c for c in headersalign]}. Did you mean `headersglobalalign = \"{headersalign}\"` or `headersalign = (\"{headersalign}\",)`?", stacklevel=2)
warnings.warn(
f'As a string, `headersalign` is interpreted as {[c for c in headersalign]}. Did you mean `headersglobalalign = "{headersalign}"` or `headersalign = ("{headersalign}",)`?',
stacklevel=2,
)
for idx, align in enumerate(headersalign):
hidx = headers_pad + idx
if not hidx < len(aligns_headers):
break
elif align == "same" and hidx < len(aligns): # same as column align
elif align == "same" and hidx < len(aligns): # same as column align
aligns_headers[hidx] = aligns[hidx]
elif align != "global":
aligns_headers[hidx] = align
Expand All @@ -2267,7 +2273,14 @@ def tabulate(
_reinsert_separating_lines(rows, separating_lines)

return _format_table(
tablefmt, headers, aligns_headers, rows, minwidths, aligns, is_multiline, rowaligns=rowaligns
tablefmt,
headers,
aligns_headers,
rows,
minwidths,
aligns,
is_multiline,
rowaligns=rowaligns,
)


Expand Down Expand Up @@ -2398,7 +2411,9 @@ def str(self):
return self


def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_multiline, rowaligns):
def _format_table(
fmt, headers, headersaligns, rows, colwidths, colaligns, is_multiline, rowaligns
):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
Expand Down Expand Up @@ -2738,7 +2753,7 @@ def _main():
print(usage)
sys.exit(0)
files = [sys.stdin] if not args else args
with (sys.stdout if outfile == "-" else open(outfile, "w")) as out:
with sys.stdout if outfile == "-" else open(outfile, "w") as out:
for f in files:
if f == "-":
f = sys.stdin
Expand Down
3 changes: 2 additions & 1 deletion test/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from pytest import skip, raises # noqa
import warnings


def assert_equal(expected, result):
print("Expected:\n%s\n" % expected)
print("Got:\n%s\n" % result)
Expand All @@ -28,6 +29,7 @@ def rows_to_pipe_table_str(rows):

return "\n".join(lines)


def check_warnings(func_args_kwargs, *, num=None, category=None, contain=None):
func, args, kwargs = func_args_kwargs
with warnings.catch_warnings(record=True) as W:
Expand All @@ -41,4 +43,3 @@ def check_warnings(func_args_kwargs, *, num=None, category=None, contain=None):
assert all([issubclass(w.category, category) for w in W])
if contain is not None:
assert all([contain in str(w.message) for w in W])

1 change: 0 additions & 1 deletion test/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"""


import os
import sys

Expand Down
20 changes: 17 additions & 3 deletions test/test_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,16 @@ def test_wrap_text_wide_chars():
except ImportError:
skip("test_wrap_text_wide_chars is skipped")

rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]]
rows = [
["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]
]
widths = [5, 20]
expected = [["청자\n청자\n청자\n청자\n청자", "약간 감싸면 더 잘\n보일 수있는 다소 긴\n설명입니다"]]
expected = [
[
"청자\n청자\n청자\n청자\n청자",
"약간 감싸면 더 잘\n보일 수있는 다소 긴\n설명입니다",
]
]
result = T._wrap_text_to_colwidths(rows, widths)

assert_equal(expected, result)
Expand Down Expand Up @@ -239,7 +246,14 @@ def test_wrap_text_to_colwidths_colors_wide_char():
except ImportError:
skip("test_wrap_text_to_colwidths_colors_wide_char is skipped")

data = [[("\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m")]]
data = [
[
(
"\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴"
" 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m"
)
]
]
result = T._wrap_text_to_colwidths(data, [30])

expected = [
Expand Down
103 changes: 59 additions & 44 deletions test/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ def test_plain_maxcolwidth_autowraps_wide_chars():

table = [
["hdr", "fold"],
["1", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명"],
[
"1",
"약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명",
],
]
expected = "\n".join(
[
Expand Down Expand Up @@ -2680,60 +2683,72 @@ def test_colalign_multi_with_sep_line():
expected = " one two\n\nthree four"
assert_equal(expected, result)


def test_column_global_and_specific_alignment():
""" Test `colglobalalign` and `"global"` parameter for `colalign`. """
table = [[1,2,3,4],[111,222,333,444]]
colglobalalign = 'center'
colalign = ('global','left', 'right')
"""Test `colglobalalign` and `"global"` parameter for `colalign`."""
table = [[1, 2, 3, 4], [111, 222, 333, 444]]
colglobalalign = "center"
colalign = ("global", "left", "right")
result = tabulate(table, colglobalalign=colglobalalign, colalign=colalign)
expected = '\n'.join([
"--- --- --- ---",
" 1 2 3 4",
"111 222 333 444",
"--- --- --- ---"])
expected = "\n".join(
[
"--- --- --- ---",
" 1 2 3 4",
"111 222 333 444",
"--- --- --- ---",
]
)
assert_equal(expected, result)


def test_headers_global_and_specific_alignment():
""" Test `headersglobalalign` and `headersalign`. """
table = [[1,2,3,4,5,6],[111,222,333,444,555,666]]
colglobalalign = 'center'
colalign = ('left',)
headers = ['h', 'e', 'a', 'd', 'e', 'r']
headersglobalalign = 'right'
headersalign = ('same', 'same', 'left', 'global', 'center')
result = tabulate(table, headers=headers, colglobalalign=colglobalalign, colalign=colalign, headersglobalalign=headersglobalalign, headersalign=headersalign)
expected = '\n'.join([
"h e a d e r",
"--- --- --- --- --- ---",
"1 2 3 4 5 6",
"111 222 333 444 555 666"])
"""Test `headersglobalalign` and `headersalign`."""
table = [[1, 2, 3, 4, 5, 6], [111, 222, 333, 444, 555, 666]]
colglobalalign = "center"
colalign = ("left",)
headers = ["h", "e", "a", "d", "e", "r"]
headersglobalalign = "right"
headersalign = ("same", "same", "left", "global", "center")
result = tabulate(
table,
headers=headers,
colglobalalign=colglobalalign,
colalign=colalign,
headersglobalalign=headersglobalalign,
headersalign=headersalign,
)
expected = "\n".join(
[
"h e a d e r",
"--- --- --- --- --- ---",
"1 2 3 4 5 6",
"111 222 333 444 555 666",
]
)
assert_equal(expected, result)


def test_colalign_or_headersalign_too_long():
""" Test `colalign` and `headersalign` too long. """
table = [[1,2],[111,222]]
colalign = ('global', 'left', 'center')
headers = ['h']
headersalign = ('center', 'right', 'same')
result = tabulate(table, headers=headers, colalign=colalign, headersalign=headersalign)
expected = '\n'.join([
" h",
"--- ---",
" 1 2",
"111 222"])
"""Test `colalign` and `headersalign` too long."""
table = [[1, 2], [111, 222]]
colalign = ("global", "left", "center")
headers = ["h"]
headersalign = ("center", "right", "same")
result = tabulate(
table, headers=headers, colalign=colalign, headersalign=headersalign
)
expected = "\n".join([" h", "--- ---", " 1 2", "111 222"])
assert_equal(expected, result)


def test_warning_when_colalign_or_headersalign_is_string():
""" Test user warnings when `colalign` or `headersalign` is a string. """
table = [[1,"bar"]]
opt = {
'colalign': "center",
'headers': ['foo', '2'],
'headersalign': "center"}
check_warnings((tabulate, [table], opt),
num = 2,
category = UserWarning,
contain = "As a string")
"""Test user warnings when `colalign` or `headersalign` is a string."""
table = [[1, "bar"]]
opt = {"colalign": "center", "headers": ["foo", "2"], "headersalign": "center"}
check_warnings(
(tabulate, [table], opt), num=2, category=UserWarning, contain="As a string"
)


def test_float_conversions():
"Output: float format parsed"
Expand Down
4 changes: 3 additions & 1 deletion test/test_textwrapper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Discretely test functionality of our custom TextWrapper"""

from __future__ import unicode_literals

import datetime
Expand Down Expand Up @@ -144,7 +145,8 @@ def test_wrap_color_in_single_line():

def test_wrap_color_line_splillover():
"""TextWrapper: Wrap a line - preserve internal color tags and wrap them to
other lines when required, requires adding the colors tags to other lines as appropriate"""
other lines when required, requires adding the colors tags to other lines as appropriate
"""
# This has both a text color and a background color
data = "This is a \033[31mtest string for testing TextWrap\033[0m with colors"

Expand Down

0 comments on commit ad49d19

Please sign in to comment.