Issue #20532: Tests which use _testcapi now are marked as CPython only.

This commit is contained in:
Serhiy Storchaka 2014-02-07 10:10:55 +02:00
commit f28ba369dd
29 changed files with 284 additions and 118 deletions

View File

@ -5,7 +5,6 @@ Common tests shared by test_str, test_unicode, test_userstring and test_string.
import unittest, string, sys, struct import unittest, string, sys, struct
from test import support from test import support
from collections import UserList from collections import UserList
import _testcapi
class Sequence: class Sequence:
def __init__(self, seq='wxyz'): self.seq = seq def __init__(self, seq='wxyz'): self.seq = seq
@ -1199,20 +1198,28 @@ class MixinStrUnicodeUserStringTest:
# Outrageously large width or precision should raise ValueError. # Outrageously large width or precision should raise ValueError.
self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2)) self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2))
self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2)) self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2))
self.checkraises(OverflowError, '%*s', '__mod__', self.checkraises(OverflowError, '%*s', '__mod__',
(_testcapi.PY_SSIZE_T_MAX + 1, '')) (sys.maxsize + 1, ''))
self.checkraises(OverflowError, '%.*f', '__mod__', self.checkraises(OverflowError, '%.*f', '__mod__',
(_testcapi.INT_MAX + 1, 1. / 7)) (sys.maxsize + 1, 1. / 7))
# Issue 15989
self.checkraises(OverflowError, '%*s', '__mod__',
(1 << (_testcapi.PY_SSIZE_T_MAX.bit_length() + 1), ''))
self.checkraises(OverflowError, '%.*f', '__mod__',
(_testcapi.UINT_MAX + 1, 1. / 7))
class X(object): pass class X(object): pass
self.checkraises(TypeError, 'abc', '__mod__', X()) self.checkraises(TypeError, 'abc', '__mod__', X())
@support.cpython_only
def test_formatting_c_limits(self):
from _testcapi import PY_SSIZE_T_MAX, INT_MAX, UINT_MAX
SIZE_MAX = (1 << (PY_SSIZE_T_MAX.bit_length() + 1)) - 1
self.checkraises(OverflowError, '%*s', '__mod__',
(PY_SSIZE_T_MAX + 1, ''))
self.checkraises(OverflowError, '%.*f', '__mod__',
(INT_MAX + 1, 1. / 7))
# Issue 15989
self.checkraises(OverflowError, '%*s', '__mod__',
(SIZE_MAX + 1, ''))
self.checkraises(OverflowError, '%.*f', '__mod__',
(UINT_MAX + 1, 1. / 7))
def test_floatformatting(self): def test_floatformatting(self):
# float formatting # float formatting
for prec in range(100): for prec in range(100):

View File

@ -25,7 +25,6 @@ import fnmatch
import logging.handlers import logging.handlers
import struct import struct
import tempfile import tempfile
import _testcapi
try: try:
import _thread, threading import _thread, threading
@ -1373,6 +1372,7 @@ _TPFLAGS_HAVE_GC = 1<<14
_TPFLAGS_HEAPTYPE = 1<<9 _TPFLAGS_HEAPTYPE = 1<<9
def check_sizeof(test, o, size): def check_sizeof(test, o, size):
import _testcapi
result = sys.getsizeof(o) result = sys.getsizeof(o)
# add GC header size # add GC header size
if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\ if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
@ -2172,4 +2172,5 @@ def run_in_subinterp(code):
raise unittest.SkipTest("run_in_subinterp() cannot be used " raise unittest.SkipTest("run_in_subinterp() cannot be used "
"if tracemalloc module is tracing " "if tracemalloc module is tracing "
"memory allocations") "memory allocations")
import _testcapi
return _testcapi.run_in_subinterp(code) return _testcapi.run_in_subinterp(code)

View File

@ -2,7 +2,6 @@ import sys
import unittest import unittest
import io import io
import atexit import atexit
import _testcapi
from test import support from test import support
### helpers ### helpers

View File

@ -18,7 +18,8 @@ try:
import threading import threading
except ImportError: except ImportError:
threading = None threading = None
import _testcapi # Skip this test if the _testcapi module isn't available.
_testcapi = support.import_module('_testcapi')
def testfunction(self): def testfunction(self):

View File

@ -104,7 +104,7 @@ consts: ('None',)
import unittest import unittest
import weakref import weakref
import _testcapi from test.support import run_doctest, run_unittest, cpython_only
def consts(t): def consts(t):
@ -126,7 +126,9 @@ def dump(co):
class CodeTest(unittest.TestCase): class CodeTest(unittest.TestCase):
@cpython_only
def test_newempty(self): def test_newempty(self):
import _testcapi
co = _testcapi.code_newempty("filename", "funcname", 15) co = _testcapi.code_newempty("filename", "funcname", 15)
self.assertEqual(co.co_filename, "filename") self.assertEqual(co.co_filename, "filename")
self.assertEqual(co.co_name, "funcname") self.assertEqual(co.co_name, "funcname")
@ -159,7 +161,6 @@ class CodeWeakRefTest(unittest.TestCase):
def test_main(verbose=None): def test_main(verbose=None):
from test.support import run_doctest, run_unittest
from test import test_code from test import test_code
run_doctest(test_code, verbose) run_doctest(test_code, verbose)
run_unittest(CodeTest, CodeWeakRefTest) run_unittest(CodeTest, CodeWeakRefTest)

View File

@ -1,4 +1,3 @@
import _testcapi
import codecs import codecs
import contextlib import contextlib
import io import io
@ -1760,7 +1759,7 @@ broken_incremental_coders = broken_unicode_with_streams + [
class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling): class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
def test_basics(self): def test_basics(self):
s = "abc123" # all codecs should be able to encode these s = "abc123" # all codecs should be able to encode these
for encoding in all_unicode_encodings: for encoding in all_unicode_encodings:
name = codecs.lookup(encoding).name name = codecs.lookup(encoding).name
if encoding.endswith("_codec"): if encoding.endswith("_codec"):
@ -1772,9 +1771,9 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
with support.check_warnings(): with support.check_warnings():
# unicode-internal has been deprecated # unicode-internal has been deprecated
(b, size) = codecs.getencoder(encoding)(s) (b, size) = codecs.getencoder(encoding)(s)
self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding)) self.assertEqual(size, len(s), "encoding=%r" % encoding)
(chars, size) = codecs.getdecoder(encoding)(b) (chars, size) = codecs.getdecoder(encoding)(b)
self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding)) self.assertEqual(chars, s, "encoding=%r" % encoding)
if encoding not in broken_unicode_with_streams: if encoding not in broken_unicode_with_streams:
# check stream reader/writer # check stream reader/writer
@ -1792,15 +1791,13 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
for c in encodedresult: for c in encodedresult:
q.write(bytes([c])) q.write(bytes([c]))
decodedresult += reader.read() decodedresult += reader.read()
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) self.assertEqual(decodedresult, s, "encoding=%r" % encoding)
if encoding not in broken_incremental_coders: if encoding not in broken_incremental_coders:
# check incremental decoder/encoder (fetched via the Python # check incremental decoder/encoder and iterencode()/iterdecode()
# and C API) and iterencode()/iterdecode()
try: try:
encoder = codecs.getincrementalencoder(encoding)() encoder = codecs.getincrementalencoder(encoding)()
cencoder = _testcapi.codec_incrementalencoder(encoding) except LookupError: # no IncrementalEncoder
except LookupError: # no IncrementalEncoder
pass pass
else: else:
# check incremental decoder/encoder # check incremental decoder/encoder
@ -1813,45 +1810,71 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
for c in encodedresult: for c in encodedresult:
decodedresult += decoder.decode(bytes([c])) decodedresult += decoder.decode(bytes([c]))
decodedresult += decoder.decode(b"", True) decodedresult += decoder.decode(b"", True)
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) self.assertEqual(decodedresult, s,
"encoding=%r" % encoding)
# check C API
encodedresult = b""
for c in s:
encodedresult += cencoder.encode(c)
encodedresult += cencoder.encode("", True)
cdecoder = _testcapi.codec_incrementaldecoder(encoding)
decodedresult = ""
for c in encodedresult:
decodedresult += cdecoder.decode(bytes([c]))
decodedresult += cdecoder.decode(b"", True)
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding))
# check iterencode()/iterdecode() # check iterencode()/iterdecode()
result = "".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding)) result = "".join(codecs.iterdecode(
self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding)) codecs.iterencode(s, encoding), encoding))
self.assertEqual(result, s, "encoding=%r" % encoding)
# check iterencode()/iterdecode() with empty string # check iterencode()/iterdecode() with empty string
result = "".join(codecs.iterdecode(codecs.iterencode("", encoding), encoding)) result = "".join(codecs.iterdecode(
codecs.iterencode("", encoding), encoding))
self.assertEqual(result, "") self.assertEqual(result, "")
if encoding not in ("idna", "mbcs"): if encoding not in ("idna", "mbcs"):
# check incremental decoder/encoder with errors argument # check incremental decoder/encoder with errors argument
try: try:
encoder = codecs.getincrementalencoder(encoding)("ignore") encoder = codecs.getincrementalencoder(encoding)("ignore")
cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore") except LookupError: # no IncrementalEncoder
except LookupError: # no IncrementalEncoder
pass pass
else: else:
encodedresult = b"".join(encoder.encode(c) for c in s) encodedresult = b"".join(encoder.encode(c) for c in s)
decoder = codecs.getincrementaldecoder(encoding)("ignore") decoder = codecs.getincrementaldecoder(encoding)("ignore")
decodedresult = "".join(decoder.decode(bytes([c])) for c in encodedresult) decodedresult = "".join(decoder.decode(bytes([c]))
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) for c in encodedresult)
self.assertEqual(decodedresult, s,
"encoding=%r" % encoding)
@support.cpython_only
def test_basics_capi(self):
from _testcapi import codec_incrementalencoder, codec_incrementaldecoder
s = "abc123" # all codecs should be able to encode these
for encoding in all_unicode_encodings:
if encoding not in broken_incremental_coders:
# check incremental decoder/encoder (fetched via the C API)
try:
cencoder = codec_incrementalencoder(encoding)
except LookupError: # no IncrementalEncoder
pass
else:
# check C API
encodedresult = b""
for c in s:
encodedresult += cencoder.encode(c)
encodedresult += cencoder.encode("", True)
cdecoder = codec_incrementaldecoder(encoding)
decodedresult = ""
for c in encodedresult:
decodedresult += cdecoder.decode(bytes([c]))
decodedresult += cdecoder.decode(b"", True)
self.assertEqual(decodedresult, s,
"encoding=%r" % encoding)
if encoding not in ("idna", "mbcs"):
# check incremental decoder/encoder with errors argument
try:
cencoder = codec_incrementalencoder(encoding, "ignore")
except LookupError: # no IncrementalEncoder
pass
else:
encodedresult = b"".join(cencoder.encode(c) for c in s) encodedresult = b"".join(cencoder.encode(c) for c in s)
cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore") cdecoder = codec_incrementaldecoder(encoding, "ignore")
decodedresult = "".join(cdecoder.decode(bytes([c])) for c in encodedresult) decodedresult = "".join(cdecoder.decode(bytes([c]))
self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) for c in encodedresult)
self.assertEqual(decodedresult, s,
"encoding=%r" % encoding)
def test_seek(self): def test_seek(self):
# all codecs should be able to encode these # all codecs should be able to encode these

View File

@ -2050,6 +2050,7 @@ order (MRO) for bases """
prop2 = property(fset=setter) prop2 = property(fset=setter)
self.assertEqual(prop2.__doc__, None) self.assertEqual(prop2.__doc__, None)
@support.cpython_only
def test_testcapi_no_segfault(self): def test_testcapi_no_segfault(self):
# this segfaulted in 2.5b2 # this segfaulted in 2.5b2
try: try:

View File

@ -7,8 +7,7 @@ import random
import select import select
import sys import sys
import unittest import unittest
from test.support import TESTFN, run_unittest from test.support import TESTFN, run_unittest, cpython_only
from _testcapi import USHRT_MAX
try: try:
select.devpoll select.devpoll
@ -121,15 +120,24 @@ class DevPollTests(unittest.TestCase):
self.addCleanup(devpoll.close) self.addCleanup(devpoll.close)
self.assertEqual(os.get_inheritable(devpoll.fileno()), False) self.assertEqual(os.get_inheritable(devpoll.fileno()), False)
def test_events_mask_overflow(self): def test_events_mask_overflow(self):
pollster = select.devpoll() pollster = select.devpoll()
w, r = os.pipe() w, r = os.pipe()
pollster.register(w) pollster.register(w)
# Issue #17919 # Issue #17919
self.assertRaises(OverflowError, pollster.register, 0, -1) self.assertRaises(OverflowError, pollster.register, 0, -1)
self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.register, 0, 1 << 64)
self.assertRaises(OverflowError, pollster.modify, 1, -1) self.assertRaises(OverflowError, pollster.modify, 1, -1)
self.assertRaises(OverflowError, pollster.modify, 1, 1 << 64)
@cpython_only
def test_events_mask_overflow_c_limits(self):
from _testcapi import USHRT_MAX
pollster = select.devpoll()
w, r = os.pipe()
pollster.register(w)
# Issue #17919
self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1)
self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1)

View File

@ -832,6 +832,7 @@ class ExceptionTests(unittest.TestCase):
self.assertIn("maximum recursion depth exceeded", str(v)) self.assertIn("maximum recursion depth exceeded", str(v))
@cpython_only
def test_MemoryError(self): def test_MemoryError(self):
# PyErr_NoMemory always raises the same exception instance. # PyErr_NoMemory always raises the same exception instance.
# Check that the traceback is not doubled. # Check that the traceback is not doubled.
@ -890,6 +891,7 @@ class ExceptionTests(unittest.TestCase):
self.assertEqual(error5.a, 1) self.assertEqual(error5.a, 1)
self.assertEqual(error5.__doc__, "") self.assertEqual(error5.__doc__, "")
@cpython_only
def test_memory_error_cleanup(self): def test_memory_error_cleanup(self):
# Issue #5437: preallocated MemoryError instances should not keep # Issue #5437: preallocated MemoryError instances should not keep
# traceback objects alive. # traceback objects alive.

View File

@ -4,9 +4,9 @@ import platform
import os import os
import struct import struct
import sys import sys
import _testcapi
import unittest import unittest
from test.support import verbose, TESTFN, unlink, run_unittest, import_module from test.support import (verbose, TESTFN, unlink, run_unittest, import_module,
cpython_only)
# Skip test if no fcntl module. # Skip test if no fcntl module.
fcntl = import_module('fcntl') fcntl = import_module('fcntl')
@ -45,6 +45,12 @@ def get_lockdata():
lockdata = get_lockdata() lockdata = get_lockdata()
class BadFile:
def __init__(self, fn):
self.fn = fn
def fileno(self):
return self.fn
class TestFcntl(unittest.TestCase): class TestFcntl(unittest.TestCase):
def setUp(self): def setUp(self):
@ -78,24 +84,27 @@ class TestFcntl(unittest.TestCase):
self.f.close() self.f.close()
def test_fcntl_bad_file(self): def test_fcntl_bad_file(self):
class F: with self.assertRaises(ValueError):
def __init__(self, fn): fcntl.fcntl(-1, fcntl.F_SETFL, os.O_NONBLOCK)
self.fn = fn with self.assertRaises(ValueError):
def fileno(self): fcntl.fcntl(BadFile(-1), fcntl.F_SETFL, os.O_NONBLOCK)
return self.fn with self.assertRaises(TypeError):
self.assertRaises(ValueError, fcntl.fcntl, -1, fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl('spam', fcntl.F_SETFL, os.O_NONBLOCK)
self.assertRaises(ValueError, fcntl.fcntl, F(-1), fcntl.F_SETFL, os.O_NONBLOCK) with self.assertRaises(TypeError):
self.assertRaises(TypeError, fcntl.fcntl, 'spam', fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(BadFile('spam'), fcntl.F_SETFL, os.O_NONBLOCK)
self.assertRaises(TypeError, fcntl.fcntl, F('spam'), fcntl.F_SETFL, os.O_NONBLOCK)
@cpython_only
def test_fcntl_bad_file_overflow(self):
from _testcapi import INT_MAX, INT_MIN
# Issue 15989 # Issue 15989
self.assertRaises(OverflowError, fcntl.fcntl, _testcapi.INT_MAX + 1, with self.assertRaises(OverflowError):
fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(INT_MAX + 1, fcntl.F_SETFL, os.O_NONBLOCK)
self.assertRaises(OverflowError, fcntl.fcntl, F(_testcapi.INT_MAX + 1), with self.assertRaises(OverflowError):
fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(BadFile(INT_MAX + 1), fcntl.F_SETFL, os.O_NONBLOCK)
self.assertRaises(OverflowError, fcntl.fcntl, _testcapi.INT_MIN - 1, with self.assertRaises(OverflowError):
fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(INT_MIN - 1, fcntl.F_SETFL, os.O_NONBLOCK)
self.assertRaises(OverflowError, fcntl.fcntl, F(_testcapi.INT_MIN - 1), with self.assertRaises(OverflowError):
fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(BadFile(INT_MIN - 1), fcntl.F_SETFL, os.O_NONBLOCK)
@unittest.skipIf( @unittest.skipIf(
platform.machine().startswith('arm') and platform.system() == 'Linux', platform.machine().startswith('arm') and platform.system() == 'Linux',
@ -128,6 +137,10 @@ class TestFcntl(unittest.TestCase):
self.assertRaises(ValueError, fcntl.flock, -1, fcntl.LOCK_SH) self.assertRaises(ValueError, fcntl.flock, -1, fcntl.LOCK_SH)
self.assertRaises(TypeError, fcntl.flock, 'spam', fcntl.LOCK_SH) self.assertRaises(TypeError, fcntl.flock, 'spam', fcntl.LOCK_SH)
@cpython_only
def test_flock_overflow(self):
import _testcapi
self.assertRaises(OverflowError, fcntl.flock, _testcapi.INT_MAX+1, self.assertRaises(OverflowError, fcntl.flock, _testcapi.INT_MAX+1,
fcntl.LOCK_SH) fcntl.LOCK_SH)

View File

@ -8,9 +8,8 @@ import unittest
from array import array from array import array
from weakref import proxy from weakref import proxy
from functools import wraps from functools import wraps
import _testcapi
from test.support import TESTFN, check_warnings, run_unittest, make_bad_fd from test.support import TESTFN, check_warnings, run_unittest, make_bad_fd, cpython_only
from collections import UserList from collections import UserList
from _io import FileIO as _FileIO from _io import FileIO as _FileIO
@ -362,7 +361,11 @@ class OtherFileTests(unittest.TestCase):
if sys.platform == 'win32': if sys.platform == 'win32':
import msvcrt import msvcrt
self.assertRaises(OSError, msvcrt.get_osfhandle, make_bad_fd()) self.assertRaises(OSError, msvcrt.get_osfhandle, make_bad_fd())
@cpython_only
def testInvalidFd_overflow(self):
# Issue 15989 # Issue 15989
import _testcapi
self.assertRaises(TypeError, _FileIO, _testcapi.INT_MAX + 1) self.assertRaises(TypeError, _FileIO, _testcapi.INT_MAX + 1)
self.assertRaises(TypeError, _FileIO, _testcapi.INT_MIN - 1) self.assertRaises(TypeError, _FileIO, _testcapi.INT_MIN - 1)

View File

@ -7,7 +7,15 @@ import gc
import unittest import unittest
import weakref import weakref
import _testcapi try:
from _testcapi import with_tp_del
except ImportError:
def with_tp_del(cls):
class C(object):
def __new__(cls, *args, **kwargs):
raise TypeError('requires _testcapi.with_tp_del')
return C
from test import support from test import support
@ -423,11 +431,11 @@ class LegacyBase(SimpleBase):
except Exception as e: except Exception as e:
self.errors.append(e) self.errors.append(e)
@_testcapi.with_tp_del @with_tp_del
class Legacy(LegacyBase): class Legacy(LegacyBase):
pass pass
@_testcapi.with_tp_del @with_tp_del
class LegacyResurrector(LegacyBase): class LegacyResurrector(LegacyBase):
def side_effect(self): def side_effect(self):
@ -436,11 +444,12 @@ class LegacyResurrector(LegacyBase):
""" """
self.survivors.append(self) self.survivors.append(self)
@_testcapi.with_tp_del @with_tp_del
class LegacySelfCycle(SelfCycleBase, LegacyBase): class LegacySelfCycle(SelfCycleBase, LegacyBase):
pass pass
@support.cpython_only
class LegacyFinalizationTest(TestBase, unittest.TestCase): class LegacyFinalizationTest(TestBase, unittest.TestCase):
""" """
Test finalization of objects with a tp_del. Test finalization of objects with a tp_del.

View File

@ -332,19 +332,28 @@ class FormatTest(unittest.TestCase):
self.assertIs(text % (), text) self.assertIs(text % (), text)
self.assertIs(text.format(), text) self.assertIs(text.format(), text)
@support.cpython_only
def test_precision(self): def test_precision(self):
from _testcapi import INT_MAX
f = 1.2 f = 1.2
self.assertEqual(format(f, ".0f"), "1") self.assertEqual(format(f, ".0f"), "1")
self.assertEqual(format(f, ".3f"), "1.200") self.assertEqual(format(f, ".3f"), "1.200")
with self.assertRaises(ValueError) as cm: with self.assertRaises(ValueError) as cm:
format(f, ".%sf" % (INT_MAX + 1)) format(f, ".%sf" % (sys.maxsize + 1))
c = complex(f) c = complex(f)
self.assertEqual(format(c, ".0f"), "1+0j") self.assertEqual(format(c, ".0f"), "1+0j")
self.assertEqual(format(c, ".3f"), "1.200+0.000j") self.assertEqual(format(c, ".3f"), "1.200+0.000j")
with self.assertRaises(ValueError) as cm:
format(c, ".%sf" % (sys.maxsize + 1))
@support.cpython_only
def test_precision_c_limits(self):
from _testcapi import INT_MAX
f = 1.2
with self.assertRaises(ValueError) as cm:
format(f, ".%sf" % (INT_MAX + 1))
c = complex(f)
with self.assertRaises(ValueError) as cm: with self.assertRaises(ValueError) as cm:
format(c, ".%sf" % (INT_MAX + 1)) format(c, ".%sf" % (INT_MAX + 1))

View File

@ -1,7 +1,6 @@
import _testcapi
import unittest import unittest
from test.support import (verbose, refcount_test, run_unittest, from test.support import (verbose, refcount_test, run_unittest,
strip_python_stderr) strip_python_stderr, cpython_only)
from test.script_helper import assert_python_ok, make_script, temp_dir from test.script_helper import assert_python_ok, make_script, temp_dir
import sys import sys
@ -14,6 +13,15 @@ try:
except ImportError: except ImportError:
threading = None threading = None
try:
from _testcapi import with_tp_del
except ImportError:
def with_tp_del(cls):
class C(object):
def __new__(cls, *args, **kwargs):
raise TypeError('requires _testcapi.with_tp_del')
return C
### Support code ### Support code
############################################################################### ###############################################################################
@ -41,7 +49,7 @@ class GC_Detector(object):
# gc collects it. # gc collects it.
self.wr = weakref.ref(C1055820(666), it_happened) self.wr = weakref.ref(C1055820(666), it_happened)
@_testcapi.with_tp_del @with_tp_del
class Uncollectable(object): class Uncollectable(object):
"""Create a reference cycle with multiple __del__ methods. """Create a reference cycle with multiple __del__ methods.
@ -143,10 +151,11 @@ class GCTests(unittest.TestCase):
del a del a
self.assertNotEqual(gc.collect(), 0) self.assertNotEqual(gc.collect(), 0)
@cpython_only
def test_legacy_finalizer(self): def test_legacy_finalizer(self):
# A() is uncollectable if it is part of a cycle, make sure it shows up # A() is uncollectable if it is part of a cycle, make sure it shows up
# in gc.garbage. # in gc.garbage.
@_testcapi.with_tp_del @with_tp_del
class A: class A:
def __tp_del__(self): pass def __tp_del__(self): pass
class B: class B:
@ -168,10 +177,11 @@ class GCTests(unittest.TestCase):
self.fail("didn't find obj in garbage (finalizer)") self.fail("didn't find obj in garbage (finalizer)")
gc.garbage.remove(obj) gc.garbage.remove(obj)
@cpython_only
def test_legacy_finalizer_newclass(self): def test_legacy_finalizer_newclass(self):
# A() is uncollectable if it is part of a cycle, make sure it shows up # A() is uncollectable if it is part of a cycle, make sure it shows up
# in gc.garbage. # in gc.garbage.
@_testcapi.with_tp_del @with_tp_del
class A(object): class A(object):
def __tp_del__(self): pass def __tp_del__(self): pass
class B(object): class B(object):
@ -570,6 +580,7 @@ class GCTests(unittest.TestCase):
# would be damaged, with an empty __dict__. # would be damaged, with an empty __dict__.
self.assertEqual(x, None) self.assertEqual(x, None)
@cpython_only
def test_garbage_at_shutdown(self): def test_garbage_at_shutdown(self):
import subprocess import subprocess
code = """if 1: code = """if 1:
@ -764,6 +775,7 @@ class GCCallbackTests(unittest.TestCase):
info = v[2] info = v[2]
self.assertEqual(info["generation"], 2) self.assertEqual(info["generation"], 2)
@cpython_only
def test_collect_garbage(self): def test_collect_garbage(self):
self.preclean() self.preclean()
# Each of these cause four objects to be garbage: Two # Each of these cause four objects to be garbage: Two

View File

@ -1,5 +1,7 @@
import unittest import unittest
from test import support from test import support
# Skip this test if the _testcapi module isn't available.
support.import_module('_testcapi')
from _testcapi import getargs_keywords, getargs_keyword_only from _testcapi import getargs_keywords, getargs_keyword_only
try: try:
from _testcapi import getargs_L, getargs_K from _testcapi import getargs_L, getargs_K

View File

@ -1,4 +1,3 @@
import _testcapi
import collections import collections
import datetime import datetime
import functools import functools
@ -21,7 +20,7 @@ try:
except ImportError: except ImportError:
ThreadPoolExecutor = None ThreadPoolExecutor = None
from test.support import run_unittest, TESTFN, DirsOnSysPath from test.support import run_unittest, TESTFN, DirsOnSysPath, cpython_only
from test.support import MISSING_C_DOCSTRINGS from test.support import MISSING_C_DOCSTRINGS
from test.script_helper import assert_python_ok, assert_python_failure from test.script_helper import assert_python_ok, assert_python_failure
from test import inspect_fodder as mod from test import inspect_fodder as mod
@ -604,16 +603,20 @@ class TestClassesAndFunctions(unittest.TestCase):
self.assertFullArgSpecEquals(_pickle.Pickler(io.BytesIO()).dump, self.assertFullArgSpecEquals(_pickle.Pickler(io.BytesIO()).dump,
args_e=['self', 'obj'], formatted='(self, obj)') args_e=['self', 'obj'], formatted='(self, obj)')
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS, @unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings") "Signature information for builtins requires docstrings")
def test_getfullagrspec_builtin_func(self): def test_getfullagrspec_builtin_func(self):
import _testcapi
builtin = _testcapi.docstring_with_signature_with_defaults builtin = _testcapi.docstring_with_signature_with_defaults
spec = inspect.getfullargspec(builtin) spec = inspect.getfullargspec(builtin)
self.assertEqual(spec.defaults[0], 'avocado') self.assertEqual(spec.defaults[0], 'avocado')
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS, @unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings") "Signature information for builtins requires docstrings")
def test_getfullagrspec_builtin_func_no_signature(self): def test_getfullagrspec_builtin_func_no_signature(self):
import _testcapi
builtin = _testcapi.docstring_no_signature builtin = _testcapi.docstring_no_signature
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
inspect.getfullargspec(builtin) inspect.getfullargspec(builtin)
@ -1647,9 +1650,11 @@ class TestSignatureObject(unittest.TestCase):
('kwargs', ..., int, "var_keyword")), ('kwargs', ..., int, "var_keyword")),
...)) ...))
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS, @unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings") "Signature information for builtins requires docstrings")
def test_signature_on_builtins(self): def test_signature_on_builtins(self):
import _testcapi
def test_unbound_method(o): def test_unbound_method(o):
"""Use this to test unbound methods (things that should have a self)""" """Use this to test unbound methods (things that should have a self)"""
@ -1709,9 +1714,11 @@ class TestSignatureObject(unittest.TestCase):
__call__ = type __call__ = type
test_callable(ThisWorksNow()) test_callable(ThisWorksNow())
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS, @unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings") "Signature information for builtins requires docstrings")
def test_signature_on_decorated_builtins(self): def test_signature_on_decorated_builtins(self):
import _testcapi
func = _testcapi.docstring_with_signature_with_defaults func = _testcapi.docstring_with_signature_with_defaults
def decorator(func): def decorator(func):
@ -1725,7 +1732,9 @@ class TestSignatureObject(unittest.TestCase):
self.assertEqual(inspect.signature(func), self.assertEqual(inspect.signature(func),
inspect.signature(decorated_func)) inspect.signature(decorated_func))
@cpython_only
def test_signature_on_builtins_no_signature(self): def test_signature_on_builtins_no_signature(self):
import _testcapi
with self.assertRaisesRegex(ValueError, 'no signature found for builtin'): with self.assertRaisesRegex(ValueError, 'no signature found for builtin'):
inspect.signature(_testcapi.docstring_no_signature) inspect.signature(_testcapi.docstring_no_signature)

View File

@ -32,7 +32,6 @@ import time
import unittest import unittest
import warnings import warnings
import weakref import weakref
import _testcapi
from collections import deque, UserList from collections import deque, UserList
from itertools import cycle, count from itertools import cycle, count
from test import support from test import support
@ -1997,8 +1996,10 @@ class TextIOWrapperTest(unittest.TestCase):
os.environ.clear() os.environ.clear()
os.environ.update(old_environ) os.environ.update(old_environ)
# Issue 15989 @support.cpython_only
def test_device_encoding(self): def test_device_encoding(self):
# Issue 15989
import _testcapi
b = self.BytesIO() b = self.BytesIO()
b.fileno = lambda: _testcapi.INT_MAX + 1 b.fileno = lambda: _testcapi.INT_MAX + 1
self.assertRaises(OverflowError, self.TextIOWrapper, b) self.assertRaises(OverflowError, self.TextIOWrapper, b)

View File

@ -4,14 +4,13 @@ import os
import subprocess import subprocess
import random import random
import select import select
from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX
try: try:
import threading import threading
except ImportError: except ImportError:
threading = None threading = None
import time import time
import unittest import unittest
from test.support import TESTFN, run_unittest, reap_threads from test.support import TESTFN, run_unittest, reap_threads, cpython_only
try: try:
select.poll select.poll
@ -163,8 +162,18 @@ class PollTests(unittest.TestCase):
# Issues #15989, #17919 # Issues #15989, #17919
self.assertRaises(OverflowError, pollster.register, 0, -1) self.assertRaises(OverflowError, pollster.register, 0, -1)
self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.register, 0, 1 << 64)
self.assertRaises(OverflowError, pollster.modify, 1, -1) self.assertRaises(OverflowError, pollster.modify, 1, -1)
self.assertRaises(OverflowError, pollster.modify, 1, 1 << 64)
@cpython_only
def test_poll_c_limits(self):
from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX
pollster = select.poll()
pollster.register(1)
# Issues #15989, #17919
self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1)
self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1)
self.assertRaises(OverflowError, pollster.poll, INT_MAX + 1) self.assertRaises(OverflowError, pollster.poll, INT_MAX + 1)
self.assertRaises(OverflowError, pollster.poll, UINT_MAX + 1) self.assertRaises(OverflowError, pollster.poll, UINT_MAX + 1)

View File

@ -17,7 +17,6 @@ import stat
import tempfile import tempfile
import unittest import unittest
import warnings import warnings
import _testcapi
_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
support.TESTFN + '-dummy-symlink') support.TESTFN + '-dummy-symlink')
@ -617,7 +616,12 @@ class PosixTester(unittest.TestCase):
except OSError: except OSError:
pass pass
@support.cpython_only
@unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
@support.requires_linux_version(2, 6, 27)
def test_pipe2_c_limits(self):
# Issue 15989 # Issue 15989
import _testcapi
self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1) self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1) self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)

View File

@ -6,7 +6,6 @@ import io
import socket import socket
import select import select
import tempfile import tempfile
import _testcapi
import time import time
import traceback import traceback
import queue import queue
@ -1344,7 +1343,10 @@ class GeneralModuleTests(unittest.TestCase):
srv.listen(backlog) srv.listen(backlog)
srv.close() srv.close()
@support.cpython_only
def test_listen_backlog_overflow(self):
# Issue 15989 # Issue 15989
import _testcapi
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind((HOST, 0)) srv.bind((HOST, 0))
self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1) self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
@ -1737,6 +1739,14 @@ class BasicTCPTest(SocketConnectedTest):
self.done.wait() self.done.wait()
def _testShutdown(self): def _testShutdown(self):
self.serv_conn.send(MSG)
self.serv_conn.shutdown(2)
testShutdown_overflow = support.cpython_only(testShutdown)
@support.cpython_only
def _testShutdown_overflow(self):
import _testcapi
self.serv_conn.send(MSG) self.serv_conn.send(MSG)
# Issue 15989 # Issue 15989
self.assertRaises(OverflowError, self.serv_conn.shutdown, self.assertRaises(OverflowError, self.serv_conn.shutdown,
@ -2506,7 +2516,12 @@ class CmsgMacroTests(unittest.TestCase):
# code with these functions. # code with these functions.
# Match the definition in socketmodule.c # Match the definition in socketmodule.c
socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX) try:
import _testcapi
except ImportError:
socklen_t_limit = 0x7fffffff
else:
socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
@requireAttrs(socket, "CMSG_LEN") @requireAttrs(socket, "CMSG_LEN")
def testCMSG_LEN(self): def testCMSG_LEN(self):
@ -3731,14 +3746,23 @@ class NonBlockingTCPTests(ThreadedTCPSocketTest):
pass pass
end = time.time() end = time.time()
self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.") self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
# Issue 15989
if _testcapi.UINT_MAX < _testcapi.ULONG_MAX:
self.serv.setblocking(_testcapi.UINT_MAX + 1)
self.assertIsNone(self.serv.gettimeout())
def _testSetBlocking(self): def _testSetBlocking(self):
pass pass
@support.cpython_only
def testSetBlocking_overflow(self):
# Issue 15989
import _testcapi
if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
self.skipTest('needs UINT_MAX < ULONG_MAX')
self.serv.setblocking(False)
self.assertEqual(self.serv.gettimeout(), 0.0)
self.serv.setblocking(_testcapi.UINT_MAX + 1)
self.assertIsNone(self.serv.gettimeout())
_testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
@unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'), @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
'test needs socket.SOCK_NONBLOCK') 'test needs socket.SOCK_NONBLOCK')
@support.requires_linux_version(2, 6, 28) @support.requires_linux_version(2, 6, 28)

View File

@ -1,3 +1,8 @@
import unittest
from test import support
# Skip this test if the _testcapi module isn't available.
support.import_module('_testcapi')
from _testcapi import _test_structmembersType, \ from _testcapi import _test_structmembersType, \
CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ CHAR_MAX, CHAR_MIN, UCHAR_MAX, \
SHRT_MAX, SHRT_MIN, USHRT_MAX, \ SHRT_MAX, SHRT_MIN, USHRT_MAX, \
@ -6,9 +11,6 @@ from _testcapi import _test_structmembersType, \
LLONG_MAX, LLONG_MIN, ULLONG_MAX, \ LLONG_MAX, LLONG_MIN, ULLONG_MAX, \
PY_SSIZE_T_MAX, PY_SSIZE_T_MIN PY_SSIZE_T_MAX, PY_SSIZE_T_MIN
import unittest
from test import support
ts=_test_structmembersType(False, # T_BOOL ts=_test_structmembersType(False, # T_BOOL
1, # T_BYTE 1, # T_BYTE
2, # T_UBYTE 2, # T_UBYTE

View File

@ -698,6 +698,7 @@ class SysModuleTest(unittest.TestCase):
self.assertIn(c, range(b - 50, b + 50)) self.assertIn(c, range(b - 50, b + 50))
@test.support.cpython_only
class SizeofTest(unittest.TestCase): class SizeofTest(unittest.TestCase):
def setUp(self): def setUp(self):

View File

@ -1,7 +1,6 @@
import unittest import unittest
import sys import sys
import os import os
import _testcapi
from test import support from test import support
# Skip this test if the _tkinter module wasn't built. # Skip this test if the _tkinter module wasn't built.
@ -13,6 +12,11 @@ support.import_fresh_module('tkinter')
from tkinter import Tcl from tkinter import Tcl
from _tkinter import TclError from _tkinter import TclError
try:
from _testcapi import INT_MAX, PY_SSIZE_T_MAX
except ImportError:
INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
tcl_version = _tkinter.TCL_VERSION.split('.') tcl_version = _tkinter.TCL_VERSION.split('.')
try: try:
for i in range(len(tcl_version)): for i in range(len(tcl_version)):
@ -505,9 +509,9 @@ class BigmemTclTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.interp = Tcl() self.interp = Tcl()
@unittest.skipUnless(_testcapi.INT_MAX < _testcapi.PY_SSIZE_T_MAX, @support.cpython_only
"needs UINT_MAX < SIZE_MAX") @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX")
@support.bigmemtest(size=_testcapi.INT_MAX + 1, memuse=5, dry_run=False) @support.bigmemtest(size=INT_MAX + 1, memuse=5, dry_run=False)
def test_huge_string(self, size): def test_huge_string(self, size):
value = ' ' * size value = ' ' * size
self.assertRaises(OverflowError, self.interp.call, 'set', '_', value) self.assertRaises(OverflowError, self.interp.call, 'set', '_', value)

View File

@ -3,7 +3,7 @@ Tests for the threading module.
""" """
import test.support import test.support
from test.support import verbose, strip_python_stderr, import_module from test.support import verbose, strip_python_stderr, import_module, cpython_only
from test.script_helper import assert_python_ok from test.script_helper import assert_python_ok
import random import random
@ -11,7 +11,6 @@ import re
import sys import sys
_thread = import_module('_thread') _thread = import_module('_thread')
threading = import_module('threading') threading = import_module('threading')
import _testcapi
import time import time
import unittest import unittest
import weakref import weakref
@ -662,6 +661,7 @@ class ThreadTests(BaseTestCase):
self.assertRegex(err.rstrip(), self.assertRegex(err.rstrip(),
b"^sys:1: ResourceWarning: unclosed file ") b"^sys:1: ResourceWarning: unclosed file ")
@cpython_only
def test_frame_tstate_tracing(self): def test_frame_tstate_tracing(self):
# Issue #14432: Crash when a generator is created in a C thread that is # Issue #14432: Crash when a generator is created in a C thread that is
# destroyed while the generator is still used. The issue was that a # destroyed while the generator is still used. The issue was that a
@ -690,6 +690,7 @@ class ThreadTests(BaseTestCase):
threading.settrace(noop_trace) threading.settrace(noop_trace)
# Create a generator in a C thread which exits after the call # Create a generator in a C thread which exits after the call
import _testcapi
_testcapi.call_in_temporary_c_thread(callback) _testcapi.call_in_temporary_c_thread(callback)
# Call the generator in a different Python thread, check that the # Call the generator in a different Python thread, check that the
@ -928,6 +929,7 @@ class SubinterpThreadingTests(BaseTestCase):
# The thread was joined properly. # The thread was joined properly.
self.assertEqual(os.read(r, 1), b"x") self.assertEqual(os.read(r, 1), b"x")
@cpython_only
def test_daemon_threads_fatal_error(self): def test_daemon_threads_fatal_error(self):
subinterp_code = r"""if 1: subinterp_code = r"""if 1:
import os import os

View File

@ -582,6 +582,7 @@ class TestPytime(unittest.TestCase):
-(2.0 ** 100.0), 2.0 ** 100.0, -(2.0 ** 100.0), 2.0 ** 100.0,
) )
@support.cpython_only
def test_time_t(self): def test_time_t(self):
from _testcapi import pytime_object_to_time_t from _testcapi import pytime_object_to_time_t
for obj, time_t in ( for obj, time_t in (
@ -597,6 +598,7 @@ class TestPytime(unittest.TestCase):
for invalid in self.invalid_values: for invalid in self.invalid_values:
self.assertRaises(OverflowError, pytime_object_to_time_t, invalid) self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
@support.cpython_only
def test_timeval(self): def test_timeval(self):
from _testcapi import pytime_object_to_timeval from _testcapi import pytime_object_to_timeval
for obj, timeval in ( for obj, timeval in (
@ -616,6 +618,7 @@ class TestPytime(unittest.TestCase):
for invalid in self.invalid_values: for invalid in self.invalid_values:
self.assertRaises(OverflowError, pytime_object_to_timeval, invalid) self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
@support.cpython_only
def test_timespec(self): def test_timespec(self):
from _testcapi import pytime_object_to_timespec from _testcapi import pytime_object_to_timespec
for obj, timespec in ( for obj, timespec in (

View File

@ -1,12 +1,11 @@
"""Test cases for traceback module""" """Test cases for traceback module"""
from _testcapi import traceback_print, exception_print
from io import StringIO from io import StringIO
import sys import sys
import unittest import unittest
import re import re
from test.support import run_unittest, Error, captured_output from test.support import run_unittest, Error, captured_output
from test.support import TESTFN, unlink from test.support import TESTFN, unlink, cpython_only
import traceback import traceback
@ -176,7 +175,9 @@ class TracebackFormatTests(unittest.TestCase):
def some_exception(self): def some_exception(self):
raise KeyError('blah') raise KeyError('blah')
@cpython_only
def check_traceback_format(self, cleanup_func=None): def check_traceback_format(self, cleanup_func=None):
from _testcapi import traceback_print
try: try:
self.some_exception() self.some_exception()
except KeyError: except KeyError:
@ -404,7 +405,9 @@ class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
# This checks built-in reporting by the interpreter. # This checks built-in reporting by the interpreter.
# #
@cpython_only
def get_report(self, e): def get_report(self, e):
from _testcapi import exception_print
e = self.get_exception(e) e = self.get_exception(e)
with captured_output("stderr") as s: with captured_output("stderr") as s:
exception_print(e) exception_print(e)

View File

@ -9,12 +9,16 @@ Modified for Python 2.0 by Fredrik Lundh (fredrik@pythonware.com)
import unittest import unittest
import unicodedata import unicodedata
import _testcapi
from test import support from test import support
from http.client import HTTPException from http.client import HTTPException
from test.test_normalization import check_version from test.test_normalization import check_version
try:
from _testcapi import INT_MAX, PY_SSIZE_T_MAX, UINT_MAX
except ImportError:
INT_MAX = PY_SSIZE_T_MAX = UINT_MAX = 2**64 - 1
class UnicodeNamesTest(unittest.TestCase): class UnicodeNamesTest(unittest.TestCase):
def checkletter(self, name, code): def checkletter(self, name, code):
@ -216,15 +220,13 @@ class UnicodeNamesTest(unittest.TestCase):
str, b"\\NSPACE", 'unicode-escape', 'strict' str, b"\\NSPACE", 'unicode-escape', 'strict'
) )
@unittest.skipUnless(_testcapi.INT_MAX < _testcapi.PY_SSIZE_T_MAX, @support.cpython_only
"needs UINT_MAX < SIZE_MAX") @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX")
@support.bigmemtest(size=_testcapi.UINT_MAX + 1, @support.bigmemtest(size=UINT_MAX + 1, memuse=2 + 1, dry_run=False)
memuse=2 + 1, dry_run=False)
def test_issue16335(self, size): def test_issue16335(self, size):
# very very long bogus character name # very very long bogus character name
x = b'\\N{SPACE' + b'x' * (_testcapi.UINT_MAX + 1) + b'}' x = b'\\N{SPACE' + b'x' * (UINT_MAX + 1) + b'}'
self.assertEqual(len(x), len(b'\\N{SPACE}') + self.assertEqual(len(x), len(b'\\N{SPACE}') + (UINT_MAX + 1))
(_testcapi.UINT_MAX + 1))
self.assertRaisesRegex(UnicodeError, self.assertRaisesRegex(UnicodeError,
'unknown Unicode character name', 'unknown Unicode character name',
x.decode, 'unicode-escape' x.decode, 'unicode-escape'

View File

@ -1187,8 +1187,13 @@ class UnicodeTest(string_tests.CommonTest,
self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123}, self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
'...3.141593...') '...3.141593...')
@support.cpython_only
def test_formatting_huge_precision(self): def test_formatting_huge_precision(self):
format_string = "%.{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format_string % 2.34
@support.cpython_only
def test_formatting_huge_precision_c_limits(self):
from _testcapi import INT_MAX from _testcapi import INT_MAX
format_string = "%.{}f".format(INT_MAX + 1) format_string = "%.{}f".format(INT_MAX + 1)
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@ -2315,6 +2320,7 @@ class UnicodeTest(string_tests.CommonTest,
b'%.%s', b'abc') b'%.%s', b'abc')
# Test PyUnicode_AsWideChar() # Test PyUnicode_AsWideChar()
@support.cpython_only
def test_aswidechar(self): def test_aswidechar(self):
from _testcapi import unicode_aswidechar from _testcapi import unicode_aswidechar
support.import_module('ctypes') support.import_module('ctypes')
@ -2352,6 +2358,7 @@ class UnicodeTest(string_tests.CommonTest,
self.assertEqual(wchar, nonbmp + '\0') self.assertEqual(wchar, nonbmp + '\0')
# Test PyUnicode_AsWideCharString() # Test PyUnicode_AsWideCharString()
@support.cpython_only
def test_aswidecharstring(self): def test_aswidecharstring(self):
from _testcapi import unicode_aswidecharstring from _testcapi import unicode_aswidecharstring
support.import_module('ctypes') support.import_module('ctypes')
@ -2386,6 +2393,7 @@ class UnicodeTest(string_tests.CommonTest,
s += "4" s += "4"
self.assertEqual(s, "3") self.assertEqual(s, "3")
@support.cpython_only
def test_encode_decimal(self): def test_encode_decimal(self):
from _testcapi import unicode_encodedecimal from _testcapi import unicode_encodedecimal
self.assertEqual(unicode_encodedecimal('123'), self.assertEqual(unicode_encodedecimal('123'),
@ -2401,6 +2409,7 @@ class UnicodeTest(string_tests.CommonTest,
"^'decimal' codec can't encode character", "^'decimal' codec can't encode character",
unicode_encodedecimal, "123\u20ac", "replace") unicode_encodedecimal, "123\u20ac", "replace")
@support.cpython_only
def test_transform_decimal(self): def test_transform_decimal(self):
from _testcapi import unicode_transformdecimaltoascii as transform_decimal from _testcapi import unicode_transformdecimaltoascii as transform_decimal
self.assertEqual(transform_decimal('123'), self.assertEqual(transform_decimal('123'),

View File

@ -125,6 +125,8 @@ IDLE
Tests Tests
----- -----
- Issue #20532: Tests which use _testcapi now are marked as CPython only.
- Issue #19920: Added tests for TarFile.list(). Based on patch by Vajrasky Kok. - Issue #19920: Added tests for TarFile.list(). Based on patch by Vajrasky Kok.
- Issue #19990: Added tests for the imghdr module. Based on patch by - Issue #19990: Added tests for the imghdr module. Based on patch by