code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def count_set_bits(n):
"""Number of '1' bits in binary expansion of a nonnnegative integer."""
return 1 + count_set_bits(n & n - 1) if n else 0 | Number of '1' bits in binary expansion of a nonnnegative integer. | count_set_bits | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def partial_product(start, stop):
"""Product of integers in range(start, stop, 2), computed recursively.
start and stop should both be odd, with start <= stop.
"""
numfactors = (stop - start) >> 1
if not numfactors:
return 1
elif numfactors == 1:
return start
else:
mid = (start + numfactors) | 1
return partial_product(start, mid) * partial_product(mid, stop) | Product of integers in range(start, stop, 2), computed recursively.
start and stop should both be odd, with start <= stop. | partial_product | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def py_factorial(n):
"""Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
described at http://www.luschny.de/math/factorial/binarysplitfact.html
"""
inner = outer = 1
for i in reversed(range(n.bit_length())):
inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
outer *= inner
return outer << (n - count_set_bits(n)) | Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
described at http://www.luschny.de/math/factorial/binarysplitfact.html | py_factorial | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def ulp_abs_check(expected, got, ulp_tol, abs_tol):
"""Given finite floats `expected` and `got`, check that they're
approximately equal to within the given number of ulps or the
given absolute tolerance, whichever is bigger.
Returns None on success and an error message on failure.
"""
ulp_error = abs(to_ulps(expected) - to_ulps(got))
abs_error = abs(expected - got)
# Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
if abs_error <= abs_tol or ulp_error <= ulp_tol:
return None
else:
fmt = ("error = {:.3g} ({:d} ulps); "
"permitted error = {:.3g} or {:d} ulps")
return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol) | Given finite floats `expected` and `got`, check that they're
approximately equal to within the given number of ulps or the
given absolute tolerance, whichever is bigger.
Returns None on success and an error message on failure. | ulp_abs_check | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def parse_mtestfile(fname):
"""Parse a file with test values
-- starts a comment
blank lines, or lines containing only a comment, are ignored
other lines are expected to have the form
id fn arg -> expected [flag]*
"""
with open(fname) as fp:
for line in fp:
# strip comments, and skip blank lines
if '--' in line:
line = line[:line.index('--')]
if not line.strip():
continue
lhs, rhs = line.split('->')
id, fn, arg = lhs.split()
rhs_pieces = rhs.split()
exp = rhs_pieces[0]
flags = rhs_pieces[1:]
yield (id, fn, float(arg), float(exp), flags) | Parse a file with test values
-- starts a comment
blank lines, or lines containing only a comment, are ignored
other lines are expected to have the form
id fn arg -> expected [flag]* | parse_mtestfile | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def parse_testfile(fname):
"""Parse a file with test values
Empty lines or lines starting with -- are ignored
yields id, fn, arg_real, arg_imag, exp_real, exp_imag
"""
with open(fname) as fp:
for line in fp:
# skip comment lines and blank lines
if line.startswith('--') or not line.strip():
continue
lhs, rhs = line.split('->')
id, fn, arg_real, arg_imag = lhs.split()
rhs_pieces = rhs.split()
exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
flags = rhs_pieces[2:]
yield (id, fn,
float(arg_real), float(arg_imag),
float(exp_real), float(exp_imag),
flags) | Parse a file with test values
Empty lines or lines starting with -- are ignored
yields id, fn, arg_real, arg_imag, exp_real, exp_imag | parse_testfile | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
# Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
"""Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely (if given and greater).
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
as far as this function is concerned.
Returns None on success and an error message on failure.
"""
# Check exactly equal (applies also to strings representing exceptions)
if got == expected:
return None
failure = "not equal"
# Turn mixed float and int comparison (e.g. floor()) to all-float
if isinstance(expected, float) and isinstance(got, int):
got = float(got)
elif isinstance(got, float) and isinstance(expected, int):
expected = float(expected)
if isinstance(expected, float) and isinstance(got, float):
if math.isnan(expected) and math.isnan(got):
# Pass, since both nan
failure = None
elif math.isinf(expected) or math.isinf(got):
# We already know they're not equal, drop through to failure
pass
else:
# Both are finite floats (now). Are they close enough?
failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
# arguments are not equal, and if numeric, are too far apart
if failure is not None:
fail_fmt = "expected {!r}, got {!r}"
fail_msg = fail_fmt.format(expected, got)
fail_msg += ' ({})'.format(failure)
return fail_msg
else:
return None | Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely (if given and greater).
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
as far as this function is concerned.
Returns None on success and an error message on failure. | result_check | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
"""Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely, whichever is greater.
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
in this function.
"""
failure = result_check(expected, got, ulp_tol, abs_tol)
if failure is not None:
self.fail("{}: {}".format(name, failure)) | Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely, whichever is greater.
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
in this function. | ftest | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def msum(iterable):
"""Full precision summation. Compute sum(iterable) without any
intermediate accumulation of error. Based on the 'lsum' function
at http://code.activestate.com/recipes/393090/
"""
tmant, texp = 0, 0
for x in iterable:
mant, exp = math.frexp(x)
mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
if texp > exp:
tmant <<= texp-exp
texp = exp
else:
mant <<= exp-texp
tmant += mant
# Round tmant * 2**texp to a float. The original recipe
# used float(str(tmant)) * 2.0**texp for this, but that's
# a little unsafe because str -> float conversion can't be
# relied upon to do correct rounding on all platforms.
tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
if tail > 0:
h = 1 << (tail-1)
tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
texp += tail
return math.ldexp(tmant, texp) | Full precision summation. Compute sum(iterable) without any
intermediate accumulation of error. Based on the 'lsum' function
at http://code.activestate.com/recipes/393090/ | testFsum.msum | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def testFsum(self):
# math.fsum relies on exact rounding for correct operation.
# There's a known problem with IA32 floating-point that causes
# inexact rounding in some situations, and will cause the
# math.fsum tests below to fail; see issue #2937. On non IEEE
# 754 platforms, and on IEEE 754 platforms that exhibit the
# problem described in issue #2937, we simply skip the whole
# test.
# Python version of math.fsum, for comparison. Uses a
# different algorithm based on frexp, ldexp and integer
# arithmetic.
from sys import float_info
mant_dig = float_info.mant_dig
etiny = float_info.min_exp - mant_dig
def msum(iterable):
"""Full precision summation. Compute sum(iterable) without any
intermediate accumulation of error. Based on the 'lsum' function
at http://code.activestate.com/recipes/393090/
"""
tmant, texp = 0, 0
for x in iterable:
mant, exp = math.frexp(x)
mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
if texp > exp:
tmant <<= texp-exp
texp = exp
else:
mant <<= exp-texp
tmant += mant
# Round tmant * 2**texp to a float. The original recipe
# used float(str(tmant)) * 2.0**texp for this, but that's
# a little unsafe because str -> float conversion can't be
# relied upon to do correct rounding on all platforms.
tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
if tail > 0:
h = 1 << (tail-1)
tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
texp += tail
return math.ldexp(tmant, texp)
test_values = [
([], 0.0),
([0.0], 0.0),
([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
([1./n for n in range(1, 1001)],
float.fromhex('0x1.df11f45f4e61ap+2')),
([(-1.)**n/n for n in range(1, 1001)],
float.fromhex('-0x1.62a2af1bd3624p-1')),
([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
([1e16, 1., 1e-16], 10000000000000002.0),
([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
# exercise code for resizing partials array
([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
[-2.**1022],
float.fromhex('0x1.5555555555555p+970')),
]
for i, (vals, expected) in enumerate(test_values):
try:
actual = math.fsum(vals)
except OverflowError:
self.fail("test %d failed: got OverflowError, expected %r "
"for math.fsum(%.100r)" % (i, expected, vals))
except ValueError:
self.fail("test %d failed: got ValueError, expected %r "
"for math.fsum(%.100r)" % (i, expected, vals))
self.assertEqual(actual, expected)
from random import random, gauss, shuffle
for j in range(1000):
vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
s = 0
for i in range(200):
v = gauss(0, random()) ** 7 - s
s += v
vals.append(v)
shuffle(vals)
s = msum(vals)
self.assertEqual(msum(vals), math.fsum(vals)) | Full precision summation. Compute sum(iterable) without any
intermediate accumulation of error. Based on the 'lsum' function
at http://code.activestate.com/recipes/393090/ | testFsum | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def validate_spec(x, y, r):
"""
Check that r matches remainder(x, y) according to the IEEE 754
specification. Assumes that x, y and r are finite and y is nonzero.
"""
fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
# r should not exceed y/2 in absolute value
self.assertLessEqual(abs(fr), abs(fy/2))
# x - r should be an exact integer multiple of y
n = (fx - fr) / fy
self.assertEqual(n, int(n))
if abs(fr) == abs(fy/2):
# If |r| == |y/2|, n should be even.
self.assertEqual(n/2, int(n/2)) | Check that r matches remainder(x, y) according to the IEEE 754
specification. Assumes that x, y and r are finite and y is nonzero. | testRemainder.validate_spec | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def testRemainder(self):
from fractions import Fraction
def validate_spec(x, y, r):
"""
Check that r matches remainder(x, y) according to the IEEE 754
specification. Assumes that x, y and r are finite and y is nonzero.
"""
fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
# r should not exceed y/2 in absolute value
self.assertLessEqual(abs(fr), abs(fy/2))
# x - r should be an exact integer multiple of y
n = (fx - fr) / fy
self.assertEqual(n, int(n))
if abs(fr) == abs(fy/2):
# If |r| == |y/2|, n should be even.
self.assertEqual(n/2, int(n/2))
# triples (x, y, remainder(x, y)) in hexadecimal form.
testcases = [
# Remainders modulo 1, showing the ties-to-even behaviour.
'-4.0 1 -0.0',
'-3.8 1 0.8',
'-3.0 1 -0.0',
'-2.8 1 -0.8',
'-2.0 1 -0.0',
'-1.8 1 0.8',
'-1.0 1 -0.0',
'-0.8 1 -0.8',
'-0.0 1 -0.0',
' 0.0 1 0.0',
' 0.8 1 0.8',
' 1.0 1 0.0',
' 1.8 1 -0.8',
' 2.0 1 0.0',
' 2.8 1 0.8',
' 3.0 1 0.0',
' 3.8 1 -0.8',
' 4.0 1 0.0',
# Reductions modulo 2*pi
'0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
'0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
'0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
'0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
'0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
'0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
'0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
'0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
'0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
'0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
'0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
'0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
'0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
'0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
'0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
'0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
'0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
'0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
'0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
# Symmetry with respect to signs.
' 1 0.c 0.4',
'-1 0.c -0.4',
' 1 -0.c 0.4',
'-1 -0.c -0.4',
' 1.4 0.c -0.4',
'-1.4 0.c 0.4',
' 1.4 -0.c -0.4',
'-1.4 -0.c 0.4',
# Huge modulus, to check that the underlying algorithm doesn't
# rely on 2.0 * modulus being representable.
'0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
'0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
'0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
]
for case in testcases:
with self.subTest(case=case):
x_hex, y_hex, expected_hex = case.split()
x = float.fromhex(x_hex)
y = float.fromhex(y_hex)
expected = float.fromhex(expected_hex)
validate_spec(x, y, expected)
actual = math.remainder(x, y)
# Cheap way of checking that the floats are
# as identical as we need them to be.
self.assertEqual(actual.hex(), expected.hex())
# Test tiny subnormal modulus: there's potential for
# getting the implementation wrong here (for example,
# by assuming that modulus/2 is exactly representable).
tiny = float.fromhex('1p-1074') # min +ve subnormal
for n in range(-25, 25):
if n == 0:
continue
y = n * tiny
for m in range(100):
x = m * tiny
actual = math.remainder(x, y)
validate_spec(x, y, actual)
actual = math.remainder(-x, y)
validate_spec(-x, y, actual)
# Special values.
# NaNs should propagate as usual.
for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
self.assertIsNaN(math.remainder(NAN, value))
self.assertIsNaN(math.remainder(value, NAN))
# remainder(x, inf) is x, for non-nan non-infinite x.
for value in [-2.3, -0.0, 0.0, 2.3]:
self.assertEqual(math.remainder(value, INF), value)
self.assertEqual(math.remainder(value, NINF), value)
# remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
# operations according to IEEE 754-2008 7.2(f), and should raise.
for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
with self.assertRaises(ValueError):
math.remainder(INF, value)
with self.assertRaises(ValueError):
math.remainder(NINF, value)
with self.assertRaises(ValueError):
math.remainder(value, 0.0)
with self.assertRaises(ValueError):
math.remainder(value, -0.0) | Check that r matches remainder(x, y) according to the IEEE 754
specification. Assumes that x, y and r are finite and y is nonzero. | testRemainder | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_math.py | MIT |
def signatures_with_lexicographic_keyword_only_parameters():
"""
Yields a whole bunch of functions with only keyword-only parameters,
where those parameters are always in lexicographically sorted order.
"""
parameters = ['a', 'bar', 'c', 'delta', 'ephraim', 'magical', 'yoyo', 'z']
for i in range(1, 2**len(parameters)):
p = []
bit = 1
for j in range(len(parameters)):
if i & (bit << j):
p.append(parameters[j])
fn_text = "def foo(*, " + ", ".join(p) + "): pass"
symbols = {}
exec(fn_text, symbols, symbols)
yield symbols['foo'] | Yields a whole bunch of functions with only keyword-only parameters,
where those parameters are always in lexicographically sorted order. | signatures_with_lexicographic_keyword_only_parameters | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | MIT |
def test_proceed_with_fake_filename(self):
'''doctest monkeypatches linecache to enable inspection'''
fn, source = '<test>', 'def x(): pass\n'
getlines = linecache.getlines
def monkey(filename, module_globals=None):
if filename == fn:
return source.splitlines(keepends=True)
else:
return getlines(filename, module_globals)
linecache.getlines = monkey
try:
ns = {}
exec(compile(source, fn, 'single'), ns)
inspect.getsource(ns["x"])
finally:
linecache.getlines = getlines | doctest monkeypatches linecache to enable inspection | test_proceed_with_fake_filename | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | MIT |
def makeCallable(self, signature):
"""Create a function that returns its locals()"""
code = "lambda %s: locals()"
return eval(code % signature) | Create a function that returns its locals() | makeCallable | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | MIT |
def test_unbound_method(o):
"""Use this to test unbound methods (things that should have a self)"""
signature = inspect.signature(o)
self.assertTrue(isinstance(signature, inspect.Signature))
self.assertEqual(list(signature.parameters.values())[0].name, 'self')
return signature | Use this to test unbound methods (things that should have a self) | test_signature_on_builtins.test_unbound_method | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | MIT |
def test_callable(o):
"""Use this to test bound methods or normal callables (things that don't expect self)"""
signature = inspect.signature(o)
self.assertTrue(isinstance(signature, inspect.Signature))
if signature.parameters:
self.assertNotEqual(list(signature.parameters.values())[0].name, 'self')
return signature | Use this to test bound methods or normal callables (things that don't expect self) | test_signature_on_builtins.test_callable | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | MIT |
def test_signature_on_builtins(self):
import _testcapi
def test_unbound_method(o):
"""Use this to test unbound methods (things that should have a self)"""
signature = inspect.signature(o)
self.assertTrue(isinstance(signature, inspect.Signature))
self.assertEqual(list(signature.parameters.values())[0].name, 'self')
return signature
def test_callable(o):
"""Use this to test bound methods or normal callables (things that don't expect self)"""
signature = inspect.signature(o)
self.assertTrue(isinstance(signature, inspect.Signature))
if signature.parameters:
self.assertNotEqual(list(signature.parameters.values())[0].name, 'self')
return signature
signature = test_callable(_testcapi.docstring_with_signature_with_defaults)
def p(name): return signature.parameters[name].default
self.assertEqual(p('s'), 'avocado')
self.assertEqual(p('b'), b'bytes')
self.assertEqual(p('d'), 3.14)
self.assertEqual(p('i'), 35)
self.assertEqual(p('n'), None)
self.assertEqual(p('t'), True)
self.assertEqual(p('f'), False)
self.assertEqual(p('local'), 3)
self.assertEqual(p('sys'), sys.maxsize)
self.assertNotIn('exp', signature.parameters)
test_callable(object)
# normal method
# (PyMethodDescr_Type, "method_descriptor")
test_unbound_method(_pickle.Pickler.dump)
d = _pickle.Pickler(io.StringIO())
test_callable(d.dump)
# static method
test_callable(str.maketrans)
test_callable('abc'.maketrans)
# class method
test_callable(dict.fromkeys)
test_callable({}.fromkeys)
# wrapper around slot (PyWrapperDescr_Type, "wrapper_descriptor")
test_unbound_method(type.__call__)
test_unbound_method(int.__add__)
test_callable((3).__add__)
# _PyMethodWrapper_Type
# support for 'method-wrapper'
test_callable(min.__call__)
# This doesn't work now.
# (We don't have a valid signature for "type" in 3.4)
with self.assertRaisesRegex(ValueError, "no signature found"):
class ThisWorksNow:
__call__ = type
test_callable(ThisWorksNow())
# Regression test for issue #20786
test_unbound_method(dict.__delitem__)
test_unbound_method(property.__delete__)
# Regression test for issue #20586
test_callable(_testcapi.docstring_with_signature_but_no_doc) | Use this to test unbound methods (things that should have a self) | test_signature_on_builtins | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_inspect.py | MIT |
def escapestr(text, ampm):
"""
Escape text to deal with possible locale values that have regex
syntax while allowing regex syntax used for comparison.
"""
new_text = re.escape(text)
new_text = new_text.replace(re.escape(ampm), ampm)
new_text = new_text.replace(r'\%', '%')
new_text = new_text.replace(r'\:', ':')
new_text = new_text.replace(r'\?', '?')
return new_text | Escape text to deal with possible locale values that have regex
syntax while allowing regex syntax used for comparison. | escapestr | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_strftime.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_strftime.py | MIT |
def readpipe_interrupted(self, interrupt):
"""Perform a read during which a signal will arrive. Return True if the
read is interrupted by the signal and raises an exception. Return False
if it returns normally.
"""
# use a subprocess to have only one thread, to have a timeout on the
# blocking read and to not touch signal handling in this process
code = """if 1:
import errno
import os
import signal
import sys
interrupt = %r
r, w = os.pipe()
def handler(signum, frame):
1 / 0
signal.signal(signal.SIGALRM, handler)
if interrupt is not None:
signal.siginterrupt(signal.SIGALRM, interrupt)
print("ready")
sys.stdout.flush()
# run the test twice
try:
for loop in range(2):
# send a SIGALRM in a second (during the read)
signal.alarm(1)
try:
# blocking call: read from a pipe without data
os.read(r, 1)
except ZeroDivisionError:
pass
else:
sys.exit(2)
sys.exit(3)
finally:
os.close(r)
os.close(w)
""" % (interrupt,)
with spawn_python('-c', code) as process:
try:
# wait until the child process is loaded and has started
first_line = process.stdout.readline()
stdout, stderr = process.communicate(timeout=5.0)
except subprocess.TimeoutExpired:
process.kill()
return False
else:
stdout = first_line + stdout
exitcode = process.wait()
if exitcode not in (2, 3):
raise Exception("Child error (exit code %s): %r"
% (exitcode, stdout))
return (exitcode == 3) | Perform a read during which a signal will arrive. Return True if the
read is interrupted by the signal and raises an exception. Return False
if it returns normally. | readpipe_interrupted | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | MIT |
def wait_helper(self, blocked, test):
"""
test: body of the "def test(signum):" function.
blocked: number of the blocked signal
"""
code = '''if 1:
import signal
import sys
from signal import Signals
def handler(signum, frame):
1/0
%s
blocked = %s
signum = signal.SIGALRM
# child: block and wait the signal
try:
signal.signal(signum, handler)
signal.pthread_sigmask(signal.SIG_BLOCK, [blocked])
# Do the tests
test(signum)
# The handler must not be called on unblock
try:
signal.pthread_sigmask(signal.SIG_UNBLOCK, [blocked])
except ZeroDivisionError:
print("the signal handler has been called",
file=sys.stderr)
sys.exit(1)
except BaseException as err:
print("error: {}".format(err), file=sys.stderr)
sys.stderr.flush()
sys.exit(1)
''' % (test.strip(), blocked)
# sig*wait* must be called with the signal blocked: since the current
# process might have several threads running, use a subprocess to have
# a single thread.
assert_python_ok('-c', code) | test: body of the "def test(signum):" function.
blocked: number of the blocked signal | wait_helper | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | MIT |
def test_stress_delivery_dependent(self):
"""
This test uses dependent signal handlers.
"""
N = self.decide_itimer_count()
sigs = []
def first_handler(signum, frame):
# 1e-6 is the minimum non-zero value for `setitimer()`.
# Choose a random delay so as to improve chances of
# triggering a race condition. Ideally the signal is received
# when inside critical signal-handling routines such as
# Py_MakePendingCalls().
signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
def second_handler(signum=None, frame=None):
sigs.append(signum)
# Here on Linux, SIGPROF > SIGALRM > SIGUSR1. By using both
# ascending and descending sequences (SIGUSR1 then SIGALRM,
# SIGPROF then SIGALRM), we maximize chances of hitting a bug.
self.setsig(signal.SIGPROF, first_handler)
self.setsig(signal.SIGUSR1, first_handler)
self.setsig(signal.SIGALRM, second_handler) # for ITIMER_REAL
expected_sigs = 0
deadline = time.monotonic() + 15.0
while expected_sigs < N:
os.kill(os.getpid(), signal.SIGPROF)
expected_sigs += 1
# Wait for handlers to run to avoid signal coalescing
while len(sigs) < expected_sigs and time.monotonic() < deadline:
time.sleep(1e-5)
os.kill(os.getpid(), signal.SIGUSR1)
expected_sigs += 1
while len(sigs) < expected_sigs and time.monotonic() < deadline:
time.sleep(1e-5)
# All ITIMER_REAL signals should have been delivered to the
# Python handler
self.assertEqual(len(sigs), N, "Some signals were lost") | This test uses dependent signal handlers. | test_stress_delivery_dependent | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | MIT |
def test_stress_delivery_simultaneous(self):
"""
This test uses simultaneous signal handlers.
"""
N = self.decide_itimer_count()
sigs = []
def handler(signum, frame):
sigs.append(signum)
self.setsig(signal.SIGUSR1, handler)
self.setsig(signal.SIGALRM, handler) # for ITIMER_REAL
expected_sigs = 0
deadline = time.monotonic() + 15.0
while expected_sigs < N:
# Hopefully the SIGALRM will be received somewhere during
# initial processing of SIGUSR1.
signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
os.kill(os.getpid(), signal.SIGUSR1)
expected_sigs += 2
# Wait for handlers to run to avoid signal coalescing
while len(sigs) < expected_sigs and time.monotonic() < deadline:
time.sleep(1e-5)
# All ITIMER_REAL signals should have been delivered to the
# Python handler
self.assertEqual(len(sigs), N, "Some signals were lost") | This test uses simultaneous signal handlers. | test_stress_delivery_simultaneous | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_signal.py | MIT |
def read_unlimited(self, v, context):
"""Work around the limitations of the 32-bit _decimal version. The
guaranteed maximum values for prec, Emax etc. are 425000000,
but higher values usually work, except for rare corner cases.
In particular, all of the IBM tests pass with maximum values
of 1070000000."""
if self.decimal == C and self.decimal.MAX_EMAX == 425000000:
self.readcontext._unsafe_setprec(1070000000)
self.readcontext._unsafe_setemax(1070000000)
self.readcontext._unsafe_setemin(-1070000000)
return self.readcontext.create_decimal(v)
else:
return self.decimal.Decimal(v, context) | Work around the limitations of the 32-bit _decimal version. The
guaranteed maximum values for prec, Emax etc. are 425000000,
but higher values usually work, except for rare corner cases.
In particular, all of the IBM tests pass with maximum values
of 1070000000. | read_unlimited | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | MIT |
def tr(s):
"""The C Context docstrings use 'x' in order to prevent confusion
with the article 'a' in the descriptions."""
if s == 'x': return 'a'
if s == 'y': return 'b'
if s == 'z': return 'c'
return s | The C Context docstrings use 'x' in order to prevent confusion
with the article 'a' in the descriptions. | test_inspect_types.tr | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | MIT |
def test_inspect_types(self):
POS = inspect._ParameterKind.POSITIONAL_ONLY
POS_KWD = inspect._ParameterKind.POSITIONAL_OR_KEYWORD
# Type heuristic (type annotations would help!):
pdict = {C: {'other': C.Decimal(1),
'third': C.Decimal(1),
'x': C.Decimal(1),
'y': C.Decimal(1),
'z': C.Decimal(1),
'a': C.Decimal(1),
'b': C.Decimal(1),
'c': C.Decimal(1),
'exp': C.Decimal(1),
'modulo': C.Decimal(1),
'num': "1",
'f': 1.0,
'rounding': C.ROUND_HALF_UP,
'context': C.getcontext()},
P: {'other': P.Decimal(1),
'third': P.Decimal(1),
'a': P.Decimal(1),
'b': P.Decimal(1),
'c': P.Decimal(1),
'exp': P.Decimal(1),
'modulo': P.Decimal(1),
'num': "1",
'f': 1.0,
'rounding': P.ROUND_HALF_UP,
'context': P.getcontext()}}
def mkargs(module, sig):
args = []
kwargs = {}
for name, param in sig.parameters.items():
if name == 'self': continue
if param.kind == POS:
args.append(pdict[module][name])
elif param.kind == POS_KWD:
kwargs[name] = pdict[module][name]
else:
raise TestFailed("unexpected parameter kind")
return args, kwargs
def tr(s):
"""The C Context docstrings use 'x' in order to prevent confusion
with the article 'a' in the descriptions."""
if s == 'x': return 'a'
if s == 'y': return 'b'
if s == 'z': return 'c'
return s
def doit(ty):
p_type = getattr(P, ty)
c_type = getattr(C, ty)
for attr in dir(p_type):
if attr.startswith('_'):
continue
p_func = getattr(p_type, attr)
c_func = getattr(c_type, attr)
if inspect.isfunction(p_func):
p_sig = inspect.signature(p_func)
c_sig = inspect.signature(c_func)
# parameter names:
p_names = list(p_sig.parameters.keys())
c_names = [tr(x) for x in c_sig.parameters.keys()]
self.assertEqual(c_names, p_names,
msg="parameter name mismatch in %s" % p_func)
p_kind = [x.kind for x in p_sig.parameters.values()]
c_kind = [x.kind for x in c_sig.parameters.values()]
# 'self' parameter:
self.assertIs(p_kind[0], POS_KWD)
self.assertIs(c_kind[0], POS)
# remaining parameters:
if ty == 'Decimal':
self.assertEqual(c_kind[1:], p_kind[1:],
msg="parameter kind mismatch in %s" % p_func)
else: # Context methods are positional only in the C version.
self.assertEqual(len(c_kind), len(p_kind),
msg="parameter kind mismatch in %s" % p_func)
# Run the function:
args, kwds = mkargs(C, c_sig)
try:
getattr(c_type(9), attr)(*args, **kwds)
except Exception as err:
raise TestFailed("invalid signature for %s: %s %s" % (c_func, args, kwds))
args, kwds = mkargs(P, p_sig)
try:
getattr(p_type(9), attr)(*args, **kwds)
except Exception as err:
raise TestFailed("invalid signature for %s: %s %s" % (p_func, args, kwds))
doit('Decimal')
doit('Context') | The C Context docstrings use 'x' in order to prevent confusion
with the article 'a' in the descriptions. | test_inspect_types | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | MIT |
def test_main(arith=None, verbose=None, todo_tests=None, debug=None):
""" Execute the tests.
Runs all arithmetic tests if arith is True or if the "decimal" resource
is enabled in regrtest.py
"""
init(C)
init(P)
global TEST_ALL, DEBUG
TEST_ALL = arith if arith is not None else is_resource_enabled('decimal')
DEBUG = debug
if todo_tests is None:
test_classes = all_tests
else:
test_classes = [CIBMTestCases, PyIBMTestCases]
# Dynamically build custom test definition for each file in the test
# directory and add the definitions to the DecimalTest class. This
# procedure insures that new files do not get skipped.
for filename in os.listdir(directory):
if '.decTest' not in filename or filename.startswith("."):
continue
head, tail = filename.split('.')
if todo_tests is not None and head not in todo_tests:
continue
tester = lambda self, f=filename: self.eval_file(directory + f)
setattr(CIBMTestCases, 'test_' + head, tester)
setattr(PyIBMTestCases, 'test_' + head, tester)
del filename, head, tail, tester
try:
run_unittest(*test_classes)
if todo_tests is None:
from doctest import IGNORE_EXCEPTION_DETAIL
savedecimal = sys.modules['decimal']
if C:
sys.modules['decimal'] = C
run_doctest(C, verbose, optionflags=IGNORE_EXCEPTION_DETAIL)
sys.modules['decimal'] = P
run_doctest(P, verbose)
sys.modules['decimal'] = savedecimal
finally:
if C: C.setcontext(ORIGINAL_CONTEXT[C])
P.setcontext(ORIGINAL_CONTEXT[P])
if not C:
warnings.warn('C tests skipped: no module named _decimal.',
UserWarning)
if not orig_sys_decimal is sys.modules['decimal']:
raise TestFailed("Internal error: unbalanced number of changes to "
"sys.modules['decimal'].") | Execute the tests.
Runs all arithmetic tests if arith is True or if the "decimal" resource
is enabled in regrtest.py | test_main | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_decimal.py | MIT |
def __instancecheck__(cls, inst):
"""Implement isinstance(inst, cls)."""
return any(cls.__subclasscheck__(c)
for c in {type(inst), inst.__class__}) | Implement isinstance(inst, cls). | __instancecheck__ | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typechecks.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typechecks.py | MIT |
def __subclasscheck__(cls, sub):
"""Implement issubclass(sub, cls)."""
candidates = cls.__dict__.get("__subclass__", set()) | {cls}
return any(c in candidates for c in sub.mro()) | Implement issubclass(sub, cls). | __subclasscheck__ | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typechecks.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_typechecks.py | MIT |
def test_threading_local_subclass(self):
class LocalSubclass(self._local):
"""To test that subclasses behave properly."""
self._test_one_class(LocalSubclass) | To test that subclasses behave properly. | test_threading_local_subclass | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threading_local.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threading_local.py | MIT |
def test_dict_attribute_subclass(self):
class LocalSubclass(self._local):
"""To test that subclasses behave properly."""
self._test_dict_attribute(LocalSubclass) | To test that subclasses behave properly. | test_dict_attribute_subclass | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threading_local.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_threading_local.py | MIT |
def test___repr__(self):
"""Check that the repr() of os.environ looks like environ({...})."""
env = os.environ
self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
'{!r}: {!r}'.format(key, value)
for key, value in env.items()))) | Check that the repr() of os.environ looks like environ({...}). | test___repr__ | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
"""
compare with walk() results.
"""
walk_kwargs = walk_kwargs.copy()
fwalk_kwargs = fwalk_kwargs.copy()
for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
expected = {}
for root, dirs, files in os.walk(**walk_kwargs):
expected[root] = (set(dirs), set(files))
for root, dirs, files, rootfd in self.fwalk(**fwalk_kwargs):
self.assertIn(root, expected)
self.assertEqual(expected[root], (set(dirs), set(files))) | compare with walk() results. | _compare_to_walk | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def _execvpe_mockup(defpath=None):
"""
Stubs out execv and execve functions when used as context manager.
Records exec calls. The mock execv and execve functions always raise an
exception as they would normally never return.
"""
# A list of tuples containing (function name, first arg, args)
# of calls to execv or execve that have been made.
calls = []
def mock_execv(name, *args):
calls.append(('execv', name, args))
raise RuntimeError("execv called")
def mock_execve(name, *args):
calls.append(('execve', name, args))
raise OSError(errno.ENOTDIR, "execve called")
try:
orig_execv = os.execv
orig_execve = os.execve
orig_defpath = os.defpath
os.execv = mock_execv
os.execve = mock_execve
if defpath is not None:
os.defpath = defpath
yield calls
finally:
os.execv = orig_execv
os.execve = orig_execve
os.defpath = orig_defpath | Stubs out execv and execve functions when used as context manager.
Records exec calls. The mock execv and execve functions always raise an
exception as they would normally never return. | _execvpe_mockup | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def test_listdir_no_extended_path(self):
"""Test when the path is not an "extended" path."""
# unicode
self.assertEqual(
sorted(os.listdir(support.TESTFN)),
self.created_paths)
# bytes
self.assertEqual(
sorted(os.listdir(os.fsencode(support.TESTFN))),
[os.fsencode(path) for path in self.created_paths]) | Test when the path is not an "extended" path. | test_listdir_no_extended_path | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def test_listdir_extended_path(self):
"""Test when the path starts with '\\\\?\\'."""
# See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
# unicode
path = '\\\\?\\' + os.path.abspath(support.TESTFN)
self.assertEqual(
sorted(os.listdir(path)),
self.created_paths)
# bytes
path = b'\\\\?\\' + os.fsencode(os.path.abspath(support.TESTFN))
self.assertEqual(
sorted(os.listdir(path)),
[os.fsencode(path) for path in self.created_paths]) | Test when the path starts with '\\\\?\\'. | test_listdir_extended_path | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def test_directory_link_nonlocal(self):
"""
The symlink target should resolve relative to the link, not relative
to the current directory.
Then, link base/some_link -> base/some_dir and ensure that some_link
is resolved as a directory.
In issue13772, it was discovered that directory detection failed if
the symlink target was not specified relative to the current
directory, which was a defect in the implementation.
"""
src = os.path.join('base', 'some_link')
os.symlink('some_dir', src)
assert os.path.isdir(src) | The symlink target should resolve relative to the link, not relative
to the current directory.
Then, link base/some_link -> base/some_dir and ensure that some_link
is resolved as a directory.
In issue13772, it was discovered that directory detection failed if
the symlink target was not specified relative to the current
directory, which was a defect in the implementation. | test_directory_link_nonlocal | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def sendfile_wrapper(self, *args, **kwargs):
"""A higher level wrapper representing how an application is
supposed to use sendfile().
"""
while True:
try:
return os.sendfile(*args, **kwargs)
except OSError as err:
if err.errno == errno.ECONNRESET:
# disconnected
raise
elif err.errno in (errno.EAGAIN, errno.EBUSY):
# we have to retry send data
continue
else:
raise | A higher level wrapper representing how an application is
supposed to use sendfile(). | sendfile_wrapper | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def test_does_not_crash(self):
"""Check if get_terminal_size() returns a meaningful value.
There's no easy portable way to actually check the size of the
terminal, so let's check if it returns something sensible instead.
"""
try:
size = os.get_terminal_size()
except OSError as e:
if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
# Under win32 a generic OSError can be thrown if the
# handle cannot be retrieved
self.skipTest("failed to query terminal size")
raise
self.assertGreaterEqual(size.columns, 0)
self.assertGreaterEqual(size.lines, 0) | Check if get_terminal_size() returns a meaningful value.
There's no easy portable way to actually check the size of the
terminal, so let's check if it returns something sensible instead. | test_does_not_crash | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def test_stty_match(self):
"""Check if stty returns the same results
stty actually tests stdin, so get_terminal_size is invoked on
stdin explicitly. If stty succeeded, then get_terminal_size()
should work too.
"""
try:
size = subprocess.check_output(['stty', 'size']).decode().split()
except (FileNotFoundError, subprocess.CalledProcessError,
PermissionError):
self.skipTest("stty invocation failed")
expected = (int(size[1]), int(size[0])) # reversed order
try:
actual = os.get_terminal_size(sys.__stdin__.fileno())
except OSError as e:
if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
# Under win32 a generic OSError can be thrown if the
# handle cannot be retrieved
self.skipTest("failed to query terminal size")
raise
self.assertEqual(expected, actual) | Check if stty returns the same results
stty actually tests stdin, so get_terminal_size is invoked on
stdin explicitly. If stty succeeded, then get_terminal_size()
should work too. | test_stty_match | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_os.py | MIT |
def abuse(self, a, b, c):
"""Another
\tdocstring
containing
\ttabs
\t
"""
self.argue(a, b, c) | Another
\tdocstring
containing
\ttabs
\t | abuse | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/inspect_fodder.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/inspect_fodder.py | MIT |
def test_duck_functional_gen(self):
class Generator:
"""Emulates the following generator (very clumsy):
def gen(fut):
result = yield fut
return result * 2
"""
def __init__(self, fut):
self._i = 0
self._fut = fut
def __iter__(self):
return self
def __next__(self):
return self.send(None)
def send(self, v):
try:
if self._i == 0:
assert v is None
return self._fut
if self._i == 1:
raise StopIteration(v * 2)
if self._i > 1:
raise StopIteration
finally:
self._i += 1
def throw(self, tp, *exc):
self._i = 100
if tp is not GeneratorExit:
raise tp
def close(self):
self.throw(GeneratorExit)
@types.coroutine
def foo(): return Generator('spam')
wrapper = foo()
self.assertIsInstance(wrapper, types._GeneratorWrapper)
async def corofunc():
return await foo() + 100
coro = corofunc()
self.assertEqual(coro.send(None), 'spam')
try:
coro.send(20)
except StopIteration as ex:
self.assertEqual(ex.args[0], 140)
else:
self.fail('StopIteration was expected') | Emulates the following generator (very clumsy):
def gen(fut):
result = yield fut
return result * 2 | test_duck_functional_gen | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_types.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_types.py | MIT |
def randomlist(self, n):
"""Helper function to make a list of random numbers"""
return [self.gen.random() for i in range(n)] | Helper function to make a list of random numbers | randomlist | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_random.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_random.py | MIT |
def __init__(self):
"""C.__init__.
>>> print(C()) # 3
42
""" | C.__init__.
>>> print(C()) # 3
42 | __init__ | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def __str__(self):
"""
>>> print(C()) # 4
42
"""
return "42" | >>> print(C()) # 4
42 | __str__ | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def nested(self):
"""
>>> print(3) # 6
3
""" | >>> print(3) # 6
3 | nested | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def getx(self):
"""
>>> c = C() # 7
>>> c.x = 12 # 8
>>> print(c.x) # 9
-12
"""
return -self._x | >>> c = C() # 7
>>> c.x = 12 # 8
>>> print(c.x) # 9
-12 | getx | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def setx(self, value):
"""
>>> c = C() # 10
>>> c.x = 12 # 11
>>> print(c.x) # 12
-12
"""
self._x = value | >>> c = C() # 10
>>> c.x = 12 # 11
>>> print(c.x) # 12
-12 | setx | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def statm():
"""
A static method.
>>> print(C.statm()) # 16
666
>>> print(C().statm()) # 17
666
"""
return 666 | A static method.
>>> print(C.statm()) # 16
666
>>> print(C().statm()) # 17
666 | statm | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def clsm(cls, val):
"""
A class method.
>>> print(C.clsm(22)) # 18
22
>>> print(C().clsm(23)) # 19
23
"""
return val | A class method.
>>> print(C.clsm(22)) # 18
22
>>> print(C().clsm(23)) # 19
23 | clsm | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_doctest2.py | MIT |
def test_splittable_setdefault(self):
"""split table must be combined when setdefault()
breaks insertion order"""
a, b = self.make_shared_key_dict(2)
a['a'] = 1
size_a = sys.getsizeof(a)
a['b'] = 2
b.setdefault('b', 2)
size_b = sys.getsizeof(b)
b['a'] = 1
self.assertGreater(size_b, size_a)
self.assertEqual(list(a), ['x', 'y', 'z', 'a', 'b'])
self.assertEqual(list(b), ['x', 'y', 'z', 'b', 'a']) | split table must be combined when setdefault()
breaks insertion order | test_splittable_setdefault | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | MIT |
def test_splittable_del(self):
"""split table must be combined when del d[k]"""
a, b = self.make_shared_key_dict(2)
orig_size = sys.getsizeof(a)
del a['y'] # split table is combined
with self.assertRaises(KeyError):
del a['y']
self.assertGreater(sys.getsizeof(a), orig_size)
self.assertEqual(list(a), ['x', 'z'])
self.assertEqual(list(b), ['x', 'y', 'z'])
# Two dicts have different insertion order.
a['y'] = 42
self.assertEqual(list(a), ['x', 'z', 'y'])
self.assertEqual(list(b), ['x', 'y', 'z']) | split table must be combined when del d[k] | test_splittable_del | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | MIT |
def test_splittable_pop(self):
"""split table must be combined when d.pop(k)"""
a, b = self.make_shared_key_dict(2)
orig_size = sys.getsizeof(a)
a.pop('y') # split table is combined
with self.assertRaises(KeyError):
a.pop('y')
self.assertGreater(sys.getsizeof(a), orig_size)
self.assertEqual(list(a), ['x', 'z'])
self.assertEqual(list(b), ['x', 'y', 'z'])
# Two dicts have different insertion order.
a['y'] = 42
self.assertEqual(list(a), ['x', 'z', 'y'])
self.assertEqual(list(b), ['x', 'y', 'z']) | split table must be combined when d.pop(k) | test_splittable_pop | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | MIT |
def test_splittable_pop_pending(self):
"""pop a pending key in a splitted table should not crash"""
a, b = self.make_shared_key_dict(2)
a['a'] = 4
with self.assertRaises(KeyError):
b.pop('a') | pop a pending key in a splitted table should not crash | test_splittable_pop_pending | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | MIT |
def test_splittable_popitem(self):
"""split table must be combined when d.popitem()"""
a, b = self.make_shared_key_dict(2)
orig_size = sys.getsizeof(a)
item = a.popitem() # split table is combined
self.assertEqual(item, ('z', 3))
with self.assertRaises(KeyError):
del a['z']
self.assertGreater(sys.getsizeof(a), orig_size)
self.assertEqual(list(a), ['x', 'y'])
self.assertEqual(list(b), ['x', 'y', 'z']) | split table must be combined when d.popitem() | test_splittable_popitem | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | MIT |
def test_splittable_setattr_after_pop(self):
"""setattr() must not convert combined table into split table."""
# Issue 28147
import _testcapi
class C:
pass
a = C()
a.a = 1
self.assertTrue(_testcapi.dict_hassplittable(a.__dict__))
# dict.pop() convert it to combined table
a.__dict__.pop('a')
self.assertFalse(_testcapi.dict_hassplittable(a.__dict__))
# But C should not convert a.__dict__ to split table again.
a.a = 1
self.assertFalse(_testcapi.dict_hassplittable(a.__dict__))
# Same for popitem()
a = C()
a.a = 2
self.assertTrue(_testcapi.dict_hassplittable(a.__dict__))
a.__dict__.popitem()
self.assertFalse(_testcapi.dict_hassplittable(a.__dict__))
a.a = 3
self.assertFalse(_testcapi.dict_hassplittable(a.__dict__)) | setattr() must not convert combined table into split table. | test_splittable_setattr_after_pop | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_dict.py | MIT |
def verbose_print(arg):
"""Helper function for printing out debugging output."""
if support.verbose:
with _print_mutex:
print(arg) | Helper function for printing out debugging output. | verbose_print | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_thread.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_thread.py | MIT |
def test_defaults_keyword(self):
"""bpo-23835 fix for ConfigParser"""
cf = self.newconfig(defaults={1: 2.4})
self.assertEqual(cf[self.default_section]['1'], '2.4')
self.assertAlmostEqual(cf[self.default_section].getfloat('1'), 2.4)
cf = self.newconfig(defaults={"A": 5.2})
self.assertEqual(cf[self.default_section]['a'], '5.2')
self.assertAlmostEqual(cf[self.default_section].getfloat('a'), 5.2) | bpo-23835 fix for ConfigParser | test_defaults_keyword | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | MIT |
def test_defaults_keyword(self):
"""bpo-23835 legacy behavior for RawConfigParser"""
with self.assertRaises(AttributeError) as ctx:
self.newconfig(defaults={1: 2.4})
err = ctx.exception
self.assertEqual(str(err), "'int' object has no attribute 'lower'")
cf = self.newconfig(defaults={"A": 5.2})
self.assertAlmostEqual(cf[self.default_section]['a'], 5.2) | bpo-23835 legacy behavior for RawConfigParser | test_defaults_keyword | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | MIT |
def readline_generator(f):
"""As advised in Doc/library/configparser.rst."""
line = f.readline()
while line:
yield line
line = f.readline() | As advised in Doc/library/configparser.rst. | readline_generator | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | MIT |
def test_readline_generator(self):
"""Issue #11670."""
parser = configparser.ConfigParser()
with self.assertRaises(TypeError):
parser.read_file(FakeFile())
parser.read_file(readline_generator(FakeFile()))
self.assertIn("Foo Bar", parser)
self.assertIn("foo", parser["Foo Bar"])
self.assertEqual(parser["Foo Bar"]["foo"], "newbar") | Issue #11670. | test_readline_generator | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | MIT |
def test_source_as_bytes(self):
"""Issue #18260."""
lines = textwrap.dedent("""
[badbad]
[badbad]""").strip().split('\n')
parser = configparser.ConfigParser()
with self.assertRaises(configparser.DuplicateSectionError) as dse:
parser.read_file(lines, source=b"badbad")
self.assertEqual(
str(dse.exception),
"While reading from b'badbad' [line 2]: section 'badbad' "
"already exists"
)
lines = textwrap.dedent("""
[badbad]
bad = bad
bad = bad""").strip().split('\n')
parser = configparser.ConfigParser()
with self.assertRaises(configparser.DuplicateOptionError) as dse:
parser.read_file(lines, source=b"badbad")
self.assertEqual(
str(dse.exception),
"While reading from b'badbad' [line 3]: option 'bad' in section "
"'badbad' already exists"
)
lines = textwrap.dedent("""
[badbad]
= bad""").strip().split('\n')
parser = configparser.ConfigParser()
with self.assertRaises(configparser.ParsingError) as dse:
parser.read_file(lines, source=b"badbad")
self.assertEqual(
str(dse.exception),
"Source contains parsing errors: b'badbad'\n\t[line 2]: '= bad'"
)
lines = textwrap.dedent("""
[badbad
bad = bad""").strip().split('\n')
parser = configparser.ConfigParser()
with self.assertRaises(configparser.MissingSectionHeaderError) as dse:
parser.read_file(lines, source=b"badbad")
self.assertEqual(
str(dse.exception),
"File contains no section headers.\nfile: b'badbad', line: 1\n"
"'[badbad'"
) | Issue #18260. | test_source_as_bytes | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_configparser.py | MIT |
def test__getitem__(self):
"""Tests invoking FileInput.__getitem__() with the current
line number"""
t = self.writeTmp("line1\nline2\n")
with FileInput(files=[t]) as fi:
retval1 = fi[0]
self.assertEqual(retval1, "line1\n")
retval2 = fi[1]
self.assertEqual(retval2, "line2\n") | Tests invoking FileInput.__getitem__() with the current
line number | test__getitem__ | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test__getitem__invalid_key(self):
"""Tests invoking FileInput.__getitem__() with an index unequal to
the line number"""
t = self.writeTmp("line1\nline2\n")
with FileInput(files=[t]) as fi:
with self.assertRaises(RuntimeError) as cm:
fi[1]
self.assertEqual(cm.exception.args, ("accessing lines out of order",)) | Tests invoking FileInput.__getitem__() with an index unequal to
the line number | test__getitem__invalid_key | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test__getitem__eof(self):
"""Tests invoking FileInput.__getitem__() with the line number but at
end-of-input"""
t = self.writeTmp('')
with FileInput(files=[t]) as fi:
with self.assertRaises(IndexError) as cm:
fi[0]
self.assertEqual(cm.exception.args, ("end of input reached",)) | Tests invoking FileInput.__getitem__() with the line number but at
end-of-input | test__getitem__eof | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_nextfile_oserror_deleting_backup(self):
"""Tests invoking FileInput.nextfile() when the attempt to delete
the backup file would raise OSError. This error is expected to be
silently ignored"""
os_unlink_orig = os.unlink
os_unlink_replacement = UnconditionallyRaise(OSError)
try:
t = self.writeTmp("\n")
self.addCleanup(support.unlink, t + '.bak')
with FileInput(files=[t], inplace=True) as fi:
next(fi) # make sure the file is opened
os.unlink = os_unlink_replacement
fi.nextfile()
finally:
os.unlink = os_unlink_orig
# sanity check to make sure that our test scenario was actually hit
self.assertTrue(os_unlink_replacement.invoked,
"os.unlink() was not invoked") | Tests invoking FileInput.nextfile() when the attempt to delete
the backup file would raise OSError. This error is expected to be
silently ignored | test_nextfile_oserror_deleting_backup | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_readline_os_fstat_raises_OSError(self):
"""Tests invoking FileInput.readline() when os.fstat() raises OSError.
This exception should be silently discarded."""
os_fstat_orig = os.fstat
os_fstat_replacement = UnconditionallyRaise(OSError)
try:
t = self.writeTmp("\n")
with FileInput(files=[t], inplace=True) as fi:
os.fstat = os_fstat_replacement
fi.readline()
finally:
os.fstat = os_fstat_orig
# sanity check to make sure that our test scenario was actually hit
self.assertTrue(os_fstat_replacement.invoked,
"os.fstat() was not invoked") | Tests invoking FileInput.readline() when os.fstat() raises OSError.
This exception should be silently discarded. | test_readline_os_fstat_raises_OSError | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_readline_os_chmod_raises_OSError(self):
"""Tests invoking FileInput.readline() when os.chmod() raises OSError.
This exception should be silently discarded."""
os_chmod_orig = os.chmod
os_chmod_replacement = UnconditionallyRaise(OSError)
try:
t = self.writeTmp("\n")
with FileInput(files=[t], inplace=True) as fi:
os.chmod = os_chmod_replacement
fi.readline()
finally:
os.chmod = os_chmod_orig
# sanity check to make sure that our test scenario was actually hit
self.assertTrue(os_chmod_replacement.invoked,
"os.fstat() was not invoked") | Tests invoking FileInput.readline() when os.chmod() raises OSError.
This exception should be silently discarded. | test_readline_os_chmod_raises_OSError | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None_and_state_file_is_not_None(self):
"""Tests invoking fileinput.input() when fileinput._state is not None
and its _file attribute is also not None. Expect RuntimeError to
be raised with a meaningful error message and for fileinput._state
to *not* be modified."""
instance = MockFileInput()
instance._file = object()
fileinput._state = instance
with self.assertRaises(RuntimeError) as cm:
fileinput.input()
self.assertEqual(("input() already active",), cm.exception.args)
self.assertIs(instance, fileinput._state, "fileinput._state") | Tests invoking fileinput.input() when fileinput._state is not None
and its _file attribute is also not None. Expect RuntimeError to
be raised with a meaningful error message and for fileinput._state
to *not* be modified. | test_state_is_not_None_and_state_file_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None_and_state_file_is_None(self):
"""Tests invoking fileinput.input() when fileinput._state is not None
but its _file attribute *is* None. Expect it to create and return
a new fileinput.FileInput object with all method parameters passed
explicitly to the __init__() method; also ensure that
fileinput._state is set to the returned instance."""
instance = MockFileInput()
instance._file = None
fileinput._state = instance
self.do_test_call_input() | Tests invoking fileinput.input() when fileinput._state is not None
but its _file attribute *is* None. Expect it to create and return
a new fileinput.FileInput object with all method parameters passed
explicitly to the __init__() method; also ensure that
fileinput._state is set to the returned instance. | test_state_is_not_None_and_state_file_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests invoking fileinput.input() when fileinput._state is None
Expect it to create and return a new fileinput.FileInput object
with all method parameters passed explicitly to the __init__()
method; also ensure that fileinput._state is set to the returned
instance."""
fileinput._state = None
self.do_test_call_input() | Tests invoking fileinput.input() when fileinput._state is None
Expect it to create and return a new fileinput.FileInput object
with all method parameters passed explicitly to the __init__()
method; also ensure that fileinput._state is set to the returned
instance. | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def do_test_call_input(self):
"""Tests that fileinput.input() creates a new fileinput.FileInput
object, passing the given parameters unmodified to
fileinput.FileInput.__init__(). Note that this test depends on the
monkey patching of fileinput.FileInput done by setUp()."""
files = object()
inplace = object()
backup = object()
bufsize = object()
mode = object()
openhook = object()
# call fileinput.input() with different values for each argument
result = fileinput.input(files=files, inplace=inplace, backup=backup,
bufsize=bufsize,
mode=mode, openhook=openhook)
# ensure fileinput._state was set to the returned object
self.assertIs(result, fileinput._state, "fileinput._state")
# ensure the parameters to fileinput.input() were passed directly
# to FileInput.__init__()
self.assertIs(files, result.files, "files")
self.assertIs(inplace, result.inplace, "inplace")
self.assertIs(backup, result.backup, "backup")
self.assertIs(bufsize, result.bufsize, "bufsize")
self.assertIs(mode, result.mode, "mode")
self.assertIs(openhook, result.openhook, "openhook") | Tests that fileinput.input() creates a new fileinput.FileInput
object, passing the given parameters unmodified to
fileinput.FileInput.__init__(). Note that this test depends on the
monkey patching of fileinput.FileInput done by setUp(). | do_test_call_input | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests that fileinput.close() does nothing if fileinput._state
is None"""
fileinput._state = None
fileinput.close()
self.assertIsNone(fileinput._state) | Tests that fileinput.close() does nothing if fileinput._state
is None | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests that fileinput.close() invokes close() on fileinput._state
and sets _state=None"""
instance = MockFileInput()
fileinput._state = instance
fileinput.close()
self.assertExactlyOneInvocation(instance, "close")
self.assertIsNone(fileinput._state) | Tests that fileinput.close() invokes close() on fileinput._state
and sets _state=None | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.nextfile() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.nextfile()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.nextfile() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.nextfile() when fileinput._state is not None.
Ensure that it invokes fileinput._state.nextfile() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
nextfile_retval = object()
instance = MockFileInput()
instance.return_values["nextfile"] = nextfile_retval
fileinput._state = instance
retval = fileinput.nextfile()
self.assertExactlyOneInvocation(instance, "nextfile")
self.assertIs(retval, nextfile_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.nextfile() when fileinput._state is not None.
Ensure that it invokes fileinput._state.nextfile() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.filename() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.filename()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.filename() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.filename() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filename() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
filename_retval = object()
instance = MockFileInput()
instance.return_values["filename"] = filename_retval
fileinput._state = instance
retval = fileinput.filename()
self.assertExactlyOneInvocation(instance, "filename")
self.assertIs(retval, filename_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.filename() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filename() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.lineno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.lineno()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.lineno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.lineno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.lineno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
lineno_retval = object()
instance = MockFileInput()
instance.return_values["lineno"] = lineno_retval
fileinput._state = instance
retval = fileinput.lineno()
self.assertExactlyOneInvocation(instance, "lineno")
self.assertIs(retval, lineno_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.lineno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.lineno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.filelineno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.filelineno()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.filelineno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.filelineno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filelineno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
filelineno_retval = object()
instance = MockFileInput()
instance.return_values["filelineno"] = filelineno_retval
fileinput._state = instance
retval = fileinput.filelineno()
self.assertExactlyOneInvocation(instance, "filelineno")
self.assertIs(retval, filelineno_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.filelineno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.filelineno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.fileno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.fileno()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.fileno() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.fileno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.fileno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
fileno_retval = object()
instance = MockFileInput()
instance.return_values["fileno"] = fileno_retval
instance.fileno_retval = fileno_retval
fileinput._state = instance
retval = fileinput.fileno()
self.assertExactlyOneInvocation(instance, "fileno")
self.assertIs(retval, fileno_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.fileno() when fileinput._state is not None.
Ensure that it invokes fileinput._state.fileno() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.isfirstline() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.isfirstline()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.isfirstline() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.isfirstline() when fileinput._state is not None.
Ensure that it invokes fileinput._state.isfirstline() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
isfirstline_retval = object()
instance = MockFileInput()
instance.return_values["isfirstline"] = isfirstline_retval
fileinput._state = instance
retval = fileinput.isfirstline()
self.assertExactlyOneInvocation(instance, "isfirstline")
self.assertIs(retval, isfirstline_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.isfirstline() when fileinput._state is not None.
Ensure that it invokes fileinput._state.isfirstline() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_None(self):
"""Tests fileinput.isstdin() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state"""
fileinput._state = None
with self.assertRaises(RuntimeError) as cm:
fileinput.isstdin()
self.assertEqual(("no active input()",), cm.exception.args)
self.assertIsNone(fileinput._state) | Tests fileinput.isstdin() when fileinput._state is None.
Ensure that it raises RuntimeError with a meaningful error message
and does not modify fileinput._state | test_state_is_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def test_state_is_not_None(self):
"""Tests fileinput.isstdin() when fileinput._state is not None.
Ensure that it invokes fileinput._state.isstdin() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object."""
isstdin_retval = object()
instance = MockFileInput()
instance.return_values["isstdin"] = isstdin_retval
fileinput._state = instance
retval = fileinput.isstdin()
self.assertExactlyOneInvocation(instance, "isstdin")
self.assertIs(retval, isstdin_retval)
self.assertIs(fileinput._state, instance) | Tests fileinput.isstdin() when fileinput._state is not None.
Ensure that it invokes fileinput._state.isstdin() exactly once,
returns whatever it returns, and does not modify fileinput._state
to point to a different object. | test_state_is_not_None | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_fileinput.py | MIT |
def int_to_float(n):
"""
Correctly-rounded integer-to-float conversion.
"""
# Constants, depending only on the floating-point format in use.
# We use an extra 2 bits of precision for rounding purposes.
PRECISION = sys.float_info.mant_dig + 2
SHIFT_MAX = sys.float_info.max_exp - PRECISION
Q_MAX = 1 << PRECISION
ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]
# Reduce to the case where n is positive.
if n == 0:
return 0.0
elif n < 0:
return -int_to_float(-n)
# Convert n to a 'floating-point' number q * 2**shift, where q is an
# integer with 'PRECISION' significant bits. When shifting n to create q,
# the least significant bit of q is treated as 'sticky'. That is, the
# least significant bit of q is set if either the corresponding bit of n
# was already set, or any one of the bits of n lost in the shift was set.
shift = n.bit_length() - PRECISION
q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift))
# Round half to even (actually rounds to the nearest multiple of 4,
# rounding ties to a multiple of 8).
q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]
# Detect overflow.
if shift + (q == Q_MAX) > SHIFT_MAX:
raise OverflowError("integer too large to convert to float")
# Checks: q is exactly representable, and q**2**shift doesn't overflow.
assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig)
assert q * 2**shift <= sys.float_info.max
# Some circularity here, since float(q) is doing an int-to-float
# conversion. But here q is of bounded size, and is exactly representable
# as a float. In a low-level C-like language, this operation would be a
# simple cast (e.g., from unsigned long long to double).
return math.ldexp(float(q), shift) | Correctly-rounded integer-to-float conversion. | int_to_float | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py | MIT |
def truediv(a, b):
"""Correctly-rounded true division for integers."""
negative = a^b < 0
a, b = abs(a), abs(b)
# exceptions: division by zero, overflow
if not b:
raise ZeroDivisionError("division by zero")
if a >= DBL_MIN_OVERFLOW * b:
raise OverflowError("int/int too large to represent as a float")
# find integer d satisfying 2**(d - 1) <= a/b < 2**d
d = a.bit_length() - b.bit_length()
if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
d += 1
# compute 2**-exp * a / b for suitable exp
exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
a, b = a << max(-exp, 0), b << max(exp, 0)
q, r = divmod(a, b)
# round-half-to-even: fractional part is r/b, which is > 0.5 iff
# 2*r > b, and == 0.5 iff 2*r == b.
if 2*r > b or 2*r == b and q % 2 == 1:
q += 1
result = math.ldexp(q, exp)
return -result if negative else result | Correctly-rounded true division for integers. | truediv | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py | MIT |
def check_truediv(self, a, b, skip_small=True):
"""Verify that the result of a/b is correctly rounded, by
comparing it with a pure Python implementation of correctly
rounded division. b should be nonzero."""
# skip check for small a and b: in this case, the current
# implementation converts the arguments to float directly and
# then applies a float division. This can give doubly-rounded
# results on x87-using machines (particularly 32-bit Linux).
if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
return
try:
# use repr so that we can distinguish between -0.0 and 0.0
expected = repr(truediv(a, b))
except OverflowError:
expected = 'overflow'
except ZeroDivisionError:
expected = 'zerodivision'
try:
got = repr(a / b)
except OverflowError:
got = 'overflow'
except ZeroDivisionError:
got = 'zerodivision'
self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
"expected {}, got {}".format(a, b, expected, got)) | Verify that the result of a/b is correctly rounded, by
comparing it with a pure Python implementation of correctly
rounded division. b should be nonzero. | check_truediv | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_long.py | MIT |
def run_once(loop):
"""Legacy API to run once through the event loop.
This is the recommended pattern for test code. It will poll the
selector once and run all callbacks scheduled in response to I/O
events.
"""
loop.call_soon(loop.stop)
loop.run_forever() | Legacy API to run once through the event loop.
This is the recommended pattern for test code. It will poll the
selector once and run all callbacks scheduled in response to I/O
events. | run_once | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def advance_time(self, advance):
"""Move test time forward."""
if advance:
self._time += advance | Move test time forward. | advance_time | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def add_reader(self, fd, callback, *args):
"""Add a reader callback."""
self._ensure_fd_no_transport(fd)
return self._add_reader(fd, callback, *args) | Add a reader callback. | add_reader | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def remove_reader(self, fd):
"""Remove a reader callback."""
self._ensure_fd_no_transport(fd)
return self._remove_reader(fd) | Remove a reader callback. | remove_reader | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def add_writer(self, fd, callback, *args):
"""Add a writer callback.."""
self._ensure_fd_no_transport(fd)
return self._add_writer(fd, callback, *args) | Add a writer callback.. | add_writer | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def remove_writer(self, fd):
"""Remove a writer callback."""
self._ensure_fd_no_transport(fd)
return self._remove_writer(fd) | Remove a writer callback. | remove_writer | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def disable_logger():
"""Context manager to disable asyncio logger.
For example, it can be used to ignore warnings in debug mode.
"""
old_level = logger.level
try:
logger.setLevel(logging.CRITICAL+1)
yield
finally:
logger.setLevel(old_level) | Context manager to disable asyncio logger.
For example, it can be used to ignore warnings in debug mode. | disable_logger | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def mock_nonblocking_socket(proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM,
family=socket.AF_INET):
"""Create a mock of a non-blocking socket."""
sock = mock.MagicMock(socket.socket)
sock.proto = proto
sock.type = type
sock.family = family
sock.gettimeout.return_value = 0.0
return sock | Create a mock of a non-blocking socket. | mock_nonblocking_socket | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/utils.py | MIT |
def _test_repr_or_str(self, fn, expect_id):
"""Test Queue's repr or str.
fn is repr or str. expect_id is True if we expect the Queue's id to
appear in fn(Queue()).
"""
def gen():
when = yield
self.assertAlmostEqual(0.1, when)
when = yield 0.1
self.assertAlmostEqual(0.2, when)
yield 0.1
loop = self.new_test_loop(gen)
q = asyncio.Queue(loop=loop)
self.assertTrue(fn(q).startswith('<Queue'), fn(q))
id_is_present = hex(id(q)) in fn(q)
self.assertEqual(expect_id, id_is_present)
async def add_getter():
q = asyncio.Queue(loop=loop)
# Start a task that waits to get.
asyncio.Task(q.get(), loop=loop)
# Let it start waiting.
await asyncio.sleep(0.1, loop=loop)
self.assertTrue('_getters[1]' in fn(q))
# resume q.get coroutine to finish generator
q.put_nowait(0)
loop.run_until_complete(add_getter())
async def add_putter():
q = asyncio.Queue(maxsize=1, loop=loop)
q.put_nowait(1)
# Start a task that waits to put.
asyncio.Task(q.put(2), loop=loop)
# Let it start waiting.
await asyncio.sleep(0.1, loop=loop)
self.assertTrue('_putters[1]' in fn(q))
# resume q.put coroutine to finish generator
q.get_nowait()
loop.run_until_complete(add_putter())
q = asyncio.Queue(loop=loop)
q.put_nowait(1)
self.assertTrue('_queue=[1]' in fn(q)) | Test Queue's repr or str.
fn is repr or str. expect_id is True if we expect the Queue's id to
appear in fn(Queue()). | _test_repr_or_str | python | sajjadium/ctf-archives | ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/test_queues.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/test/test_asyncio/test_queues.py | MIT |
Subsets and Splits