Skip to content

Commit 5a5b021

Browse files
committed
Add tests
1 parent 9d98ac5 commit 5a5b021

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Lib/test/test_capi/test_long.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import unittest
2+
import sys
3+
4+
from test.support import import_helper
5+
6+
# Skip this test if the _testcapi module isn't available.
7+
_testcapi = import_helper.import_module('_testcapi')
8+
9+
10+
class LongTests(unittest.TestCase):
11+
12+
def test_compact(self):
13+
for n in {
14+
# Edge cases
15+
*(2**n for n in range(66)),
16+
*(-2**n for n in range(66)),
17+
*(2**n - 1 for n in range(66)),
18+
*(-2**n + 1 for n in range(66)),
19+
# Essentially random
20+
*(37**n for n in range(14)),
21+
*(-37**n for n in range(14)),
22+
}:
23+
with self.subTest(n=n):
24+
is_compact, value = _testcapi.call_long_compact_api(n)
25+
if is_compact:
26+
self.assertEqual(n, value)
27+
28+
def test_compact_known(self):
29+
# Sanity-check some implementation details (we don't guarantee
30+
# that these are/aren't compact)
31+
self.assertEqual(_testcapi.call_long_compact_api(-1), (True, 0))
32+
self.assertEqual(_testcapi.call_long_compact_api(0), (True, 0))
33+
self.assertEqual(_testcapi.call_long_compact_api(256), (True, 256))
34+
self.assertEqual(_testcapi.call_long_compact_api(sys.maxsize),
35+
(False, -1))
36+
37+
38+
if __name__ == "__main__":
39+
unittest.main()

Modules/_testcapi/long.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,18 @@ test_long_numbits(PyObject *self, PyObject *Py_UNUSED(ignored))
534534
Py_RETURN_NONE;
535535
}
536536

537+
static PyObject *
538+
check_long_compact_api(PyObject *self, PyObject *arg)
539+
{
540+
assert(PyLong_Check(arg));
541+
int is_compact = PyUnstable_Long_IsCompact((PyLongObject*)arg);
542+
Py_ssize_t value = -1;
543+
if (is_compact) {
544+
value = PyUnstable_Long_CompactValue((PyLongObject*)arg);
545+
}
546+
return Py_BuildValue("in", is_compact, value);
547+
}
548+
537549
static PyMethodDef test_methods[] = {
538550
{"test_long_and_overflow", test_long_and_overflow, METH_NOARGS},
539551
{"test_long_api", test_long_api, METH_NOARGS},
@@ -543,6 +555,7 @@ static PyMethodDef test_methods[] = {
543555
{"test_long_long_and_overflow",test_long_long_and_overflow, METH_NOARGS},
544556
{"test_long_numbits", test_long_numbits, METH_NOARGS},
545557
{"test_longlong_api", test_longlong_api, METH_NOARGS},
558+
{"call_long_compact_api", check_long_compact_api, METH_O},
546559
{NULL},
547560
};
548561

0 commit comments

Comments
 (0)