8000 [3.12] gh-109546: Add more tests for formatting floats and fractions (GH-109548) by miss-islington · Pull Request #109557 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

[3.12] gh-109546: Add more tests for formatting floats and fractions (GH-109548) #109557

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 1 commit into from
Oct 2, 2023
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
9 changes: 7 additions & 2 deletions Lib/test/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,8 +733,13 @@ def test_format_testfile(self):

lhs, rhs = map(str.strip, line.split('->'))
fmt, arg = lhs.split()
self.assertEqual(fmt % float(arg), rhs)
self.assertEqual(fmt % -float(arg), '-' + rhs)
f = float(arg)
self.assertEqual(fmt % f, rhs)
self.assertEqual(fmt % -f, '-' + rhs)
if fmt != '%r':
fmt2 = fmt[1:]
self.assertEqual(format(f, fmt2), rhs)
self.assertEqual(format(-f, fmt2), '-' + rhs)

def test_issue5864(self):
self.assertEqual(format(123.456, '.4'), '123.5')
Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import operator
import fractions
import functools
import os
import sys
import typing
import unittest
Expand All @@ -15,6 +16,9 @@
from pickle import dumps, loads
F = fractions.Fraction

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

class DummyFloat(object):
"""Dummy float class for testing comparisons with Fractions"""
Expand Down Expand Up @@ -1220,6 +1224,30 @@ def test_invalid_formats(self):
with self.assertRaises(ValueError):
format(fraction, spec)

@requires_IEEE_754
def test_float_format_testfile(self):
with open(format_testfile, encoding="utf-8") as testfile:
for line in testfile:
if line.startswith('--'):
continue
line = line.strip()
if not line:
continue

lhs, rhs = map(str.strip, line.split('->'))
fmt, arg = lhs.split()
if fmt == '%r':
continue
fmt2 = fmt[1:]
with self.subTest(fmt=fmt, arg=arg):
f = F(float(arg))
self.assertEqual(format(f, fmt2), rhs)
if f: # skip negative zero
self.assertEqual(format(-f, fmt2), '-' + rhs)
f = F(arg)
self.assertEqual(float(format(f, fmt2)), float(rhs))
self.assertEqual(float(format(-f, fmt2)), float('-' + rhs))


if __name__ == '__main__':
unittest.main()
0