Skip to content

CLN: replace %s syntax with .format in tests.io.formats/json/sas #18351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions pandas/tests/io/formats/test_css.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,25 +69,25 @@ def test_css_parse_invalid(invalid_css, remainder):
def test_css_side_shorthands(shorthand, expansions):
top, right, bottom, left = expansions

assert_resolves('%s: 1pt' % shorthand,
assert_resolves('{shorthand}: 1pt'.format(shorthand=shorthand),
{top: '1pt', right: '1pt',
bottom: '1pt', left: '1pt'})

assert_resolves('%s: 1pt 4pt' % shorthand,
assert_resolves('{shorthand}: 1pt 4pt'.format(shorthand=shorthand),
{top: '1pt', right: '4pt',
bottom: '1pt', left: '4pt'})

assert_resolves('%s: 1pt 4pt 2pt' % shorthand,
assert_resolves('{shorthand}: 1pt 4pt 2pt'.format(shorthand=shorthand),
{top: '1pt', right: '4pt',
bottom: '2pt', left: '4pt'})

assert_resolves('%s: 1pt 4pt 2pt 0pt' % shorthand,
assert_resolves('{shorthand}: 1pt 4pt 2pt 0pt'.format(shorthand=shorthand),
{top: '1pt', right: '4pt',
bottom: '2pt', left: '0pt'})

with tm.assert_produces_warning(CSSWarning):
assert_resolves('%s: 1pt 1pt 1pt 1pt 1pt' % shorthand,
{})
assert_resolves(
'{shorthand}: 1pt 1pt 1pt 1pt 1pt'.format(shorthand=shorthand), {})


@pytest.mark.parametrize('style,inherited,equiv', [
Expand Down Expand Up @@ -127,10 +127,10 @@ def test_css_none_absent(style, equiv):

@pytest.mark.parametrize('size,resolved', [
('xx-small', '6pt'),
('x-small', '%fpt' % 7.5),
('small', '%fpt' % 9.6),
('x-small', '{pt:f}pt'.format(pt=7.5)),
('small', '{pt:f}pt'.format(pt=9.6)),
('medium', '12pt'),
('large', '%fpt' % 13.5),
('large', '{pt:f}pt'.format(pt=13.5)),
('x-large', '18pt'),
('xx-large', '24pt'),

Expand All @@ -149,8 +149,8 @@ def test_css_absolute_font_size(size, relative_to, resolved):
inherited = None
else:
inherited = {'font-size': relative_to}
assert_resolves('font-size: %s' % size, {'font-size': resolved},
inherited=inherited)
assert_resolves('font-size: {size}'.format(size=size),
{'font-size': resolved}, inherited=inherited)


@pytest.mark.parametrize('size,relative_to,resolved', [
Expand All @@ -174,13 +174,13 @@ def test_css_absolute_font_size(size, relative_to, resolved):

('smaller', None, '10pt'),
('smaller', '18pt', '15pt'),
('larger', None, '%fpt' % 14.4),
('larger', None, '{pt:f}pt'.format(pt=14.4)),
('larger', '15pt', '18pt'),
])
def test_css_relative_font_size(size, relative_to, resolved):
if relative_to is None:
inherited = None
else:
inherited = {'font-size': relative_to}
assert_resolves('font-size: %s' % size, {'font-size': resolved},
inherited=inherited)
assert_resolves('font-size: {size}'.format(size=size),
{'font-size': resolved}, inherited=inherited)
27 changes: 14 additions & 13 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def test_repr_max_columns_max_rows(self):
"{0} x {1}".format(term_width, term_height))

def mkframe(n):
index = ['%05d' % i for i in range(n)]
index = ['{i:05d}'.format(i=i) for i in range(n)]
return DataFrame(0, index, index)

df6 = mkframe(6)
Expand Down Expand Up @@ -465,9 +465,9 @@ def test_to_string_with_formatters(self):
'object': [(1, 2), True, False]},
columns=['int', 'float', 'object'])

formatters = [('int', lambda x: '0x%x' % x),
('float', lambda x: '[% 4.1f]' % x),
('object', lambda x: '-%s-' % str(x))]
formatters = [('int', lambda x: '0x{x:x}'.format(x=x)),
('float', lambda x: '[{x: 4.1f}]'.format(x=x)),
('object', lambda x: '-{x!s}-'.format(x=x))]
result = df.to_string(formatters=dict(formatters))
result2 = df.to_string(formatters=lzip(*formatters)[1])
assert result == (' int float object\n'
Expand Down Expand Up @@ -500,7 +500,8 @@ def format_func(x):

def test_to_string_with_formatters_unicode(self):
df = DataFrame({u('c/\u03c3'): [1, 2, 3]})
result = df.to_string(formatters={u('c/\u03c3'): lambda x: '%s' % x})
result = df.to_string(
formatters={u('c/\u03c3'): lambda x: '{x}'.format(x=x)})
assert result == u(' c/\u03c3\n') + '0 1\n1 2\n2 3'

def test_east_asian_unicode_frame(self):
Expand Down Expand Up @@ -944,7 +945,7 @@ def test_wide_repr(self):
set_option('display.expand_frame_repr', False)
rep_str = repr(df)

assert "10 rows x %d columns" % (max_cols - 1) in rep_str
assert "10 rows x {c} columns".format(c=max_cols - 1) in rep_str
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
assert rep_str != wide_repr
Expand Down Expand Up @@ -1056,7 +1057,7 @@ def test_long_series(self):
n = 1000
s = Series(
np.random.randint(-50, 50, n),
index=['s%04d' % x for x in range(n)], dtype='int64')
index=['s{x:04d}'.format(x=x) for x in range(n)], dtype='int64')

import re
str_rep = str(s)
Expand Down Expand Up @@ -1174,7 +1175,7 @@ def test_to_string(self):
assert header == expected

biggie.to_string(columns=['B', 'A'],
formatters={'A': lambda x: '%.1f' % x})
formatters={'A': lambda x: '{x:.1f}'.format(x=x)})

biggie.to_string(columns=['B', 'A'], float_format=str)
biggie.to_string(columns=['B', 'A'], col_space=12, float_format=str)
Expand Down Expand Up @@ -1269,7 +1270,7 @@ def test_to_string_small_float_values(self):

result = df.to_string()
# sadness per above
if '%.4g' % 1.7e8 == '1.7e+008':
if '{x:.4g}'.format(x=1.7e8) == '1.7e+008':
expected = (' a\n'
'0 1.500000e+000\n'
'1 1.000000e-017\n'
Expand Down Expand Up @@ -1456,7 +1457,7 @@ def test_repr_html_long(self):
long_repr = df._repr_html_()
assert '..' in long_repr
assert str(41 + max_rows // 2) not in long_repr
assert u('%d rows ') % h in long_repr
assert u('{h} rows ').format(h=h) in long_repr
assert u('2 columns') in long_repr

def test_repr_html_float(self):
Expand All @@ -1478,7 +1479,7 @@ def test_repr_html_float(self):
long_repr = df._repr_html_()
assert '..' in long_repr
assert '31' not in long_repr
assert u('%d rows ') % h in long_repr
assert u('{h} rows ').format(h=h) in long_repr
assert u('2 columns') in long_repr

def test_repr_html_long_multiindex(self):
Expand Down Expand Up @@ -1673,7 +1674,7 @@ def test_to_string(self):
result = cp.to_string(length=True, name=True, dtype=True)
last_line = result.split('\n')[-1].strip()
assert last_line == ("Freq: B, Name: foo, "
"Length: %d, dtype: float64" % len(cp))
"Length: {cp}, dtype: float64".format(cp=len(cp)))

def test_freq_name_separation(self):
s = Series(np.random.randn(10),
Expand Down Expand Up @@ -2176,7 +2177,7 @@ def test_to_string_header(self):


def _three_digit_exp():
return '%.4g' % 1.7e8 == '1.7e+008'
return '{x:.4g}'.format(x=1.7e8) == '1.7e+008'


class TestFloatArrayFormatter(object):
Expand Down
8 changes: 5 additions & 3 deletions pandas/tests/io/formats/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def setup_method(self, method):
self.g = lambda x: x

def h(x, foo='bar'):
return pd.Series(['color: %s' % foo], index=x.index, name=x.name)
return pd.Series(
['color: {foo}'.format(foo=foo)], index=x.index, name=x.name)

self.h = h
self.styler = Styler(self.df)
Expand Down Expand Up @@ -214,7 +215,7 @@ def test_numeric_columns(self):

def test_apply_axis(self):
df = pd.DataFrame({'A': [0, 0], 'B': [1, 1]})
f = lambda x: ['val: %s' % x.max() for v in x]
f = lambda x: ['val: {max}'.format(max=x.max()) for v in x]
result = df.style.apply(f, axis=1)
assert len(result._todo) == 1
assert len(result.ctx) == 0
Expand Down Expand Up @@ -658,7 +659,8 @@ def test_highlight_max(self):

def test_export(self):
f = lambda x: 'color: red' if x > 0 else 'color: blue'
g = lambda x, y, z: 'color: %s' if x > 0 else 'color: %s' % z
g = lambda x, y, z: 'color: {z}'.format(z=z) \
if x > 0 else 'color: {z}'.format(z=z)
style1 = self.styler
style1.applymap(f)\
.applymap(g, y='a', z='b')\
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/formats/test_to_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -1435,7 +1435,7 @@ def test_to_html(self):

biggie.to_html(columns=['B', 'A'], col_space=17)
biggie.to_html(columns=['B', 'A'],
formatters={'A': lambda x: '%.1f' % x})
formatters={'A': lambda x: '{x:.1f}'.format(x=x)})

biggie.to_html(columns=['B', 'A'], float_format=str)
biggie.to_html(columns=['B', 'A'], col_space=12, float_format=str)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/io/formats/test_to_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,11 @@ def test_to_latex_with_formatters(self):
datetime(2016, 2, 5),
datetime(2016, 3, 3)]})

formatters = {'int': lambda x: '0x%x' % x,
'float': lambda x: '[% 4.1f]' % x,
'object': lambda x: '-%s-' % str(x),
formatters = {'int': lambda x: '0x{x:x}'.format(x=x),
'float': lambda x: '[{x: 4.1f}]'.format(x=x),
'object': lambda x: '-{x!s}-'.format(x=x),
'datetime64': lambda x: x.strftime('%Y-%m'),
'__index__': lambda x: 'index: %s' % x}
'__index__': lambda x: 'index: {x}'.format(x=x)}
result = df.to_latex(formatters=dict(formatters))

expected = r"""\begin{tabular}{llrrl}
Expand Down
10 changes: 6 additions & 4 deletions pandas/tests/io/json/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,8 @@ def __str__(self):

# verify the proper conversion of printable content
df_printable = DataFrame({'A': [binthing.hexed]})
assert df_printable.to_json() == '{"A":{"0":"%s"}}' % hexed
assert df_printable.to_json() == \
'{{"A":{{"0":"{hex}"}}}}'.format(hex=hexed)

# check if non-printable content throws appropriate Exception
df_nonprintable = DataFrame({'A': [binthing]})
Expand All @@ -546,15 +547,16 @@ def __str__(self):

# default_handler should resolve exceptions for non-string types
assert df_nonprintable.to_json(default_handler=str) == \
'{"A":{"0":"%s"}}' % hexed
'{{"A":{{"0":"{hex}"}}}}'.format(hex=hexed)
assert df_mixed.to_json(default_handler=str) == \
'{"A":{"0":"%s"},"B":{"0":1}}' % hexed
'{{"A":{{"0":"{hex}"}},"B":{{"0":1}}}}'.format(hex=hexed)

def test_label_overflow(self):
# GH14256: buffer length not checked when writing label
df = pd.DataFrame({'foo': [1337], 'bar' * 100000: [1]})
assert df.to_json() == \
'{"%s":{"0":1},"foo":{"0":1337}}' % ('bar' * 100000)
'{{"{bar}":{{"0":1}},"foo":{{"0":1337}}}}'.format(
bar=('bar' * 100000))

def test_series_non_unique_index(self):
s = Series(['a', 'b'], index=[1, 1])
Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/io/json/test_readlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_readjson_chunks_closes(chunksize):
lines=True, chunksize=chunksize, compression=None)
reader.read()
assert reader.open_stream.closed, "didn't close stream with \
chunksize = %s" % chunksize
chunksize = {chunksize}".format(chunksize=chunksize)


@pytest.mark.parametrize("chunksize", [0, -1, 2.2, "foo"])
Expand Down Expand Up @@ -165,4 +165,5 @@ def test_readjson_chunks_multiple_empty_lines(chunksize):
test = pd.read_json(j, lines=True, chunksize=chunksize)
if chunksize is not None:
test = pd.concat(test)
tm.assert_frame_equal(orig, test, obj="chunksize: %s" % chunksize)
tm.assert_frame_equal(
orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize))
12 changes: 6 additions & 6 deletions pandas/tests/io/json/test_ujson.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,21 +394,21 @@ def test_encodeTimeConversion(self):
]
for test in tests:
output = ujson.encode(test)
expected = '"%s"' % test.isoformat()
expected = '"{iso}"'.format(iso=test.isoformat())
assert expected == output

def test_encodeTimeConversion_pytz(self):
# see gh-11473: to_json segfaults with timezone-aware datetimes
test = datetime.time(10, 12, 15, 343243, pytz.utc)
output = ujson.encode(test)
expected = '"%s"' % test.isoformat()
expected = '"{iso}"'.format(iso=test.isoformat())
assert expected == output

def test_encodeTimeConversion_dateutil(self):
# see gh-11473: to_json segfaults with timezone-aware datetimes
test = datetime.time(10, 12, 15, 343243, dateutil.tz.tzutc())
output = ujson.encode(test)
expected = '"%s"' % test.isoformat()
expected = '"{iso}"'.format(iso=test.isoformat())
assert expected == output

def test_nat(self):
Expand Down Expand Up @@ -856,9 +856,9 @@ def test_decodeNumberWith32bitSignBit(self):
boundary2 = 2**32 # noqa
docs = (
'{"id": 3590016419}',
'{"id": %s}' % 2**31,
'{"id": %s}' % 2**32,
'{"id": %s}' % ((2**32) - 1),
'{{"id": {low}}}'.format(low=2**31),
'{{"id": {high}}}'.format(high=2**32),
'{{"id": {one_less}}}'.format(one_less=(2**32) - 1),
)
results = (3590016419, 2**31, 2**32, 2**32 - 1)
for doc, result in zip(docs, results):
Expand Down
24 changes: 15 additions & 9 deletions pandas/tests/io/sas/test_sas7bdat.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ def setup_method(self, method):
self.data = []
self.test_ix = [list(range(1, 16)), [16]]
for j in 1, 2:
fname = os.path.join(self.dirpath, "test_sas7bdat_%d.csv" % j)
fname = os.path.join(
self.dirpath, "test_sas7bdat_{j}.csv".format(j=j))
df = pd.read_csv(fname)
epoch = pd.datetime(1960, 1, 1)
t1 = pd.to_timedelta(df["Column4"], unit='d')
Expand All @@ -37,15 +38,17 @@ def test_from_file(self):
for j in 0, 1:
df0 = self.data[j]
for k in self.test_ix[j]:
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
fname = os.path.join(
self.dirpath, "test{k}.sas7bdat".format(k=k))
df = pd.read_sas(fname, encoding='utf-8')
tm.assert_frame_equal(df, df0)

def test_from_buffer(self):
for j in 0, 1:
df0 = self.data[j]
for k in self.test_ix[j]:
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
fname = os.path.join(
self.dirpath, "test{k}.sas7bdat".format(k=k))
with open(fname, 'rb') as f:
byts = f.read()
buf = io.BytesIO(byts)
Expand All @@ -59,7 +62,8 @@ def test_from_iterator(self):
for j in 0, 1:
df0 = self.data[j]
for k in self.test_ix[j]:
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
fname = os.path.join(
self.dirpath, "test{k}.sas7bdat".format(k=k))
rdr = pd.read_sas(fname, iterator=True, encoding='utf-8')
df = rdr.read(2)
tm.assert_frame_equal(df, df0.iloc[0:2, :])
Expand All @@ -73,7 +77,8 @@ def test_path_pathlib(self):
for j in 0, 1:
df0 = self.data[j]
for k in self.test_ix[j]:
fname = Path(os.path.join(self.dirpath, "test%d.sas7bdat" % k))
fname = Path(os.path.join(
self.dirpath, "test{k}.sas7bdat".format(k=k)))
df = pd.read_sas(fname, encoding='utf-8')
tm.assert_frame_equal(df, df0)

Expand All @@ -83,8 +88,8 @@ def test_path_localpath(self):
for j in 0, 1:
df0 = self.data[j]
for k in self.test_ix[j]:
fname = LocalPath(os.path.join(self.dirpath,
"test%d.sas7bdat" % k))
fname = LocalPath(os.path.join(
self.dirpath, "test{k}.sas7bdat".format(k=k)))
df = pd.read_sas(fname, encoding='utf-8')
tm.assert_frame_equal(df, df0)

Expand All @@ -93,7 +98,8 @@ def test_iterator_loop(self):
for j in 0, 1:
for k in self.test_ix[j]:
for chunksize in 3, 5, 10, 11:
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
fname = os.path.join(
self.dirpath, "test{k}.sas7bdat".format(k=k))
rdr = pd.read_sas(fname, chunksize=10, encoding='utf-8')
y = 0
for x in rdr:
Expand All @@ -104,7 +110,7 @@ def test_iterator_loop(self):
def test_iterator_read_too_much(self):
# github #14734
k = self.test_ix[0][0]
fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k)
fname = os.path.join(self.dirpath, "test{k}.sas7bdat".format(k=k))
rdr = pd.read_sas(fname, format="sas7bdat",
iterator=True, encoding='utf-8')
d1 = rdr.read(rdr.row_count + 20)
Expand Down