text stringlengths 79 3.72M |
|---|
<vulnerable_code> with full_name.open('wb') as f:
f.write(contents)
else:
with full_name.open('w') as f:
f.write(DALS(contents))
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixe... |
<vulnerable_code> module = loader.load_module('_temp')
module_id = id(module)
module_dict_id = id(module.__dict__)
with open(mapping['_temp'], 'w') as file:
file.write("testing_var = 42\n")
with warnings.catch_warnings():
war... |
<vulnerable_code> # The empty string from sys.path means to search in the cwd.
finder = self.machinery.FileFinder('', (self.machinery.SourceFileLoader,
self.machinery.SOURCE_SUFFIXES))
with open('mod.py', 'w') as file:
file.write("# test file for importlib")
try:
... |
<vulnerable_code> '__file__': None,
}
os.mkdir(name)
with open(bad_path, 'w') as init_file:
init_file.write('eggs = None')
module = self.init.import_module(name)
... |
<vulnerable_code>
def test_read_text(self):
files = resources.files(self.data)
actual = files.joinpath('utf-8.file').read_text()
assert actual == 'Hello, UTF-8 world!\n'
@unittest.skipUnless(<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descri... |
<vulnerable_code> metadata_dir = site_dir / 'my_pkg.dist-info'
metadata_dir.mkdir()
metadata = metadata_dir / 'METADATA'
with metadata.open('w') as strm:
strm.write('Version: 1.0\n')
return 'my-pkg'
metadata_dir = site_dir / 'CherryPy.dist-info'
metada... |
<vulnerable_code> compiled_path = cache_from_source(self.module_path)
if os.path.exists(compiled_path):
os.remove(compiled_path)
with open(self.module_path, 'w') as f:
f.write(contents)
def test_package_import__semantics(self):<commit_title>[PATCH 003/413] bpo-43651: ... |
<vulnerable_code>
def submodule(parent, name, pkg_dir, content=''):
path = os.path.join(pkg_dir, name + '.py')
with open(path, 'w') as subfile:
subfile.write(content)
return '{}.{}'.format(parent, name), path
content = ''
if content is not None:
... |
<vulnerable_code> """
if isinstance(path, tuple):
path = os.path.join(*path)
with open(path, 'wb' if binary else 'w') as fp:
fp.write(content)
def write_test_file(path, size):
"""
if isinstance(path, tuple):
path = os.path.join(*path)
with open(path, 'rb' if binary else '... |
<vulnerable_code> @requires_curses_window_meth('enclose')
def test_enclose(self):
win = curses.newwin(5, 15, 2, 5)
# TODO: Return bool instead of 1/0
self.assertTrue(win.enclose(2, 5))
self.assertFalse(win.enclose(1, 5))
self.assertFalse(win.enclose(2, 4))
self.ass... |
<vulnerable_code>
#ifdef NCURSES_MOUSE_VERSION
/*[clinic input]
_curses.window.enclose -> long
y: int
Y-coordinate.
Return True if the screen-relative coordinates are enclosed by the window.
[clinic start generated code]*/
static long
_curses_window_enclose_impl(PyCursesWindowObject *self, int y, int x)
/... |
<vulnerable_code># -*- coding: utf-8 -*-
# Autogenerated by Sphinx on Mon Mar 1 16:48:51 2021
topics = {'assert': 'The "assert" statement\n'
'**********************\n'
'\n'
'"Formatter",\n'
'subclasses can define their own format string syntax). The '
... |
<vulnerable_code>"""turtledemo.two_canvases
Use TurtleScreen and RawTurtle to draw on two
distinct canvases in a separate windows. The
new window must be separately closed in
addition to pressing the STOP button.
"""<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><... |
<vulnerable_code> continue
if f.name not in changes:
if f._field_type is _FIELD_INITVAR:
raise ValueError(f"InitVar {f.name!r} "
'must be specified with replace()')
changes[f.name] = getattr(obj, f.name)<commit_title>[PATCH 003... |
<vulnerable_code> c = replace(c, x=3, y=5)
self.assertEqual(c.x, 15)
def test_recursive_repr(self):
@dataclass
class C:<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
c = replace(c, x=3, y=5)
self.asse... |
<vulnerable_code> done = {}
notdone = {}
with open(filename, errors="surrogateescape") as f:
lines = f.readlines()
for line in lines:
# load the installed pyconfig.h:
config_h = get_config_h_filename()
try:
with open(config_h) as f:
parse_config_h(f, vars)
ex... |
<vulnerable_code> self.assertEqual(C(42).__match_args__, ('a',))
def test_explicit_match_args(self):
ma = []
@dataclass
class C:
a: int<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
self.assertEqu... |
<vulnerable_code>class MyClass:
x: int
y: str
__match_args__ = ["x", "y"]
@dataclasses.dataclass
def test_patma_200(self):
class Class:
__match_args__ = ["a", "b"]
c = Class()
c.a = 0
c.b = 1
class Parent:
__match_args__ = "a", "b"
... |
<vulnerable_code> int match_self = 0;
match_args = PyObject_GetAttrString(type, "__match_args__");
if (match_args) {
if (PyList_CheckExact(match_args)) {
Py_SETREF(match_args, PyList_AsTuple(match_args));
}
if (match_args == NULL) {
... |
<vulnerable_code> data = None
for filename in self.__filenames:
try:
with open(filename, "r") as fp:
data = fp.read()
break
except OSError:<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_... |
<vulnerable_code> self.baseFilename = os.path.abspath(filename)
self.mode = mode
self.encoding = encoding
self.errors = errors
self.delay = delay
# bpo-26789: FileHandler keeps a reference to the builtin open()
filename = kwargs.pop("filename", None)
... |
<vulnerable_code>To use, simply 'import logging.handlers' and log away!
"""
import logging, socket, os, pickle, struct, time, re
from stat import ST_DEV, ST_INO, ST_MTIME
import queue
import threading
# on each run.
if maxBytes > 0:
mode = 'a'
BaseRotatingHandler.__init__(self, file... |
<vulnerable_code> fodderModule = None
def setUp(self):
with open(inspect.getsourcefile(self.fodderModule)) as fp:
self.source = fp.read()
def sourcerange(self, top, bottom):
def setUp(self):
self.tempdir = TESTFN + '_dir'
os.mkdir(self.tempdir)
with open(os.p... |
<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 clean_up_interpreters():
... |
<vulnerable_code> self.assertEqual(t.encoding, "utf-8")
self.assertEqual(t.line_buffering, True)
self.assertEqual("\xe9\n", t.readline())
self.assertRaises(TypeError, t.__init__, b, newline=42)
self.assertRaises(ValueError, t.__init__, b, newline='xyzzy')
def test_uninitializ... |
<vulnerable_code>
# Test a file
def test_iter_file(self):
f = open(TESTFN, "w")
try:
for i in range(5):
f.write("%d\n" % i)
finally:
f.close()
f = open(TESTFN, "r")
try:
self.check_for_loop(f, ["0\n", "1\n", "2\n", "3\n"... |
<vulnerable_code> outfile = os_helper.TESTFN + '.out'
rc, out, err = assert_python_ok('-m', 'json.tool', infile, outfile)
self.addCleanup(os.remove, outfile)
with open(outfile, "r") as fp:
self.assertEqual(fp.read(), self.expect)
self.assertEqual(rc, 0)
self.as... |
<vulnerable_code> # Check module loading
for entry in MODULES:
filename = os.path.join(MODULE_PATH, entry) + '.py'
with open(filename) as file:
for index, line in enumerate(file):
self.assertEqual(line, getline(filename, index + 1))
def te... |
<vulnerable_code> # bpo-34113. The crash happened at the command line console of
# debug Python builds with __ltrace__ enabled (only possible in console),
# when the interal Python stack was negatively adjusted
with open(os_helper.TESTFN, 'w') as fd:
self.addCleanup(os_helper.... |
<vulnerable_code> os.close(fd)
if not existing:
os.unlink(fn)
h = logging.handlers.WatchedFileHandler(fn, delay=True)
if existing:
dev, ino = h.dev, h.ino
self.assertEqual(dev, -1)
if sys.p... |
<vulnerable_code> def test_text_modes(self):
uncompressed = INPUT.decode("ascii")
uncompressed_raw = uncompressed.replace("\n", os.linesep)
with lzma.open(BytesIO(COMPRESSED_XZ), "rt") as f:
self.assertEqual(f.read(), uncompressed)
with BytesIO() as bio:
with l... |
<vulnerable_code> self.assertEqual(len(self._box), 6)
with self.assertWarns(DeprecationWarning):
keys.append(self._box.add(
io.TextIOWrapper(io.BytesIO(_bytes_sample_message))))
self.assertEqual(len(self._box), 7)
self.assertEqual(self._box.get_string(keys[0]),... |
<vulnerable_code> with os_helper.temp_dir() as directory:
data = "x-application/x-unittest pyunit\n"
file = pathlib.Path(directory, "sample.mimetype")
file.write_text(data)
mime_dict = mimetypes.read_mime_types(file)
eq(mime_dict[".pyunit"], "x-applicat... |
<vulnerable_code>
def setUp(self):
# create empty file
fp = open(os_helper.TESTFN, 'w+')
fp.close()
self.teardown_files = [ os_helper.TESTFN ]
self._warnings_manager = warnings_helper.check_warnings()
self._warnings_manager.__enter__()
args = self.python_args(... |
<vulnerable_code> # Only process classes that have been processed by our
# decorator. That is, they have a _FIELDS attribute.
base_fields = getattr(b, _FIELDS, None)
if base_fields:
has_dataclass_bases = True
for f in base_fields.values():
fields[f... |
<vulnerable_code> self.assertEqual(d.i, 0)
self.assertEqual(d.j, 10)
# Test both ways: with an intermediate normal (non-dataclass)
# class and without an intermediate class.
def test_inherit_nonfrozen_from_frozen(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io ... |
<vulnerable_code># Collect data from one file
#
def process(filename, table):
with open(filename) as fp:
mod = os.path.basename(filename)
if mod[-3:] == '.py':
mod = mod[:-3]<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>... |
<vulnerable_code>def_op('DELETE_FAST', 126) # Local variable number
haslocal.append(126)
def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3)
def_op('CALL_FUNCTION', 131) # #args
def_op('MAKE_FUNCTION', 132) # Flags<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (... |
<vulnerable_code> }
assert(_PyFrame_IsRunnable(f));
if (f->f_lasti == -1) {
if (arg && arg != Py_None) {
const char *msg = "can't send non-None value to a "
"just-started generator";
if (PyCoro_CheckExact(gen)) {
msg = NON_INIT_CO... |
<vulnerable_code> goto exiting;
}
case TARGET(POP_EXCEPT): {
PyObject *type, *value, *traceback;
_PyErr_StackItem *exc_info;<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
goto exiting;
... |
<vulnerable_code> return 1;
case LIST_TO_TUPLE:
return 0;
case LIST_EXTEND:
case SET_UPDATE:
case DICT_MERGE:
}
sp = stack;
stackdepth_push(&sp, entryblock, 0);
while (sp != stack) {
b = *--sp;
int depth = b->b_startdepth;
static in... |
<vulnerable_code>## # Uncomment these lines if you want to play with xxmodule.c
## self.add(Extension('xx', ['xxmodule.c']))
# Limited C API
self.add(Extension('xxlimited', ['xxlimited.c']))
self.add(Extension('xxlimited_35', ['xxlimited_35.c']))
def detect_tkinter_fromenv(... |
<vulnerable_code> This function is deprecated in favor of importlib.util.find_spec().
"""
warnings.warn('Deprecated since Python 3.4. '
'Use importlib.util.find_spec() instead.',
DeprecationWarning, stacklevel=2)
try:
loader = sys.modules[name].__loader__<comm... |
<vulnerable_code> This method is deprecated. Use find_spec() instead.
"""
spec = cls.find_spec(fullname, path)
return spec.loader if spec is not None else None
This method is deprecated. Use find_spec() instead.
"""
return cls if _imp.is_frozen(fullname) else ... |
<vulnerable_code> This method is deprecated in favor of finder.find_spec().
"""
# Call find_loader(). If it returns a string (indicating this
# is a namespace package portion), generate a warning and
# return None.
def find_module(cls, fullname, path=None):
"""Find module named in the re... |
<vulnerable_code> Deprecated since Python 3.3
"""
@abc.abstractmethod
def find_module(self, fullname, path=None):
"""An abstract method that should find a module.
The fullname is a str and the optional path is a str or None.
Returns a Loader object or None.
"""
class Me... |
<vulnerable_code>
import sys
import unittest
@unittest.skipIf(util.BUILTINS.good_name is None, 'no reasonable builtin module')
def test_module(self):
# Common case.
with util.uncache(util.BUILTINS.good_name):
found = self.machinery.BuiltinImporter.find_module(util.BUILTINS.good_name)
... |
<vulnerable_code>@util.case_insensitive_tests
class ExtensionModuleCaseSensitivityTest(util.CASEOKTestBase):
def find_module(self):
good_name = util.EXTENSIONS.name
bad_name = good_name.upper()
assert good_name != bad_name
finder = self.machinery.FileFinder(util.EXTENSIONS.path,
... |
<vulnerable_code>
"""Test the finder for extension modules."""
def find_module(self, fullname):
importer = self.machinery.FileFinder(util.EXTENSIONS.path,
(self.machinery.ExtensionFileLoader,
self.machinery.EXTENSI... |
<vulnerable_code>machinery = util.import_importlib('importlib.machinery')
import unittest
class FindSpecTests(abc.FinderTests):
def find(self, name, path=None):
finder = self.machinery.FrozenImporter
return finder.find_module(name, path)
def test_module(self):
name = '__hello__'<com... |
<vulnerable_code> test_state_after_failure = None
def test_unloadable(self):
assert self.machinery.FrozenImporter.find_module('_not_real') is None
with self.assertRaises(ImportError) as cm:
self.exec_module('_not_real')
self.assertEqual(cm.exception.name, '_not_real')<commit_... |
<vulnerable_code> with util.import_state(path_importer_cache={}, path_hooks=[],
path=[path_entry]):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
self.assertIsNone(self.find('os'))
self.as... |
<vulnerable_code>import os
from test.support import os_helper
import unittest
@util.case_insensitive_tests
class CaseSensitivityTestPEP302(CaseSensitivityTest):
def find(self, finder):
return finder.find_module(self.name)
(Frozen_CaseSensitivityTestPEP302,<commit_title>[PATCH 003/413] bpo-43651: Fix En... |
<vulnerable_code>
class MetaPathFinder(InheritanceTests):
superclass_names = ['Finder']
subclass_names = ['BuiltinImporter', 'FrozenImporter', 'PathFinder',
'WindowsRegistryFinder']
class PathEntryFinder(InheritanceTests):
superclass_names = ['Finder']
subclass_names = ['FileFi... |
<vulnerable_code> with self.subTest(name=name):
self.assertTrue(hasattr(module, '__loader__'),
'{!r} lacks a __loader__ attribute'.format(name))
if self.machinery.BuiltinImporter.find_module(name):
self.as... |
<vulnerable_code>
Deprecated since Python 3.10. Use find_spec() instead.
"""
mi = _get_module_info(self, fullname)
if mi is not None:
# This is a module or package.
Deprecated since Python 3.10. Use find_spec() instead.
"""
return self.find_loader(ful... |
<vulnerable_code>from urllib.parse import quote_from_bytes as urlquote_from_bytes
supports_symlinks = True
if os.name == 'nt':
import nt
if sys.getwindowsversion()[:2] >= (6, 0):
from nt import _getfinalpathname
else:
supports_symlinks = False
_getfinalpathname = None
else:
nt ... |
<vulnerable_code># Assumption made in _path_join()
assert all(len(sep) == 1 for sep in path_separators)
path_sep = path_separators[0]
path_separators = ''.join(path_separators)
_pathseps_with_colon = {f':{s}' for s in path_separators}
return int.from_bytes(data, 'little')
def _path_join(*path_parts):
"""Repl... |
<vulnerable_code> m = __import__(TESTFN)
try:
self.assertEqual(m.__file__,
os.path.join(os.curdir, os.path.relpath(pyc_file)))
finally:
os.remove(pyc_file)
# Modules now also have an __cached__ that points to the pyc file.
m = ... |
<vulnerable_code>
def setUp(self):
self.name = 'spam'
self.path = 'spam.py'
self.cached = self.util.cache_from_source(self.path)
self.loader = TestLoader()
self.fileloader = TestLoader(self.path)
self.assertEqual(spec.loader, self.fileloader)
self.assertEqual(... |
<vulnerable_code>(Frozen_WindowsExtensionSuffixTests,
Source_WindowsExtensionSuffixTests
) = test_util.test_both(WindowsExtensionSuffixTests, machinery=machinery)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
(Frozen_WindowsExtensionSuffixTests,
Sou... |
<vulnerable_code> pth_dir, pth_fn = self.make_pth("abc\x00def\n")
with captured_stderr() as err_out:
self.assertFalse(site.addpackage(pth_dir, pth_fn, set()))
self.assertEqual(err_out.getvalue(), "")
for path in sys.path:
if isinstance(path, str):
"""Restor... |
<vulnerable_code>
FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
# include <windows.h>
#endif
#ifdef __VXWORKS__
return result;
}
#endif /* MS_WINDOWS */
OS__GETDISKUSAGE_METHODDEF
OS__GETFINALPATHNAME_METHODDEF
OS__GETVOLUMEPATHNAME_METHODDEF
OS_GETLOADAVG_METHODDEF... |
<vulnerable_code> def symlink(self, src, dst, target_is_directory=False):
raise NotImplementedError("os.symlink() not available on this system")
utime = os.utime
if hasattr(os, "readlink"):
readlink = os.readlink
# A stub for the opener argument to built-in open()
re... |
<vulnerable_code> return cls._flavour.parse_parts(parts)
@classmethod
def _from_parts(cls, args, init=True):
# We need to call _parse_args on the instance, so as to get the
# right flavour.
self = object.__new__(cls)
self._drv = drv
self._root = root
self.... |
<vulnerable_code># Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0)
# Python 3.10a6 3434 (PEP 634: Structural Pattern Matching)
# Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets).
# Python 3.10a7 3436 (Add GEN_START bytecode #43683)
#
# MAGIC must change whenever the b... |
<vulnerable_code> entryblock = b;
nblocks++;
}
if (!entryblock)
return 0;
stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
if (!stack) {
PyErr_NoMemory();
nblocks++;
entryblock = b;
}
if (insert_generator_prefix(c, entryblock... |
<vulnerable_code> margs = "a0"
for i in range(1, len(args)+1):
margs += ", a%d" % i
self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
reflow=False)
self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), False)
def visitProduct(self, prod,... |
<vulnerable_code>// File automatically generated by Parser/asdl_c.py.
#include <stddef.h>
#include "Python.h"
#include "pycore_ast_state.h" // struct ast_state
#include "pycore_interp.h" // _PyInterpreterState.ast
#include "pycore_pystate.h" // _PyInterpreterState_GET()
// Forward declarati... |
<vulnerable_code> return 0;
}
asdl_seq_SET(values, 0, st->v.Expr.value);
expr_ty expr = JoinedStr(values, st->lineno, st->col_offset,
st->end_lineno, st->end_col_offset, ctx_);
if (!expr) {
return 0;
}<commit_title>[PATCH 00... |
<vulnerable_code>#include "Python.h"
#include <ctype.h>
#include "pycore_ast.h" // _PyAST_Validate()
#undef Yield /* undefine macro conflicting with <winbase.h> */
#include "pycore_compile.h" // _PyAST_Compile()
#include "pycore_object.h" // _Py_AddToAllObjects()
#include "pycore_pyerrors.h" ... |
<vulnerable_code>
#include "Python.h"
#undef Yield /* undefine macro conflicting with <winbase.h> */
#include "pycore_import.h" // _PyImport_BootstrapImp()
#include "pycore_initconfig.h"
#include "pycore_pyerrors.h"<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descr... |
<vulnerable_code>#include "Python.h"
#include "pycore_ast.h" // PyAST_mod2obj
#undef Yield /* undefine macro conflicting with <winbase.h> */
#include "pycore_compile.h" // _PyAST_Compile()
#include "pycore_interp.h" // PyInterpreterState.importlib
#include "pycore_object.h" // _PyDebug... |
<vulnerable_code>#include "Python.h"
#include "pycore_ast.h" // identifier, stmt_ty
#undef Yield /* undefine macro conflicting with <winbase.h> */
#include "pycore_compile.h" // _Py_Mangle()
#include "pycore_parser.h" // _PyParser_ASTFromString()
#include "pycore_pystate.h" // _PyThreadSt... |
<vulnerable_code> # (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t]+)' # scheme like "Basic"
'[ \t]+' # mandatory whitespaces
... |
<vulnerable_code> "python-{}-webinstall.exe".format(m.group(0)),
"python-{}-amd64.exe".format(m.group(0)),
"python-{}-amd64-webinstall.exe".format(m.group(0)),
] + ["win32{}/{}".format(REL, f) for f in FILES] + ["amd64{}/{}".format(REL, f) for f in FILES]
print('Purged:')
for n in PATHS:<commit_title>[PATCH... |
<vulnerable_code>*/
enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
struct fblockinfo {
enum fblocktype fb_type;
switch (info->fb_type) {
case WHILE_LOOP:
case EXCEPTION_HANDLER:
... |
<vulnerable_code>
stat = os.stat
lstat = os.lstat
open = os.open
listdir = os.listdir
chmod = os.chmod
if hasattr(os, "lchmod"):
lchmod = os.lchmod
else:
def lchmod(self, path, mode):
raise NotImplementedError("os.lchmod() not available on this system")
... |
<vulnerable_code> p.chmod(new_mode)
self.assertEqual(p.stat().st_mode, new_mode)
# XXX also need a test for lchmod.
def test_stat(self):
self.addCleanup(p.chmod, st.st_mode)
self.assertNotEqual(p.stat(), st)
@os_helper.skip_unless_symlink
def test_lstat(self):
p... |
<vulnerable_code> """
return self.stat(follow_symlinks=False)
def link_to(self, target):
"""
Create a hard link pointing to a path named target.
"""
self._accessor.link(self, target)
def rename(self, target):
"""
Rename this path to the target pat... |
<vulnerable_code> def resolve(self, path, strict=False):
s = str(path)
if not s:
return os.getcwd()
previous_s = None
if _getfinalpathname is not None:
if strict:
return path
# NOTE: according to POSIX, getcwd() cannot contain path component... |
<vulnerable_code>
def test_c_parser(self) -> None:
grammar_source = """
start[mod_ty]: a[asdl_stmt_seq*]=stmt* $ { Module(a, NULL, p->arena) }
stmt[stmt_ty]: a=expr_stmt { a }
expr_stmt[stmt_ty]: a=expression NEWLINE { _Py_Expr(a, EXTRA) }
expression[expr_ty]: ( l=expression ... |
<vulnerable_code> self.emit("", depth)
class PrototypeVisitor(EmitVisitor):
"""Generate function prototypes for the .h file"""
argstr += ", PyArena *arena"
else:
argstr = "PyArena *arena"
margs = "a0"
for i in range(1, len(args)+1):
margs += ", a... |
<vulnerable_code> )
{
D(fprintf(stderr, "%*c+ interactive[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "statement_newline"));
_res = Interactive ( a , p -> arena );
if (_res == NULL && PyErr_Occurred()) {
p->error_indicator = 1;
... |
<vulnerable_code> if (tco == NULL) {
return NULL;
}
return arg(a->arg, a->annotation, tco,
a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
p->arena);
}
static int
if (!id) {
return NULL;
}
cache = Name(id, Load, 1, 0, 1, 0, p->arena);
... |
<vulnerable_code> /* And now create the FormattedValue node that represents this
entire expression with the conversion and format spec. */
//TODO: Fix this
*expression = FormattedValue(simple_expression, conversion,
format_spec, first_token->lineno,
... |
<vulnerable_code> type_ignore_ty* out, PyArena* arena);
mod_ty
_Py_Module(asdl_stmt_seq * body, asdl_type_ignore_seq * type_ignores, PyArena
*arena)
{
mod_ty p;
p = (mod_ty)_PyArena_Malloc(arena, sizeof(*p));
}
mod_ty
_Py_Interactive(asdl_stmt_seq * body, PyArena *aren... |
<vulnerable_code> return 0;
}
asdl_seq_SET(values, 0, st->v.Expr.value);
expr_ty expr = _Py_JoinedStr(values, st->lineno, st->col_offset,
st->end_lineno, st->end_col_offset, ctx_);
if (!expr) {
return 0;
}<commit_title>[... |
<vulnerable_code> // memory cannot be allocated on the heap in a signal handler.
// Iterate on the dict instead.
PyObject *stdlib_module_names = NULL;
pos = 0;
while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
if (PyUnicode_Check(key)
&& PyUnicode_CompareWithASCIIString(ke... |
<vulnerable_code> return status;
}
#define INIT_TYPE(TYPE, NAME) \
do { \
if (PyType_Ready(TYPE) < 0) { \
return _PyStatus_ERR("Can't initialize " NAME " type"); \
} \
} while (0)
INIT_TYPE(&PyBaseObject_Type, "object");
INIT_TYPE(&PyType_Type, "type");
INIT_... |
<vulnerable_code>#include "pycore_pylifecycle.h"
#include "pycore_pymem.h" // _PyMem_IsPtrFreed()
#include "pycore_pystate.h" // _PyThreadState_GET()
#include "frameobject.h"
#include "interpreteridobject.h"
assert(PyType_Type.tp_base == &PyBaseObject_Type);
// All other static types
INIT_TY... |
<vulnerable_code> drive = ''
userhome = join(drive, os.environ['HOMEPATH'])
if isinstance(path, bytes):
userhome = os.fsencode(userhome)
if i != 1: #~user
userhome = join(dirname(userhome), path[1:i])
return userhome + path[i:]
<commit_title>[PATCH 003/413] bpo-43651: ... |
<vulnerable_code> # It's a path on a network drive => 'file://host/share/a/b'
return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8'))
def gethomedir(self, username):
if 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH'... |
<vulnerable_code> env.clear()
tester('ntpath.expanduser("~test")', '~test')
env['HOMEPATH'] = 'eric\\idle'
env['HOMEDRIVE'] = 'C:\\'
tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
tester('ntpath.expanduser("~")', 'C:\\eric\\idle')
... |
<vulnerable_code> env.pop('USERNAME', None)
self.assertEqual(p1.expanduser(),
P('C:/Users/alice/My Documents'))
self.assertRaises(KeyError, p2.expanduser)
env['USERNAME'] = 'alice'
self.assertEqual(p2.expandu... |
<vulnerable_code> return result
def __repr__(self):
return "MySet(%s)" % repr(list(self))
s = MySet([5,43,2,1])
self.assertEqual(s.pop(), 1)
def test_issue8750(self):
empty = WithSet()<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in ... |
<vulnerable_code> 0, /* am_send */
};
PyTypeObject PyAnextAwaitable_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"anext_awaitable", /* tp_name */
sizeof(anextawaitableobject), /* tp_basicsize */
PyAnextAwaitable_New(PyOb... |
<vulnerable_code> INIT_TYPE(PyUnicode_Type);
INIT_TYPE(PyWrapperDescr_Type);
INIT_TYPE(Py_GenericAliasType);
INIT_TYPE(_PyAsyncGenASend_Type);
INIT_TYPE(_PyAsyncGenAThrow_Type);
INIT_TYPE(_PyAsyncGenWrappedValue_Type);<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-250... |
<vulnerable_code> -fno-crossjumping).
*/
#ifdef DYNAMIC_EXECUTION_PROFILE
#undef USE_COMPUTED_GOTOS
#define USE_COMPUTED_GOTOS 0
#endif
#if USE_COMPUTED_GOTOS
#define TARGET(op) \
op: \
TARGET_##op
#ifdef LLTRACE
#define DISPATCH() \
{ \
if (!lltrace && !_Py_TracingPossible(ceval2) && !PyDTrace... |
<vulnerable_code> str(inspect.signature(cls)).replace(' -> NoneType', ''))
if '__match_args__' not in cls.__dict__:
cls.__match_args__ = tuple(f.name for f in flds if f.init)
abc.update_abstractmethods(cls)
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.