text stringlengths 79 3.72M |
|---|
<vulnerable_code> # verify readinto refuses text files
a = array('b', b'x'*10)
self.f.close()
self.f = self.open(TESTFN, 'r')
if hasattr(self.f, "readinto"):
self.assertRaises(TypeError, self.f.readinto, a)
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning i... |
<vulnerable_code> def _generate_infile_setup_code(self):
"""Returns the infile = ... line of code to make a TextIOWrapper."""
return ('import %s as io ;'
'infile = io.open(sys.stdin.fileno(), "rt", newline=None) ;'
'assert isinstance(infile, io.TextIOWrapper)' %
... |
<vulnerable_code> def test_invalid_operations(self):
# Try writing on a file opened in read mode and vice-versa.
exc = self.UnsupportedOperation
for mode in ("w", "wb"):
with self.open(os_helper.TESTFN, mode) as fp:
self.assertRaises(exc, fp.read)
s... |
<vulnerable_code> (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
(void)printone(out, "# arenas highwater mark", narenas_highwater);
(void)printone(out, "# arenas allocated current", narenas);
#ifdef USE_INTERIOR_NODES
(void)printone(out, "# arena map mid nodes", arena_map_mi... |
<vulnerable_code> stable_data, stable_exported_data, stable_functions = get_limited_api_definitions(
headers
)
macros = get_limited_api_macros(headers)
stable_symbols = {
symbol
for symbol in (stable_functions | stable_exported_data | stable_data | macros)
if symbol.start... |
<vulnerable_code> if 'd' not in sysconfig.get_config_var('ABIFLAGS'):
# Non-debug mode: Build xxlimited with limited API
self.add(Extension('xxlimited', ['xxlimited.c'],
define_macros=[('Py_LIMITED_API', '0x03100000')]))
self.add(Extension('xxlim... |
<vulnerable_code> argval, argrepr = _get_const_info(arg, constants)
elif op in hasname:
argval, argrepr = _get_name_info(arg, names)
elif op in hasjrel:
argval = offset + 2 + arg
argrepr = "to " + repr(argval)
elif op in ... |
<vulnerable_code># Python 3.10a2 3432 (Function annotation for MAKE_FUNCTION is changed from dict to tuple bpo-42202)
# Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0)
# Python 3.10a6 3434 (PEP 634: Structural Pattern Matching)
#
# MAGIC must change whenever the bytecode emitted by the compiler... |
<vulnerable_code>
%3d 6 CALL_FUNCTION 2
8 GET_ITER
>> 10 FOR_ITER 4 (to 16)
12 STORE_FAST 0 (res)
%3d 14 JUMP_ABSOLUTE 10
%3d >> 16 LOAD_CONST 0 (None)
18 RETURN_VALUE
... |
<vulnerable_code>int
PyCode_Addr2Line(PyCodeObject *co, int addrq)
{
if (addrq == -1) {
return co->co_firstlineno;
}
assert(addrq >= 0 && addrq < PyBytes_GET_SIZE(co->co_code));<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
int
PyCo... |
<vulnerable_code> {"f_code", T_OBJECT, OFF(f_code), READONLY},
{"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
{"f_globals", T_OBJECT, OFF(f_globals), READONLY},
{"f_lasti", T_INT, OFF(f_lasti), READONLY},
{"f_trace_lines", T_B... |
<vulnerable_code> return NULL;
}
if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
return NULL;
assert(f->f_stackdepth > 0);
yf = f->f_valuestack[f->f_stackdepth-1];
Py_DECREF(ret);
/* Termination repetition of YIELD_FROM */
... |
<vulnerable_code>/* Code access macros */
/* The integer overflow is checked by an assertion below. */
#define INSTR_OFFSET() \
(sizeof(_Py_CODEUNIT) * (int)(next_instr - first_instr))
#define NEXTOPARG() do { \
_Py_CODEUNIT word = *next_instr; \
opcode = _Py_OPCODE(word); \
oparg = _Py_O... |
<vulnerable_code> if (is_relative_jump(instr)) {
instr->i_oparg -= bsize;
}
instr->i_oparg *= sizeof(_Py_CODEUNIT);
if (instrsize(instr->i_oparg) != isize) {
extended_arg_recompile = 1;
... |
<vulnerable_code> assert(tb_next == NULL || PyTraceBack_Check(tb_next));
assert(frame != NULL);
return tb_create_raw((PyTracebackObject *)tb_next, frame, frame->f_lasti,
PyFrame_GetLineNumber(frame));
}
PUTS(fd, "???");
}
/* PyFrame_GetLineNumber() was introduced i... |
<vulnerable_code> return self.f_lineno
try:
return self.co.addr2line(self.f_lasti)
except Exception:
# bpo-34989: addr2line() is a complex function, it can fail in many
# ways. For example, it fails with a TypeError on "FakeRepr" if<commit_title>[PATCH 003... |
<vulnerable_code> print("The program finished and will be restarted")
except Restart:
print("Restarting", mainpyfile, "with arguments:")
print("\t" + " ".join(args))
except SystemExit:
# In most cases SystemExit does not warrant a post-mortem session.
... |
<vulnerable_code> 'Fail to handle a syntax error in the debuggee.'
.format(expected, stdout))
def test_readrc_kwarg(self):
script = textwrap.dedent("""<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
'Fail... |
<vulnerable_code> quit
"""
stdout, stderr = self.run_pdb_script(script, commands)
output = '\n'.join([x.strip() for x in stdout.splitlines()])
self.assertIn("Restarting main.py with arguments:\na b c", output)
self.assertIn("Restarting main.py with arguments:\nd e f", ... |
<vulnerable_code> def test_tracemalloc(self):
self.addCleanup(os_helper.unlink, os_helper.TESTFN)
with open(os_helper.TESTFN, 'w') as fp:
fp.write(textwrap.dedent("""
def func():
f = open(__file__)
# Emit ResourceWarning
... |
<vulnerable_code> def __init__(self, filename, stream=None):
close_stream = None
if stream is None:
stream = open(filename)
close_stream = stream.close
self.filename = filename
self.stream = stream<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in ... |
<vulnerable_code> # if flist is provided then load it
if args.flist:
try:
with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
for line in f:
compile_dests.append(line.strip())
except OSError:<commit_title>[PATCH 003/413] bpo-43651: Fix E... |
<vulnerable_code> try:
fd = os.open(os.devnull, os.O_RDONLY)
try:
sys.stdin = open(fd, closefd=False)
except:
os.close(fd)
raise<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
try:
... |
<vulnerable_code> self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
self.bc_path = importlib.util.cache_from_source(self.source_path)
with open(self.source_path, 'w') as file:
file.write('x = 123\n')
self.source_path2 = os.... |
<vulnerable_code> indented = script.replace('\n', '\n ')
wrapped = dedent(f"""
import contextlib
with open({w}, 'w') as spipe:
with contextlib.redirect_stdout(spipe):
{indented}
""")
return wrapped, open(r)
def _run_output(interp, request, ... |
<vulnerable_code>
def create_readonly_file(self, filename):
file_path = os.path.join(self.temp_dir, filename)
with open(file_path, 'w') as file:
file.write(filename)
os.chmod(file_path, stat.S_IREAD)
('invalid', '@no-such-path\n'),
]
for path, text in... |
<vulnerable_code> except TypeError:
pass
inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
'exception_hierarchy.txt'))
try:
superclass_name = inheritance_tree.readline().rstrip()
try:<commi... |
<vulnerable_code> try:
for m in modules:
fname = m + '.py'
with open(fname, 'w') as f:
f.write(textwrap.dedent(modules[m]))
linecache.checkcache(fname)
importlib.invalidate_caches()<commit_title>[PATCH 003/413] bpo-43651:... |
<vulnerable_code>
def test_fileclosed(self):
try:
with open(os_helper.TESTFN, "w") as f:
self.assertIs(f.closed, False)
self.assertIs(f.closed, True)
finally:<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description>... |
<vulnerable_code>
def write_testfile(self):
# NB the first 4 lines are also used to test input, below
fp = open(TESTFN, 'w')
self.addCleanup(unlink, TESTFN)
with fp:
fp.write('1+1\n')
def test_open(self):
self.write_testfile()
fp = open(TESTFN, 'r')
... |
<vulnerable_code> >>> from test.support.os_helper import temp_dir
>>> with temp_dir() as tmpdir:
... fn = os.path.join(tmpdir, 'myfile.doc')
... with open(fn, 'w') as f:
... _ = f.write('This is a very simple test file.\n')
... _ = f.write(' >>> 1 + 1\n')
... ... |
<vulnerable_code> self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
self.raise_catch(EOFError, "EOFError")
fp = open(TESTFN, 'w')
fp.close()
fp = open(TESTFN, 'r')
savestdin = sys.stdin
try:
try:<commit_title>[PATCH 003/413] bpo-43... |
<vulnerable_code> def test_setup_annotations_line(self):
# check that SETUP_ANNOTATIONS does not create spurious line numbers
try:
with open(ann_module.__file__) as f:
txt = f.read()
co = compile(txt, ann_module.__file__, 'exec')
self.assertEqual(co... |
<vulnerable_code> self.assertNotIn("sched", sys.modules)
def test_unlink(self):
with open(TESTFN, "w") as f:
pass
os_helper.unlink(TESTFN)
self.assertFalse(os.path.exists(TESTFN))
def test_forget(self):
mod_filename = TESTFN + '.py'
with open(mod_file... |
<vulnerable_code>
def parse(filename):
"""Parse ASDL from the given file and return a Module node describing it."""
with open(filename) as f:
parser = ASDLParser()
return parser.parse(f.read())
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description>... |
<vulnerable_code> if (encoding == NULL || encoding == Py_None) {
PyInterpreterState *interp = _PyInterpreterState_GET();
if (_PyInterpreterState_GetConfig(interp)->warn_default_encoding) {
PyErr_WarnEx(PyExc_EncodingWarning,
"'encoding' argument not specified", st... |
<vulnerable_code> self->ok = 0;
self->detached = 0;
if (errors == Py_None) {
errors = _PyUnicode_FromId(&PyId_strict); /* borrowed */
if (errors == NULL) {
self->encodefunc = NULL;
self->b2cratio = 0.0;
if (encoding == NULL) {
PyInterpreterState *interp = _PyInterpreterS... |
<vulnerable_code> .tp_vectorcall = (vectorcallfunc)float_vectorcall,
};
int
_PyFloat_Init(void)
{
/* We attempt to determine if this machine is using IEEE
double_format = detected_double_format;
float_format = detected_float_format;
/* Init float info */
if (FloatInfoType.tp_name == NULL) {
... |
<vulnerable_code>
interp->small_ints[i] = v;
}
if (_Py_IsMainInterpreter(interp)) {
/* initialize int_info */
if (Int_InfoType.tp_name == NULL) {
if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) {
return 0;
}
}
}
... |
<vulnerable_code> if (_PyUnicode_FromId(&PyId_n_sequence_fields) == NULL
|| _PyUnicode_FromId(&PyId_n_fields) == NULL
|| _PyUnicode_FromId(&PyId_n_unnamed_fields) == NULL)
return -1;
return 0;
}<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_desc... |
<vulnerable_code>PyStatus
_PyUnicode_Init(PyInterpreterState *interp)
{
/* XXX - move this array to unicodectype.c ? */
const Py_UCS2 linebreak[] = {
0x000A, /* LINE FEED */
0x000D, /* CARRIAGE RETURN */
0x001C, /* FILE SEPARATOR */
0x001D, /* GROUP SEPARATOR */
0x001E, /... |
<vulnerable_code>
PyStatus
_PyErr_Init(void)
{
if (UnraisableHookArgsType.tp_name == NULL) {
if (PyStructSequence_InitType2(&UnraisableHookArgsType,<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
PyStatus
_PyErr_InitTypes(void)
{
if (... |
<vulnerable_code>
static PyStatus
pycore_init_types(PyInterpreterState *interp)
{
PyStatus status;
int is_main_interp = _Py_IsMainInterpreter(interp);
status = _PyGC_Init(interp);
if (_PyStatus_EXCEPTION(status)) {
return status;
}
// Create the empty tuple singleton. It must be creat... |
<vulnerable_code>#include "frameobject.h"
#include "interpreteridobject.h"
#ifdef __cplusplus
extern "C" {
#endif
Py_XDECREF(o);
}
PyObject *
PyObject_Init(PyObject *op, PyTypeObject *tp)
{<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
#include "... |
<vulnerable_code>EXPORT_FUNC(_PyTrash_destroy_chain)
EXPORT_FUNC(_PyTrash_thread_deposit_object)
EXPORT_FUNC(_PyTrash_thread_destroy_chain)
EXPORT_FUNC(Py_AddPendingCall)
EXPORT_FUNC(Py_AtExit)
EXPORT_FUNC(Py_BuildValue)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descriptio... |
<vulnerable_code>## # Uncomment these lines if you want to play with xxmodule.c
## self.add(Extension('xx', ['xxmodule.c']))
if 'd' not in sysconfig.get_config_var('ABIFLAGS'):
# Non-debug mode: Build xxlimited with limited API
self.add(Extension('xxlimited', ['xxlimited... |
<vulnerable_code>
def generate_limited_api_symbols(args):
if hasattr(sys, "gettotalrefcount"):
print(
"Stable ABI symbols cannot be generated from a debug build", file=sys.stderr
)
sys.exit(1)
library = sysconfig.get_config_var("LIBRARY")
ldlibrary = sysconfig.get_config... |
<vulnerable_code> pass
*/
#include "Python.h"
// Module state<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
pass
*/
#define Py_LIMITED_API 0x030a0000
#include "Python.h"
// Module state |
<vulnerable_code> * See the xxlimited module for an extension module template.
*/
/* Xxo objects */
#include "Python.h"
static PyObject *ErrorObject;
typedef struct {<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
* See the xxlimited module for an... |
<vulnerable_code>## self.add(Extension('xx', ['xxmodule.c']))
# Limited C API
self.add(Extension('xxlimited', ['xxlimited.c'],
define_macros=[('Py_LIMITED_API', '0x030a0000')]))
self.add(Extension('xxlimited_35', ['xxlimited_35.c'],
... |
<vulnerable_code> self.assertRaises(ValueError, a.index, None)
self.assertRaises(ValueError, a.index, self.outside)
def test_count(self):
example = 2*self.example
a = array.array(self.typecode, example)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)... |
<vulnerable_code>array.array.index
v: object
/
Return index of first occurrence of v in the array.
[clinic start generated code]*/
static PyObject *
array_array_index(arrayobject *self, PyObject *v)
/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
{
Py_ssize_t i;
for (... |
<vulnerable_code> self.fncache = {}
self.frame_returning = None
def canonic(self, filename):
"""Return canonical form of filename.
# Call self.get_*break*() to see the breakpoints or better
# for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
def set_break(self, filename, li... |
<vulnerable_code>dry_run = 0
def reset_Breakpoint():
_bdb.Breakpoint.next = 1
_bdb.Breakpoint.bplist = {}
_bdb.Breakpoint.bpbynumber = [None]
def info_breakpoints():
bp_list = [bp for bp in _bdb.Breakpoint.bpbynumber if bp]
with TracerRun(self) as tracer:
self.assertRaises(BdbErro... |
<vulnerable_code> BAZ
"""
def test_pdb_breakpoint_commands():
"""Test basic commands related to breakpoints.
First, need to clear bdb state that might be left over from previous tests.
Otherwise, the new breakpoints might get assigned different numbers.
>>> from bdb import Breakpoint
>>> B... |
<vulnerable_code> # This would be a good place for a DeprecationWarning if
# we ended up going that route.
if hasattr(finder, 'find_loader'):
loader, portions = finder.find_loader(fullname)
else:
msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; "
... |
<vulnerable_code> ) = util.test_both(LoaderTests, machinery=machinery)
class MultiPhaseExtensionModuleTests(abc.LoaderTests):
"""Test loading extension modules with multi-phase initialization (PEP 489)
"""
def setUp(self):
self.name = '_testmultiphase'
self.name, self.spec.origin)
... |
<vulnerable_code> return self.loader, self.portions
path = 'testing path'
with util.import_state(path_importer_cache={path: TestFinder()}):
self.assertIsNone(
self.machinery.PathFinder.find_spec('whatever', [path]))
success_finder = TestFinder()
... |
<vulnerable_code> def test_module_repr(self):
mod = types.ModuleType('blah')
with warnings.catch_warnings():
warnings.simplefilter("ignore")
with self.assertRaises(NotImplementedError):
self.ins.module_repr(mod)
original_repr = repr(mod)
mod.__l... |
<vulnerable_code> Distribution.from_name('does-not-exist')
def test_package_not_found_mentions_metadata(self):
"""
When a package is not found, that could indicate that the
packgae is not installed or that it is installed without
metadata. Ensure the exception mentions me... |
<vulnerable_code> self.assertEqual(ep.dist.version, "1.0.0")
def test_entry_points_unique_packages(self):
"""
Entry points should only be exposed for the first package
on sys.path with a given name.
"""
alt_site_dir = self.fixtures.enter_context(fixtures.tempdir()... |
<vulnerable_code> data = data01
def test_natural_path(self):
"""
Guarantee the internal implementation detail that
file-system-backed resources do not get the tempdir
treatment.
"""
with resources.path(self.data, 'utf-8.file') as path:
assert 'data' in... |
<vulnerable_code> path.open()
def test_join_path(self):
print('test_join_path')
prefix = os.path.abspath(os.path.join(__file__, '..'))
data01 = os.path.join(prefix, 'data01')
path = MultiplexedPath(self.folder, data01)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingW... |
<vulnerable_code> 'only applies to candidate or final python release levels'
)
def test_magic_number(self):
"""
Each python minor release should generally have a MAGIC_NUMBER
that does not change once the release reaches candidate status.
Once a release reaches candidate ... |
<vulnerable_code>import types
import warnings
warnings.warn("the imp module is deprecated in favour of importlib; "
"see the module's documentation for alternative uses",
DeprecationWarning, stacklevel=2)
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<com... |
<vulnerable_code> """
@functools.wraps(fxn)
def set_package_wrapper(*args, **kwargs):
warnings.warn('The import system now takes care of this automatically.',
DeprecationWarning, stacklevel=2)
module = fxn(*args, **kwargs)
if getattr(module, '__package__', None) ... |
<vulnerable_code>
def __init__(self, path=None):
global imp
warnings.warn("This emulation is deprecated, use 'importlib' instead",
DeprecationWarning)
_import_imp()
self.path = path
code = source = None
def __init__(self, fullname, file, filename, etc):
... |
<vulnerable_code>
def check_deprecated(self):
return check_warnings(
("This emulation is deprecated, use 'importlib' instead",
DeprecationWarning))
def test_importer_deprecated(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descr... |
<vulnerable_code> srcname = os.path.join(d, 'dummy.c')
libname = 'py_ctypes_test_dummy'
dstname = os.path.join(d, 'lib%s.so' % libname)
with open(srcname, 'w') as f:
pass
self.assertTrue(os.path.exists(srcname))
# compile the file to... |
<vulnerable_code> __all__.append("popen")
# Supply os.fdopen()
def fdopen(fd, *args, **kwargs):
if not isinstance(fd, int):
raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
import io
return io.open(fd, *args, **kwargs)
# For testing purposes, make sure the function is avail... |
<vulnerable_code> proc = self.Process(target=self._test_stderr_flush, args=(testfn,))
proc.start()
proc.join()
with open(testfn, 'r') as f:
err = f.read()
# The whole traceback was printed
self.assertIn("ZeroDivisionError", err)
@classmethod
def... |
<vulnerable_code> self.skipTest("Could not retrieve "+self.mapfileurl)
def open_mapping_file(self):
return support.open_urlresource(self.mapfileurl)
def test_mapping_file(self):
if self.mapfileurl.endswith('.xml'):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_... |
<vulnerable_code>
def test_nonbinary_file(self):
sock = self.make_socket()
with open(os_helper.TESTFN, 'r') as f:
with self.assertRaisesRegex(ValueError, "binary mode"):
self.run_loop(self.loop.sock_sendfile(sock, f))
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingW... |
<vulnerable_code>
rpipe, wpipe = os.pipe()
rpipeobj = io.open(rpipe, 'rb', 1024)
wpipeobj = io.open(wpipe, 'w', 1024)
async def connect():
read_transport, _ = await loop.connect_read_pipe(<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<comm... |
<vulnerable_code> for mode in ("wt", "xt"):
if mode == "xt":
unlink(self.filename)
with self.open(self.filename, mode) as f:
f.write(text)
with open(self.filename, "rb") as f:
file_data = ext_decompress(f.read()).decode("ascii")
... |
<vulnerable_code> test_functions.append(lambda x : cmath.log(14.-27j, x))
def setUp(self):
self.test_values = open(test_file)
def tearDown(self):
self.test_values.close()<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
te... |
<vulnerable_code> # the dict whereas the module was destroyed
filename = os_helper.TESTFN
self.addCleanup(os_helper.unlink, filename)
with open(filename, "w") as script:
print("import sys", file=script)
print("del sys.modules['__main__']", file=script)
asse... |
<vulnerable_code> # does not alter the value of sys.path[0]
with os_helper.temp_dir() as script_dir:
with os_helper.change_cwd(path=script_dir):
with open("-c", "w") as f:
f.write("data")
rc, out, err = assert_python_ok('-c',
... |
<vulnerable_code> fname = __file__
if fname.lower().endswith('pyc'):
fname = fname[:-1]
with open(fname, 'r') as f:
fcontents = f.read()
sample_code = [
['<assign>', 'x = 5'],<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25... |
<vulnerable_code> file1 = support.findfile("cfgparser.1")
# check when we pass a mix of readable and non-readable files:
cf = self.newconfig()
parsed_files = cf.read([file1, "nonexistent-file"])
self.assertEqual(parsed_files, [file1])
self.assertEqual(cf.get("Foo Bar", "fo... |
<vulnerable_code> tfn = tempfile.mktemp()
try:
f = None
with open(tfn, "w") as f:
self.assertFalse(f.closed)
f.write("Booh\n")
self.assertTrue(f.closed)
f = None
with self.assertRaises(ZeroDivisionError):
... |
<vulnerable_code>
def _write_test(self, fields, expect, **kwargs):
with TemporaryFile("w+", newline='') as fileobj:
writer = csv.writer(fileobj, **kwargs)
writer.writerow(fields)
fileobj.seek(0)
expect + writer.dialect.lineterminator)
de... |
<vulnerable_code> self.assertEqual(f.keys(), [])
def test_eval(self):
with open(_fname + '.dir', 'w') as stream:
stream.write("str(print('Hacked!')), 0\n")
with support.captured_stdout() as stdout:
with self.assertRaises(ValueError):<commit_title>[PATCH 003/413] b... |
<vulnerable_code> global skip_expected
if skip_expected:
raise unittest.SkipTest
with open(file) as f:
for line in f:
line = line.replace('\r\n', '').replace('\n', '')
#print line<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning i... |
<vulnerable_code> #with open('test_difflib_expect.html','w') as fp:
# fp.write(actual)
with open(findfile('test_difflib_expect.html')) as fp:
self.assertEqual(actual, fp.read())
def test_recursion_limit(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in tes... |
<vulnerable_code> id fn arg -> expected [flag]*
"""
with open(fname) as fp:
for line in fp:
# strip comments, and skip blank lines
if '--' in line:
Empty lines or lines starting with -- are ignored
yields id, fn, arg_real, arg_imag, exp_real, exp_imag
"""
wi... |
<vulnerable_code> def test_output_file_when_changing_directory(self):
with temp_dir() as tmpdir, change_cwd(tmpdir):
os.mkdir('dest')
with open('demo.py', 'w') as f:
f.write('import os; os.chdir("dest")')
assert_python_ok(<commit_title>[PATCH 003/413] bpo-... |
<vulnerable_code> if _SYSTEM_VERSION is None:
_SYSTEM_VERSION = ''
try:
f = open('/System/Library/CoreServices/SystemVersion.plist')
except OSError:
# We're on a plain darwin box, fall back to the default
# behaviour.
if _cache_default_sysroot is not N... |
<vulnerable_code>
@support.requires_IEEE_754
def test_format_testfile(self):
with open(format_testfile) as testfile:
for line in testfile:
if line.startswith('--'):
continue
class ReprTestCase(unittest.TestCase):
def test_repr(self):
with open(... |
<vulnerable_code> # see issue 38964
with temp_cwd() as cwd:
file_path = os.path.join(cwd, 't.py')
with open(file_path, 'w') as f:
f.write('f"{a b}"') # This generates a SyntaxError
_, _, stderr = assert_python_failure(file_path,
... |
<vulnerable_code> a.link = a
raise SystemExit(0)"""
self.addCleanup(unlink, TESTFN)
with open(TESTFN, 'w') as script:
script.write(code)
rc, out, err = assert_python_ok(TESTFN)
self.assertEqual(out.strip(), b'__del__ called')<commit_title>[PATCH 003/413... |
<vulnerable_code> def test_text_modes(self):
uncompressed = data1.decode("ascii") * 50
uncompressed_raw = uncompressed.replace("\n", os.linesep)
with gzip.open(self.filename, "wt") as f:
f.write(uncompressed)
with open(self.filename, "rb") as f:
file_data = gzi... |
<vulnerable_code>def read_vectors(hash_name):
url = URL.format(hash_name)
try:
testdata = support.open_urlresource(url)
except (OSError, HTTPException):
raise unittest.SkipTest("Could not retrieve {}".format(url))
with testdata:<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning... |
<vulnerable_code># Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array
# in PC/launcher.c must also be updated.
MAGIC_NUMBER = (3434).to_bytes(2, 'little') + b'\r\n'
_RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c
_PYCACHE = '__pycache__'<commit_title>[PATCH 003/413] bpo-... |
<vulnerable_code> ... 'continue',
... ]):
... pdb.run('print()')
> <string>(1)<module>()
(Pdb) import test.test_pdb
(Pdb) break test.test_pdb.do_something
Breakpoint 1 at ...test_pdb.py:...
... 'continue',
... ]):
... pdb.run('print()')
> <string>(1)<module>()
... |
<vulnerable_code> ndiffAssertEqual = unittest.TestCase.assertEqual
def _msgobj(self, filename):
with openfile(filename) as fp:
return email.message_from_file(fp, policy=self.policy)
def _str_msg(self, string, message=None, policy=None):<commit_title>[PATCH 003/413] bpo-43651: Fix Encodi... |
<vulnerable_code> def test_message_rfc822_only(self):
# Issue 7970: message/rfc822 not in multipart parsed by
# HeaderParser caused an exception when flattened.
with openfile('msg_46.txt') as fp:
msgdata = fp.read()
parser = HeaderParser()
msg = parser.parsestr(msg... |
<vulnerable_code> self.name_diff = os_helper.TESTFN + '-diff'
data = 'Contents of file go here.\n'
for name in [self.name, self.name_same, self.name_diff]:
with open(name, 'w') as output:
output.write(data)
with open(self.name_diff, 'a+') as output:
... |
<vulnerable_code> temp_mod_name = 'test_imp_helper'
sys.path.insert(0, '.')
try:
with open(temp_mod_name + '.py', 'w') as file:
file.write("# coding: cp1252\nu = 'test.test_imp'\n")
file, filename, info = imp.find_module(temp_mod_name)
file.clos... |
<vulnerable_code> def test_from_import_star_invalid_type(self):
import re
with _ready_to_import() as (name, path):
with open(path, 'w') as f:
f.write("__all__ = [b'invalid_type']")
globals = {}
with self.assertRaisesRegex(
exec(f"fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.