Skip to content

Commit beb5ec5

Browse files
gh-109546: Add more tests for formatting floats and fractions (GH-109548)
1 parent c829975 commit beb5ec5

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

Lib/test/test_float.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -733,8 +733,13 @@ 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+
fmt2 = fmt[1:]
741+
self.assertEqual(format(f, fmt2), rhs)
742+
self.assertEqual(format(-f, fmt2), '-' + rhs)
738743

739744
def test_issue5864(self):
740745
self.assertEqual(format(123.456, '.4'), '123.5')

Lib/test/test_fractions.py

+28
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import operator
88
import fractions
99
import functools
10+
import os
1011
import sys
1112
import typing
1213
import unittest
@@ -15,6 +16,9 @@
1516
from pickle import dumps, loads
1617
F = fractions.Fraction
1718

19+
#locate file with float format test values
20+
test_dir = os.path.dirname(__file__) or os.curdir
21+
format_testfile = os.path.join(test_dir, 'formatfloat_testcases.txt')
1822

1923
class DummyFloat(object):
2024
"""Dummy float class for testing comparisons with Fractions"""
@@ -1220,6 +1224,30 @@ def test_invalid_formats(self):
12201224
with self.assertRaises(ValueError):
12211225
format(fraction, spec)
12221226

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

12241252
if __name__ == '__main__':
12251253
unittest.main()

0 commit comments

Comments
 (0)