Skip to content

Commit fc23ebd

Browse files
attack68JulianWgs
authored andcommitted
move Styler format tests to own module (pandas-dev#40641)
Co-authored-by: JHM Darbyshire (iMac) <[email protected]>
1 parent 34fe51d commit fc23ebd

File tree

2 files changed

+199
-156
lines changed

2 files changed

+199
-156
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
import numpy as np
2+
import pytest
3+
4+
from pandas import (
5+
DataFrame,
6+
IndexSlice,
7+
NaT,
8+
Timestamp,
9+
)
10+
import pandas._testing as tm
11+
12+
pytest.importorskip("jinja2")
13+
from pandas.io.formats.style import Styler
14+
15+
16+
@pytest.fixture
17+
def df():
18+
return DataFrame(
19+
data=[[0, -0.609], [1, -1.228]],
20+
columns=["A", "B"],
21+
index=["x", "y"],
22+
)
23+
24+
25+
@pytest.fixture
26+
def styler(df):
27+
return Styler(df, uuid_len=0)
28+
29+
30+
def test_display_format(styler):
31+
ctx = styler.format("{:0.1f}")._translate()
32+
assert all(["display_value" in c for c in row] for row in ctx["body"])
33+
assert all([len(c["display_value"]) <= 3 for c in row[1:]] for row in ctx["body"])
34+
assert len(ctx["body"][0][1]["display_value"].lstrip("-")) <= 3
35+
36+
37+
def test_format_dict(styler):
38+
ctx = styler.format({"A": "{:0.1f}", "B": "{0:.2%}"})._translate()
39+
assert ctx["body"][0][1]["display_value"] == "0.0"
40+
assert ctx["body"][0][2]["display_value"] == "-60.90%"
41+
42+
43+
def test_format_string(styler):
44+
ctx = styler.format("{:.2f}")._translate()
45+
assert ctx["body"][0][1]["display_value"] == "0.00"
46+
assert ctx["body"][0][2]["display_value"] == "-0.61"
47+
assert ctx["body"][1][1]["display_value"] == "1.00"
48+
assert ctx["body"][1][2]["display_value"] == "-1.23"
49+
50+
51+
def test_format_callable(styler):
52+
ctx = styler.format(lambda v: "neg" if v < 0 else "pos")._translate()
53+
assert ctx["body"][0][1]["display_value"] == "pos"
54+
assert ctx["body"][0][2]["display_value"] == "neg"
55+
assert ctx["body"][1][1]["display_value"] == "pos"
56+
assert ctx["body"][1][2]["display_value"] == "neg"
57+
58+
59+
def test_format_with_na_rep():
60+
# GH 21527 28358
61+
df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
62+
63+
ctx = df.style.format(None, na_rep="-")._translate()
64+
assert ctx["body"][0][1]["display_value"] == "-"
65+
assert ctx["body"][0][2]["display_value"] == "-"
66+
67+
ctx = df.style.format("{:.2%}", na_rep="-")._translate()
68+
assert ctx["body"][0][1]["display_value"] == "-"
69+
assert ctx["body"][0][2]["display_value"] == "-"
70+
assert ctx["body"][1][1]["display_value"] == "110.00%"
71+
assert ctx["body"][1][2]["display_value"] == "120.00%"
72+
73+
ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate()
74+
assert ctx["body"][0][2]["display_value"] == "-"
75+
assert ctx["body"][1][2]["display_value"] == "120.00%"
76+
77+
78+
def test_format_non_numeric_na():
79+
# GH 21527 28358
80+
df = DataFrame(
81+
{
82+
"object": [None, np.nan, "foo"],
83+
"datetime": [None, NaT, Timestamp("20120101")],
84+
}
85+
)
86+
87+
with tm.assert_produces_warning(FutureWarning):
88+
ctx = df.style.set_na_rep("NA")._translate()
89+
assert ctx["body"][0][1]["display_value"] == "NA"
90+
assert ctx["body"][0][2]["display_value"] == "NA"
91+
assert ctx["body"][1][1]["display_value"] == "NA"
92+
assert ctx["body"][1][2]["display_value"] == "NA"
93+
94+
ctx = df.style.format(None, na_rep="-")._translate()
95+
assert ctx["body"][0][1]["display_value"] == "-"
96+
assert ctx["body"][0][2]["display_value"] == "-"
97+
assert ctx["body"][1][1]["display_value"] == "-"
98+
assert ctx["body"][1][2]["display_value"] == "-"
99+
100+
101+
def test_format_clear(styler):
102+
assert (0, 0) not in styler._display_funcs # using default
103+
styler.format("{:.2f")
104+
assert (0, 0) in styler._display_funcs # formatter is specified
105+
styler.format()
106+
assert (0, 0) not in styler._display_funcs # formatter cleared to default
107+
108+
109+
def test_format_escape():
110+
df = DataFrame([['<>&"']])
111+
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=False)
112+
expected = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>'
113+
assert expected in s.render()
114+
115+
# only the value should be escaped before passing to the formatter
116+
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True)
117+
ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'
118+
assert ex in s.render()
119+
120+
121+
def test_format_escape_na_rep():
122+
# tests the na_rep is not escaped
123+
df = DataFrame([['<>&"', None]])
124+
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True, na_rep="&")
125+
ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'
126+
expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>'
127+
assert ex in s.render()
128+
assert expected2 in s.render()
129+
130+
131+
def test_format_escape_floats(styler):
132+
# test given formatter for number format is not impacted by escape
133+
s = styler.format("{:.1f}", escape=True)
134+
for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]:
135+
assert expected in s.render()
136+
# tests precision of floats is not impacted by escape
137+
s = styler.format(precision=1, escape=True)
138+
for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]:
139+
assert expected in s.render()
140+
141+
142+
@pytest.mark.parametrize("formatter", [5, True, [2.0]])
143+
def test_format_raises(styler, formatter):
144+
with pytest.raises(TypeError, match="expected str or callable"):
145+
styler.format(formatter)
146+
147+
148+
def test_format_with_precision():
149+
# Issue #13257
150+
df = DataFrame(data=[[1.0, 2.0090], [3.2121, 4.566]], columns=["a", "b"])
151+
s = Styler(df)
152+
153+
ctx = s.format(precision=1)._translate()
154+
assert ctx["body"][0][1]["display_value"] == "1.0"
155+
assert ctx["body"][0][2]["display_value"] == "2.0"
156+
assert ctx["body"][1][1]["display_value"] == "3.2"
157+
assert ctx["body"][1][2]["display_value"] == "4.6"
158+
159+
ctx = s.format(precision=2)._translate()
160+
assert ctx["body"][0][1]["display_value"] == "1.00"
161+
assert ctx["body"][0][2]["display_value"] == "2.01"
162+
assert ctx["body"][1][1]["display_value"] == "3.21"
163+
assert ctx["body"][1][2]["display_value"] == "4.57"
164+
165+
ctx = s.format(precision=3)._translate()
166+
assert ctx["body"][0][1]["display_value"] == "1.000"
167+
assert ctx["body"][0][2]["display_value"] == "2.009"
168+
assert ctx["body"][1][1]["display_value"] == "3.212"
169+
assert ctx["body"][1][2]["display_value"] == "4.566"
170+
171+
172+
def test_format_subset():
173+
df = DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])
174+
ctx = df.style.format(
175+
{"a": "{:0.1f}", "b": "{0:.2%}"}, subset=IndexSlice[0, :]
176+
)._translate()
177+
expected = "0.1"
178+
raw_11 = "1.123400"
179+
assert ctx["body"][0][1]["display_value"] == expected
180+
assert ctx["body"][1][1]["display_value"] == raw_11
181+
assert ctx["body"][0][2]["display_value"] == "12.34%"
182+
183+
ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, :])._translate()
184+
assert ctx["body"][0][1]["display_value"] == expected
185+
assert ctx["body"][1][1]["display_value"] == raw_11
186+
187+
ctx = df.style.format("{:0.1f}", subset=IndexSlice["a"])._translate()
188+
assert ctx["body"][0][1]["display_value"] == expected
189+
assert ctx["body"][0][2]["display_value"] == "0.123400"
190+
191+
ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, "a"])._translate()
192+
assert ctx["body"][0][1]["display_value"] == expected
193+
assert ctx["body"][1][1]["display_value"] == raw_11
194+
195+
ctx = df.style.format("{:0.1f}", subset=IndexSlice[[0, 1], ["a"]])._translate()
196+
assert ctx["body"][0][1]["display_value"] == expected
197+
assert ctx["body"][1][1]["display_value"] == "1.1"
198+
assert ctx["body"][0][2]["display_value"] == "0.123400"
199+
assert ctx["body"][1][2]["display_value"] == raw_11

pandas/tests/io/formats/style/test_style.py

-156
Original file line numberDiff line numberDiff line change
@@ -575,24 +575,6 @@ def test_duplicate(self):
575575
]
576576
assert result == expected
577577

578-
def test_format_with_na_rep(self):
579-
# GH 21527 28358
580-
df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
581-
582-
ctx = df.style.format(None, na_rep="-")._translate()
583-
assert ctx["body"][0][1]["display_value"] == "-"
584-
assert ctx["body"][0][2]["display_value"] == "-"
585-
586-
ctx = df.style.format("{:.2%}", na_rep="-")._translate()
587-
assert ctx["body"][0][1]["display_value"] == "-"
588-
assert ctx["body"][0][2]["display_value"] == "-"
589-
assert ctx["body"][1][1]["display_value"] == "110.00%"
590-
assert ctx["body"][1][2]["display_value"] == "120.00%"
591-
592-
ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate()
593-
assert ctx["body"][0][2]["display_value"] == "-"
594-
assert ctx["body"][1][2]["display_value"] == "120.00%"
595-
596578
def test_init_with_na_rep(self):
597579
# GH 21527 28358
598580
df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
@@ -619,65 +601,6 @@ def test_set_na_rep(self):
619601
assert ctx["body"][0][1]["display_value"] == "NA"
620602
assert ctx["body"][0][2]["display_value"] == "-"
621603

622-
def test_format_non_numeric_na(self):
623-
# GH 21527 28358
624-
df = DataFrame(
625-
{
626-
"object": [None, np.nan, "foo"],
627-
"datetime": [None, pd.NaT, pd.Timestamp("20120101")],
628-
}
629-
)
630-
631-
with tm.assert_produces_warning(FutureWarning):
632-
ctx = df.style.set_na_rep("NA")._translate()
633-
assert ctx["body"][0][1]["display_value"] == "NA"
634-
assert ctx["body"][0][2]["display_value"] == "NA"
635-
assert ctx["body"][1][1]["display_value"] == "NA"
636-
assert ctx["body"][1][2]["display_value"] == "NA"
637-
638-
ctx = df.style.format(None, na_rep="-")._translate()
639-
assert ctx["body"][0][1]["display_value"] == "-"
640-
assert ctx["body"][0][2]["display_value"] == "-"
641-
assert ctx["body"][1][1]["display_value"] == "-"
642-
assert ctx["body"][1][2]["display_value"] == "-"
643-
644-
def test_format_clear(self):
645-
assert (0, 0) not in self.styler._display_funcs # using default
646-
self.styler.format("{:.2f")
647-
assert (0, 0) in self.styler._display_funcs # formatter is specified
648-
self.styler.format()
649-
assert (0, 0) not in self.styler._display_funcs # formatter cleared to default
650-
651-
def test_format_escape(self):
652-
df = DataFrame([['<>&"']])
653-
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=False)
654-
expected = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>'
655-
assert expected in s.render()
656-
657-
# only the value should be escaped before passing to the formatter
658-
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True)
659-
ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'
660-
assert ex in s.render()
661-
662-
def test_format_escape_na_rep(self):
663-
# tests the na_rep is not escaped
664-
df = DataFrame([['<>&"', None]])
665-
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True, na_rep="&")
666-
ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'
667-
expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>'
668-
assert ex in s.render()
669-
assert expected2 in s.render()
670-
671-
def test_format_escape_floats(self):
672-
# test given formatter for number format is not impacted by escape
673-
s = self.df.style.format("{:.1f}", escape=True)
674-
for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]:
675-
assert expected in s.render()
676-
# tests precision of floats is not impacted by escape
677-
s = self.df.style.format(precision=1, escape=True)
678-
for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]:
679-
assert expected in s.render()
680-
681604
def test_nonunique_raises(self):
682605
df = DataFrame([[1, 2]], columns=["A", "A"])
683606
msg = "style is not supported for non-unique indices."
@@ -804,85 +727,6 @@ def test_export(self):
804727
assert style1._todo == style2._todo
805728
style2.render()
806729

807-
def test_display_format(self):
808-
df = DataFrame(np.random.random(size=(2, 2)))
809-
ctx = df.style.format("{:0.1f}")._translate()
810-
811-
assert all(["display_value" in c for c in row] for row in ctx["body"])
812-
assert all(
813-
[len(c["display_value"]) <= 3 for c in row[1:]] for row in ctx["body"]
814-
)
815-
assert len(ctx["body"][0][1]["display_value"].lstrip("-")) <= 3
816-
817-
@pytest.mark.parametrize("formatter", [5, True, [2.0]])
818-
def test_format_raises(self, formatter):
819-
with pytest.raises(TypeError, match="expected str or callable"):
820-
self.df.style.format(formatter)
821-
822-
def test_format_with_precision(self):
823-
# Issue #13257
824-
df = DataFrame(data=[[1.0, 2.0090], [3.2121, 4.566]], columns=["a", "b"])
825-
s = Styler(df)
826-
827-
ctx = s.format(precision=1)._translate()
828-
assert ctx["body"][0][1]["display_value"] == "1.0"
829-
assert ctx["body"][0][2]["display_value"] == "2.0"
830-
assert ctx["body"][1][1]["display_value"] == "3.2"
831-
assert ctx["body"][1][2]["display_value"] == "4.6"
832-
833-
ctx = s.format(precision=2)._translate()
834-
assert ctx["body"][0][1]["display_value"] == "1.00"
835-
assert ctx["body"][0][2]["display_value"] == "2.01"
836-
assert ctx["body"][1][1]["display_value"] == "3.21"
837-
assert ctx["body"][1][2]["display_value"] == "4.57"
838-
839-
ctx = s.format(precision=3)._translate()
840-
assert ctx["body"][0][1]["display_value"] == "1.000"
841-
assert ctx["body"][0][2]["display_value"] == "2.009"
842-
assert ctx["body"][1][1]["display_value"] == "3.212"
843-
assert ctx["body"][1][2]["display_value"] == "4.566"
844-
845-
def test_format_subset(self):
846-
df = DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])
847-
ctx = df.style.format(
848-
{"a": "{:0.1f}", "b": "{0:.2%}"}, subset=pd.IndexSlice[0, :]
849-
)._translate()
850-
expected = "0.1"
851-
raw_11 = "1.123400"
852-
assert ctx["body"][0][1]["display_value"] == expected
853-
assert ctx["body"][1][1]["display_value"] == raw_11
854-
assert ctx["body"][0][2]["display_value"] == "12.34%"
855-
856-
ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, :])._translate()
857-
assert ctx["body"][0][1]["display_value"] == expected
858-
assert ctx["body"][1][1]["display_value"] == raw_11
859-
860-
ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice["a"])._translate()
861-
assert ctx["body"][0][1]["display_value"] == expected
862-
assert ctx["body"][0][2]["display_value"] == "0.123400"
863-
864-
ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, "a"])._translate()
865-
assert ctx["body"][0][1]["display_value"] == expected
866-
assert ctx["body"][1][1]["display_value"] == raw_11
867-
868-
ctx = df.style.format(
869-
"{:0.1f}", subset=pd.IndexSlice[[0, 1], ["a"]]
870-
)._translate()
871-
assert ctx["body"][0][1]["display_value"] == expected
872-
assert ctx["body"][1][1]["display_value"] == "1.1"
873-
assert ctx["body"][0][2]["display_value"] == "0.123400"
874-
assert ctx["body"][1][2]["display_value"] == raw_11
875-
876-
def test_format_dict(self):
877-
df = DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])
878-
ctx = df.style.format({"a": "{:0.1f}", "b": "{0:.2%}"})._translate()
879-
assert ctx["body"][0][1]["display_value"] == "0.1"
880-
assert ctx["body"][0][2]["display_value"] == "12.34%"
881-
df["c"] = ["aaa", "bbb"]
882-
ctx = df.style.format({"a": "{:0.1f}", "c": str.upper})._translate()
883-
assert ctx["body"][0][1]["display_value"] == "0.1"
884-
assert ctx["body"][0][3]["display_value"] == "AAA"
885-
886730
def test_bad_apply_shape(self):
887731
df = DataFrame([[1, 2], [3, 4]])
888732
msg = "returned the wrong shape"

0 commit comments

Comments
 (0)