|
| 1 | +# PyOS_ascii_formatd is deprecated and not called from anywhere in |
| 2 | +# Python itself. So this module is the only place it gets tested. |
| 3 | +# Test that it works, and test that it's deprecated. |
| 4 | + |
| 5 | +import unittest |
| 6 | +from test.support import check_warnings, run_unittest, cpython_only |
| 7 | + |
| 8 | +class FormatDeprecationTests(unittest.TestCase): |
| 9 | + |
| 10 | + @cpython_only |
| 11 | + def testFormatDeprecation(self): |
| 12 | + # delay importing ctypes until we know we're in CPython |
| 13 | + from ctypes import (pythonapi, create_string_buffer, sizeof, byref, |
| 14 | + c_double) |
| 15 | + PyOS_ascii_formatd = pythonapi.PyOS_ascii_formatd |
| 16 | + buf = create_string_buffer(100) |
| 17 | + |
| 18 | + with check_warnings() as w: |
| 19 | + PyOS_ascii_formatd(byref(buf), sizeof(buf), b'%+.10f', |
| 20 | + c_double(10.0)) |
| 21 | + self.assertEqual(buf.value, b'+10.0000000000') |
| 22 | + |
| 23 | + self.assertEqual(str(w.message), 'PyOS_ascii_formatd is deprecated, ' |
| 24 | + 'use PyOS_double_to_string instead') |
| 25 | + |
| 26 | +class FormatTests(unittest.TestCase): |
| 27 | + # ensure that, for the restricted set of format codes, |
| 28 | + # %-formatting returns the same values os PyOS_ascii_formatd |
| 29 | + @cpython_only |
| 30 | + def testFormat(self): |
| 31 | + # delay importing ctypes until we know we're in CPython |
| 32 | + from ctypes import (pythonapi, create_string_buffer, sizeof, byref, |
| 33 | + c_double) |
| 34 | + PyOS_ascii_formatd = pythonapi.PyOS_ascii_formatd |
| 35 | + buf = create_string_buffer(100) |
| 36 | + |
| 37 | + tests = [ |
| 38 | + ('%f', 100.0), |
| 39 | + ('%g', 100.0), |
| 40 | + ('%#g', 100.0), |
| 41 | + ('%#.2g', 100.0), |
| 42 | + ('%#.2g', 123.4567), |
| 43 | + ('%#.2g', 1.234567e200), |
| 44 | + ('%e', 1.234567e200), |
| 45 | + ('%e', 1.234), |
| 46 | + ('%+e', 1.234), |
| 47 | + ('%-e', 1.234), |
| 48 | + ] |
| 49 | + |
| 50 | + with check_warnings(): |
| 51 | + for format, val in tests: |
| 52 | + PyOS_ascii_formatd(byref(buf), sizeof(buf), |
| 53 | + bytes(format, 'ascii'), |
| 54 | + c_double(val)) |
| 55 | + self.assertEqual(buf.value, bytes(format % val, 'ascii')) |
| 56 | + |
| 57 | + |
| 58 | +def test_main(): |
| 59 | + run_unittest(FormatDeprecationTests, FormatTests) |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + test_main() |
0 commit comments