Skip to content

Commit 948747a

Browse files
gh-109546: Add more tests for formatting floats and fractions
1 parent add16f1 commit 948747a

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

Lib/test/test_float.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -733,8 +733,12 @@ def test_format_testfile(self):
733733

734734
lhs, rhs = map(str.strip, line.split('->'))
735735
fmt, arg = lhs.split()
736-
self.assertEqual(fmt % float(arg), rhs)
737-
self.assertEqual(fmt % -float(arg), '-' + rhs)
736+
f = float(arg)
737+
self.assertEqual(fmt % f, rhs)
738+
self.assertEqual(fmt % -f, '-' + rhs)
739+
if fmt != '%r':
740+
self.assertEqual(format(f, fmt[1:]), rhs)
741+
self.assertEqual(format(-f, fmt[1:]), '-' + rhs)
738742

739743
def test_issue5864(self):
740744
self.assertEqual(format(123.456, '.4'), '123.5')

Lib/test/test_fractions.py

+24
Original file line numberDiff line numberDiff line change
@@ -1220,6 +1220,30 @@ def test_invalid_formats(self):
12201220
with self.assertRaises(ValueError):
12211221
format(fraction, spec)
12221222

1223+
@requires_IEEE_754
1224+
def test_float_format_testfile(self):
1225+
from test.test_float import format_testfile
1226+
with open(format_testfile, encoding="utf-8") as testfile:
1227+
for line in testfile:
1228+
if line.startswith('--'):
1229+
continue
1230+
line = line.strip()
1231+
if not line:
1232+
continue
1233+
1234+
lhs, rhs = map(str.strip, line.split('->'))
1235+
fmt, arg = lhs.split()
1236+
if fmt == '%r':
1237+
continue
1238+
with self.subTest(fmt=fmt, arg=arg):
1239+
f = F(float(arg))
1240+
self.assertEqual(format(f, fmt[1:]), rhs)
1241+
if f: # skip negative zero
1242+
self.assertEqual(format(-f, fmt[1:]), '-' + rhs)
1243+
f = F(arg)
1244+
self.assertEqual(float(format(f, fmt[1:])), float(rhs))
1245+
self.assertEqual(float(format(-f, fmt[1:])), float('-' + rhs))
1246+
12231247

12241248
if __name__ == '__main__':
12251249
unittest.main()

0 commit comments

Comments
 (0)