text stringlengths 79 3.72M |
|---|
<vulnerable_code> def test_ignores_newline_at_end(self):
with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
zipfp.write(TESTFN, TESTFN)
with open(TESTFN2, 'a') as f:
f.write("\r\n\00\00\00")
with zipfile.ZipFile(TESTFN2, "r") as zipfp:
self.as... |
<vulnerable_code> if args or kwargs:
raise ValueError("encoding args invalid for binary operation")
return stream
return io.TextIOWrapper(stream, *args, **kwargs)
@property
return pathlib.Path(self.root.filename).joinpath(self.at)
def read_text(self, *arg... |
<vulnerable_code>
# We can not use io.text_encoding() here because old openhook doesn't
# take encoding parameter.
if "b" not in mode and encoding is None and sys.flags.warn_default_encoding:
import warnings
warnings.warn("'encoding' argument not specified.",
... |
<vulnerable_code> def writeTmp(self, content, *, mode='w'): # opening in text mode is the default
fd, name = tempfile.mkstemp()
self.addCleanup(os_helper.unlink, name)
with open(fd, mode) as f:
f.write(content)
return name
if verbose:
print('1. Simpl... |
<vulnerable_code>#include "zlib.h"
#define ENTER_ZLIB(obj) \
Py_BEGIN_ALLOW_THREADS; \
PyThread_acquire_lock((obj)->lock, 1); \
Py_END_ALLOW_THREADS;
#define LEAVE_ZLIB(obj) PyThread_release_lock((obj)->lock);
#if defined(ZLIB_VERNUM) && ZLIB_VERNUM >= 0x1221
PyObject *RetVal = NULL;
Py_ssize_t o... |
<vulnerable_code>
if sys.platform == "darwin" and sys._framework:
return joinuser("~", "Library", sys._framework,
"%d.%d" % sys.version_info[:2])
return joinuser("~", ".local")
'scripts', 'data')
_PY_VERSION = sys.version.split()[0]
_PY_VERSION_SHORT = '%d.%d' ... |
<vulnerable_code>import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars,
get_path, get_path_names, _INSTALL_SCHEMES,
_get_default_scheme, _expand_vars,
get_scheme_names, get_config_var, _main)
import _osx_support
def t... |
<vulnerable_code>from typing import Annotated, ForwardRef
from typing import TypeAlias
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
import abc
import typing
import weakref
self.assertEqual(C4.__parameters__, (T, P))
class AllTests(BaseTestCase):
"""Tests for __all__."""
<commi... |
<vulnerable_code> 'Text',
'TYPE_CHECKING',
'TypeAlias',
]
# The pseudo-submodules 're' and 'io' are part of the public
return _ConcatenateGenericAlias(self, parameters)
class ForwardRef(_Final, _root=True):
"""Internal wrapper to hold a forward reference."""
<commit_title>[PATCH 003/413] bpo-43651... |
<vulnerable_code>
def test_module_found(self):
with setup_module(self.machinery, self.test_module):
loader = self.machinery.WindowsRegistryFinder.find_module(self.test_module)
spec = self.machinery.WindowsRegistryFinder.find_spec(self.test_module)
self.assertIsNot(loader,... |
<vulnerable_code> ),
),
dict(
name="SQLite 3.34.0",
url="https://sqlite.org/2020/sqlite-autoconf-3340000.tar.gz",
checksum='7f33c9db7b713957fcb9271fe9049fef',
extra_cflags=('-Os '
'-DSQLITE_ENABLE_FT... |
<vulnerable_code> # installer file name. With the introduction of weaklinked installer
# variants, we may have two variants with the same file name, i.e.
# both ending in '10.9'. To avoid this, we now use the major/minor
# version numbers of the macOS version we are building on, i.e.
# '10.9' as bef... |
<vulnerable_code> # Find out which *open() is appropriate for opening the file.
def not_compressed(comptype):
return cls.OPEN_METH[comptype] == 'taropen'
for comptype in sorted(cls.OPEN_METH, key=not_compressed):
func = getattr(cls, cls.OPEN_METH[compty... |
<vulnerable_code> 'SubsequentHeaderError', 'ExFileObject', 'main'}
support.check__all__(self, tarfile, not_exported=not_exported)
class CommandLineTest(unittest.TestCase):
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
... |
<vulnerable_code> # linear.
enum_class._value2member_map_.setdefault(value, enum_member)
except TypeError:
pass
class _EnumDict(dict):
classdict['_member_names_'] = []
classdict['_member_map_'] = {}
classdict['_value2member_map_'] = {}
classdi... |
<vulnerable_code>from test.support import threading_helper
from datetime import timedelta
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(enum))
if os.path.exists('Doc/library/enum.rst'):
self.assertTrue(IntLogic.true)
self.assertFalse(IntLogic.false)
def test_co... |
<vulnerable_code> # race condition, check it.
self.assertIsInstance(cm.unraisable.exc_value, OSError)
self.assertIn(
f"Signal {signum} ignored due to race condition",
str(cm.unraisable.exc_value))
... |
<vulnerable_code>
static int
signal_module_exec(PyObject *m)
{
assert(!PyErr_Occurred());
if (signal_add_constants(m) < 0) {
return -1;
}
/* Add some symbolic constants to the module */
PyObject *d = PyModule_GetDict(m);
if (PyDict_SetItemString(d, "SIG_DFL", DefaultHandler) < 0) {
... |
<vulnerable_code>/* XXX Signals should be recorded per thread, now we have thread state. */
#include "Python.h"
#include "pycore_atomic.h"
#include "pycore_call.h"
#include "pycore_ceval.h"
#include "pycore_pyerrors.h"
#include "pycore_pylifecycle.h"
#include "pycore_pystate.h" // _PyThreadState_GET()
#ifndef MS_W... |
<vulnerable_code>"""Internal classes used by the gzip, lzma and bz2 modules"""
import io
BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE # Compressed data read chunk size
self._pos += len(data)
return data
# Rewind the file to the beginning of the data stream.
def _rewind(self):
self._fp.seek... |
<vulnerable_code>#include <bzlib.h>
#include <stdio.h>
#ifndef BZ_CONFIG_ERROR
#define BZ2_bzCompress bzCompress
}
}
#if BUFSIZ < 8192
#define INITIAL_BUFFER_SIZE 8192
#else
#define INITIAL_BUFFER_SIZE BUFSIZ
#endif
static int
grow_buffer(PyObject **buf, Py_ssize_t max_length)
{
/* Expand the buffer by an a... |
<vulnerable_code>
#include <lzma.h>
#define ACQUIRE_LOCK(obj) do { \
if (!PyThread_acquire_lock((obj)->lock, 0)) { \
Py_BEGIN_ALLOW_THREADS \
PyMem_RawFree(ptr);
}
#if BUFSIZ < 8192
#define INITIAL_BUFFER_SIZE 8192
#else
#define INITIAL_BUFFER_SIZE BUFSIZ
#endif
static int
grow_buffer(PyObject **buf,... |
<vulnerable_code>#include "structmember.h" // PyMemberDef
#include "zlib.h"
#define ENTER_ZLIB(obj) do { \
if (!PyThread_acquire_lock((obj)->lock, 0)) { \
*remains -= zst->avail_in;
}
static Py_ssize_t
arrange_output_buffer_with_maximum(z_stream *zst, PyObject **buffer,
... |
<vulnerable_code> def __repr__(self):
obj_repr = (
f"<{self.__class__.__name__}: "
f"returncode: {self.returncode} args: {list(self.args)!r}>"
)
if len(obj_repr) > 80:
obj_repr = obj_repr[:76] + "...>"<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWar... |
<vulnerable_code>import gc
import textwrap
import json
from test.support.os_helper import FakePath
try:
p.communicate(b"x" * 2**20)
def test_repr(self):
# Run a command that waits for user input, to check the repr() of
# a Proc object while and after the sub-process runs.
code = 'i... |
<vulnerable_code> ... print('value', i)
... x = 123
>>> with PdbTestInput(['break test_gen',
... 'continue',
... 'next',<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
... ... |
<vulnerable_code> }
}
interpid *self = PyObject_New(interpid, cls);
if (self == NULL) {
return NULL;
}
self->id = id;
if (interp != NULL) {
_PyInterpreterState_IDIncref(interp);
}
return self;
}
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test... |
<vulnerable_code>}
void
_PyInterpreterState_IDIncref(PyInterpreterState *interp)
{
if (interp->id_mutex == NULL) {
return;
}
PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
interp->id_refcount += 1;
PyThread_release_lock(interp->id_mutex);
}
void
_PyInterpreterState_IDDecref(PyInterp... |
<vulnerable_code>
def rotator(self, source, dest):
if os.path.exists(source):
os.rename(source, dest + ".rotated")
rh = HandlerWithNamerAndRotator(
self.fn, encoding="utf-8", backupCount=2, maxBytes=1)<commit_title>[PATCH 003/413] bpo-43651: Fix Encod... |
<vulnerable_code>from test.support import warnings_helper
with warnings_helper.check_warnings(
("The distutils package is deprecated", DeprecationWarning)):
import distutils.tests
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
from test.suppo... |
<vulnerable_code> ga_args = args
return super().__new__(cls, origin, ga_args)
def __repr__(self):
if _has_special_args(self.__args__):
return super().__repr__()
def __getitem__(self, item):
# Called during TypeVar substitution, returns the custom subclass
... |
<vulnerable_code> self.assertEqual(repr(C4[dict]).split(".")[-1], "Callable[[int, dict], str]")
self.assertEqual(C4[dict], Callable[[int, dict], str])
with self.subTest("Testing type erasure"):
class C1(Callable):
def __call__(self):
self.assertEqu... |
<vulnerable_code> return NULL;
}
/* Checks if a variable number of names are from typing.py.
* If any one of the names are found, return 1, else 0.
**/
static inline int
is_typing_name(PyObject *obj, int num, ...)
{
va_list names;
va_start(names, num);
PyTypeObject *type = Py_TYPE(obj);
int hit = ... |
<vulnerable_code> tail = join(name, tail) if tail else name
return tail
def realpath(path):
path = normpath(path)
if isinstance(path, bytes):
prefix = b'\\\\?\\'
path = _getfinalpathname(path)
initial_winerror = 0
except OSError as ... |
<vulnerable_code>from urllib.parse import quote_from_bytes as urlquote_from_bytes
if os.name == 'nt':
from nt import _getfinalpathname
else:
_getfinalpathname = None
__all__ = [
"PurePath", "PurePosixPath", "PureWindowsPath",
"Path", "PosixPath", "WindowsPath",
# Internals
#
# EBADF - guard against... |
<vulnerable_code># Return a canonical path (i.e. the absolute location of a file on the
# filesystem).
def realpath(filename):
"""Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path."""
filename = os.fspath(filename)
path, ok = _joinrealpath(filename[... |
<vulnerable_code> self.assertPathEqual(ntpath.realpath(os.fsencode(ABSTFN + "1")),
os.fsencode(ABSTFN))
@os_helper.skip_unless_symlink
@unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
def test_realpath_relative(self):
@os_helper.skip_unless_symlink
... |
<vulnerable_code> finally:
os_helper.unlink(ABSTFN)
@unittest.skipUnless(hasattr(os, "symlink"),
"Missing symlink implementation")
@skip_if_ABSTFN_contains_backslash
@skip_if_ABSTFN_contains_backslash
def test_realpath_symlink_loops(self):
# Bug #9300... |
<vulnerable_code>#endif
}
static PyObject*
test_list_api(PyObject *self, PyObject *Py_UNUSED(ignored))
{"PyDateTime_DATE_GET", test_PyDateTime_DATE_GET, METH_O},
{"PyDateTime_TIME_GET", test_PyDateTime_TIME_GET, METH_O},
{"PyDateTime_DELTA_GET", test_PyDateTime_DELTA_GET, ... |
<vulnerable_code>gc_enable_impl(PyObject *module)
/*[clinic end generated code: output=45a427e9dce9155c input=81ac4940ca579707]*/
{
GCState *gcstate = get_gc_state();
gcstate->enabled = 1;
Py_RETURN_NONE;
}
gc_disable_impl(PyObject *module)
/*[clinic end generated code: output=97d1030f7aa9d279 input=8c2e5a... |
<vulnerable_code>type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
int res;
if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
PyErr_Format(
PyExc_TypeError,
"can't set attributes of built-in/extension type '%s'",
type->tp_flags |= Py_TPFLAGS_READYING;
if... |
<vulnerable_code> def test_preexec_gc_module_failure(self):
# This tests the code that disables garbage collection if the child
# process will execute any Python.
def raise_runtime_error():
raise RuntimeError("this shouldn't escape")
enabled = gc.isenabled()
orig_g... |
<vulnerable_code>
#define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0)
typedef struct {
PyObject* disable;
PyObject* enable;
PyObject* isenabled;
} _posixsubprocessstate;
static struct PyModuleDef _posixsubprocessmodule;
static inline _posixsubprocessstate*
get_posixsubprocess_state(... |
<vulnerable_code> # non-modal alternative.
"hit": idleConf.GetHighlight(theme, "hit"),
}
if DEBUG: print('tagdefs', self.tagdefs)
def insert(self, index, chars, tags=None):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descripti... |
<vulnerable_code> from idlelib.sidebar import LineNumbers
from idlelib.format import FormatParagraph, FormatRegion, Indents, Rstrip
from idlelib.parenmatch import ParenMatch
from idlelib.squeezer import Squeezer
from idlelib.zoomheight import ZoomHeight
filesystemencoding = sys.getfilesystemenco... |
<vulnerable_code> else:
if self.text.get("iomark", "end-1c") != prefix:
self.text.delete("iomark", "end-1c")
self.text.insert("iomark", prefix)
pointer = prefix = None
break
item = self.his... |
<vulnerable_code> '2.end'),
)
w.prompt_last_line = ''
for test in tests:
with self.subTest(label=test.label):
insert(text, test.text)
# Deletes selected text before adding new line.
eq(get('1.0', 'end'), ' def f1(sel... |
<vulnerable_code>## self.assertIsInstance(ps, pyshell.PyShell)
if __name__ == '__main__':
unittest.main(verbosity=2)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
## self.assertIsInstance(ps, pyshell.PyShell)
class PyShellRemoveLa... |
<vulnerable_code>"""Test sidebar, coverage 93%"""
import idlelib.sidebar
from itertools import chain
import unittest
import unittest.mock
from test.support import requires
import tkinter as tk
from idlelib.delegator import Delegator
from idlelib.percolator import Percolator
class Dummy_editwin:
def setUpClass(cl... |
<vulnerable_code>from test.support import requires
from idlelib.config import idleConf
from idlelib.squeezer import count_lines_with_wrapping, ExpandingButton, \
Squeezer
from idlelib import macosx
from idlelib.textview import view_text
from idlelib.tooltip import Hovertip
from idlelib.pyshell import PyShell
SEN... |
<vulnerable_code><commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
"""Utilities for testing with Tkinter"""
import functools
def run_in_tk_mainloop(test_method):
"""Decorator for running a test method with a real Tk mainloop.
This starts a Tk m... |
<vulnerable_code> filter.setdelegate(self.top)
self.top = filter
def removefilter(self, filter):
# XXX Perhaps should only support popfilter()?
assert isinstance(filter, Delegator)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><f... |
<vulnerable_code>
from idlelib.colorizer import ColorDelegator
from idlelib.config import idleConf
from idlelib import debugger
from idlelib import debugger_r
from idlelib.editor import EditorWindow, fixwordbreaks
from idlelib.filelist import FileList
from idlelib.outwin import OutputWindow
from idlelib import rpc
from... |
<vulnerable_code>from idlelib import searchengine
def replace(text):
"""Create or reuse a singleton ReplaceDialog instance.
The singleton dialog saves user entries and preferences
if not hasattr(engine, "_replacedialog"):
engine._replacedialog = ReplaceDialog(root, engine)
dialog = engine._re... |
<vulnerable_code>"""Line numbering implementation for IDLE as an extension.
Includes BaseSideBar which can be extended for other sidebar based extensions
"""
import functools
import itertools
import tkinter as tk
from idlelib.config import idleConf
from idlelib.delegator import Delegator
def get_end_linenumber(text)... |
<vulnerable_code> if not confirm:
return "break"
self.base_text.insert(self.text.index(self), self.s, self.tags)
self.base_text.delete(self)
self.squeezer.expandingbuttons.remove(self)
def copy(self, event=None):
"""
return count_lines_with_wrappi... |
<vulnerable_code> """Return a new path pointing to the current working directory
(as returned by os.getcwd()).
"""
return cls(cls()._accessor.getcwd())
@classmethod
def home(cls):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description... |
<vulnerable_code> gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
class CAPITest(unittest.TestCase):
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
def te... |
<vulnerable_code> unicodes is to override __eq__, and for speed we don't cater to
that here. */
if (!PyUnicode_CheckExact(key)) {
mp->ma_keys->dk_lookup = lookdict;
return lookdict(mp, key, hash, value_addr);
}
unicodes is to override __eq__, and for speed we don't cater to
... |
<vulnerable_code>
def test_text_file_body(self):
self.addCleanup(os_helper.unlink, os_helper.TESTFN)
with open(os_helper.TESTFN, "w") as f:
f.write("body")
with open(os_helper.TESTFN) as f:
self.conn.request("PUT", "/url", f)
message, f = self.get_headers_... |
<vulnerable_code> fullpath = os.path.join(self.tempdir, filename)
try:
open(fullpath, 'w').close()
except OSError:
raise unittest.SkipTest('Can not create file %s on current file '
'system' % filename)
self.skipTest("Python ... |
<vulnerable_code> class=FileHandler
level=DEBUG
args=("{tempfile}",)
"""
disable_test = """
def apply_config(self, conf, **kwargs):
file = io.StringIO(textwrap.dedent(conf))
logging.config.fileConfig(file, **kwargs)
def test_config0_ok(self):
# A simple config file ... |
<vulnerable_code> import subprocess, io
if mode == "r":
proc = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
bufsize=buffering)
return _wrap_close(io.TextIOWrapp... |
<vulnerable_code>
def fdopen_helper(self, *args):
fd = os.open(os_helper.TESTFN, os.O_RDONLY)
f = os.fdopen(fd, *args)
f.close()
def test_fdopen(self):
os.replace(os_helper.TESTFN, TESTFN2)
self.assertRaises(FileNotFoundError, os.stat, os_helper.TESTFN)
with ope... |
<vulnerable_code>import html
import locale
import tempfile
__all__ = ["MiniFieldStorage", "FieldStorage", "parse", "parse_multipart",
"parse_header", "test", "print_exception", "print_environ",
"""
global log, logfile, logfp
if logfile and not logfp:
try:
logfp = open(logfil... |
<vulnerable_code>from collections import namedtuple
from io import StringIO, BytesIO
from test import support
class HackedSysModule:
# The regression test will have real values in sys.argv, which
else:
self.assertEqual(fs.getvalue(key), expect_val[0])
def test_log(s... |
<vulnerable_code> else:
super().visit(node)
def visit(self, node):
"""Outputs a source code string that, if converted back to an ast
(using ast.parse) will generate an AST equivalent to *node*"""
with self.block():
self.traverse(node.body)
def visit_Match... |
<vulnerable_code> self.assertIs(y, None)
self.assertIs(z, None)
class PerfPatma(TestPatma):
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
self.assertIs(y, None)
self.assertIs(z, None)
@no_perf
def test_patma_2... |
<vulnerable_code> lib_dir = pathlib.Path(__file__).parent / ".."
test_directories = (lib_dir, lib_dir / "test")
run_always_files = {"test_grammar.py", "test_syntax.py", "test_compile.py",
"test_ast.py", "test_asdl_parser.py", "test_fstring.py"}
_files_to_test = None
<commit_title... |
<vulnerable_code>#define or_pattern_type 1045
#define closed_pattern_type 1046
#define literal_pattern_type 1047
#define signed_number_type 1048
#define capture_pattern_type 1049
#define wildcard_pattern_type 1050
#define value_pattern_type 1051
#define attr_type 1052 // Left-recursive
#define name_or_attr_type 1053 ... |
<vulnerable_code>#include <Python.h>
#include "pycore_ast.h" // _PyAST_Validate()
#include <errcode.h>
#include "tokenizer.h"
return new_seq;
}
/* Constructs a NameDefaultPair */
NameDefaultPair *
_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
return NULL;
}
mod_ty
_PyP... |
<vulnerable_code> Py_CLEAR(state->MatMult_singleton);
Py_CLEAR(state->MatMult_type);
Py_CLEAR(state->MatchAs_type);
Py_CLEAR(state->MatchOr_type);
Py_CLEAR(state->Match_type);
Py_CLEAR(state->Mod_singleton);
Py_CLEAR(state->Mod_type);
Py_CLEAR(state->boolop_type);
Py_CLEAR(state->case... |
<vulnerable_code>#include "pycore_pystate.h" // _PyThreadState_GET()
#include <assert.h>
struct validator {
int recursion_depth; /* current recursion depth */
static int _validate_nonempty_seq(asdl_seq *, const char *, const char *);
static int validate_stmt(struct validator *, stmt_ty);
static i... |
<vulnerable_code>static int astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
static int astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
static int astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTOptimizeState *state);
static int astfo... |
<vulnerable_code>#include <float.h> // DBL_MAX_10_EXP
#include <stdbool.h>
static PyObject *_str_open_br;
static PyObject *_str_dbl_open_br;
static PyObject *_str_close_br;
return append_ast_tuple(writer, e, level);
case NamedExpr_kind:
return append_named_expr(writer, e, level);
... |
<vulnerable_code> if (arena == NULL)
goto error;
mod = PyAST_obj2mod(source, arena, compile_mode);
if (mod == NULL) {
_PyArena_Free(arena);
goto error;
}
if (!_PyAST_Validate(mod)) {
_PyArena_Free(... |
<vulnerable_code> int depth,
expr_ty elt, expr_ty val, int type);
static int compiler_pattern(struct compiler *, expr_ty, pattern_context *);
static int compiler_match(struct compiler *, stmt_ty);
static int compiler_pattern_subpattern(struct c... |
<vulnerable_code>static int symtable_visit_annotations(struct symtable *st, arguments_ty, expr_ty);
static int symtable_visit_withitem(struct symtable *st, withitem_ty item);
static int symtable_visit_match_case(struct symtable *st, match_case_ty m);
static identifier top = NULL, lambda = NULL, genexpr = NULL,
... |
<vulnerable_code> Test implementation details of the re module.
"""
def test_overlap_table(self):
f = sre_compile._generate_overlap_table
self.assertEqual(f(""), [])<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
Test imp... |
<vulnerable_code> .name = "re.Pattern",
.basicsize = sizeof(PatternObject),
.itemsize = sizeof(SRE_CODE),
.flags = Py_TPFLAGS_DEFAULT,
.slots = pattern_slots,
};
.name = "re.Match",
.basicsize = sizeof(MatchObject),
.itemsize = sizeof(Py_ssize_t),
.flags = Py_TPFLAGS_DEFAULT,
.sl... |
<vulnerable_code> self.assertRaises(TypeError, array.array, 'xx')
self.assertRaises(ValueError, array.array, 'x')
def test_empty(self):
# Exercise code for handling zero-length arrays
a = array.array('B')<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-2509... |
<vulnerable_code>static PyType_Spec array_spec = {
.name = "array.array",
.basicsize = sizeof(arrayobject),
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.slots = array_slots,
};
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
stati... |
<vulnerable_code> # This tests the code that disables garbage collection if the child
# process will execute any Python.
enabled = gc.isenabled()
orig_gc_disable = gc.disable
orig_gc_isenabled = gc.isenabled
try:
gc.disable()
self.assertFalse(gc.ise... |
<vulnerable_code>/* Re-export stable Python API */
#ifdef _M_IX86
#define DECORATE "_"
EXPORT_FUNC(Py_AddPendingCall)
EXPORT_FUNC(Py_AtExit)
EXPORT_FUNC(Py_BuildValue)
EXPORT_FUNC(Py_CompileString)
EXPORT_FUNC(Py_DecodeLocale)
EXPORT_FUNC(Py_DecRef)
EXPORT_FUNC(Py_IncRef)
EXPORT_FUNC(Py_Initialize)
EXPORT_FUNC(Py_Init... |
<vulnerable_code>#!/usr/bin/env python
import argparse
import glob
import os.path
import pathlib
import re
import subprocess
import sys
import sysconfig
EXCLUDED_HEADERS = {
"bytes_methods.h",
"token.h",
"ucnhash.h",
}
MACOS = (sys.platform == "darwin")
def get_exported_symbols(library, dynamic=False):
... |
<vulnerable_code>
OutputWindow.__init__(self, flist, None, None)
self.usetabs = True
# indentwidth must be 8 when using tabs. See note in EditorWindow:
self.indentwidth = 8
self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>> '
self.prompt_last_line = self.sys_ps1.s... |
<vulnerable_code> h1.close()
os.remove(fn)
#with self.check_no_resource_warning():
if 1:
fd, fn = tempfile.mkstemp(".log", "test_logging-X-")
os.close(fd)
<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description... |
<vulnerable_code> continue
items.append((entry.name.decode("ascii"), entry.size))
expected = [("__hello__", 139),
("__phello__", -139),
("__phello__.spam", 139),
]
self.assertEqual(items, expected, "PyImport_FrozenMo... |
<vulnerable_code># Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets).
# Python 3.10b1 3436 (Add GEN_START bytecode #43683)
# Python 3.10b1 3437 (Undo making 'annotations' future by default - We like to dance among core devs!)
#
# MAGIC must change whenever the bytecode emitted by the ... |
<vulnerable_code> new_code = code.replace(**{attr: value})
self.assertEqual(getattr(new_code, attr), value)
def isinterned(s):
return s is sys.intern(('_' + s + '_')[1:-1])<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_co... |
<vulnerable_code>
# Set line number for 'pass' to None
bug42562.__code__ = bug42562.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
dis_bug42562 = """\<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
# Set line number for 'pass' to None
bug42562.... |
<vulnerable_code> }
_PyCode_InitAddressRange(code, &bounds);
while (PyLineTable_NextAddressRange(&bounds)) {
if (bounds.ar_computed_line != line) {
int bdelta = bounds.ar_start - code_offset;
int ldelta = bounds.ar_computed_line - line;
if (!emit_delta(&bytes, bdel... |
<vulnerable_code> if (!assemble_line_range(&a)) {
return 0;
}
/* Emit sentinel at end of line number table */
if (!assemble_emit_linetable_pair(&a, 255, -128)) {
goto error;
}
if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) {
goto error;<commit_title>[PATCH 003/413]... |
<vulnerable_code>EXPORT_FUNC(PyFrame_GetLineNumber)
EXPORT_FUNC(PyFrozenSet_New)
EXPORT_FUNC(PyGC_Collect)
EXPORT_FUNC(PyGILState_Ensure)
EXPORT_FUNC(PyGILState_GetThisThreadState)
EXPORT_FUNC(PyGILState_Release)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed... |
<vulnerable_code> with self.assertRaisesRegex(ValueError, "out of range"):
p.port
def test_attributes_bad_port(self):
"""Check handling of invalid ports."""
for bytes in (False, True):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descri... |
<vulnerable_code> '0123456789'
'+-.')
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {}
else:
scheme, url = url[:i].lower(), url[i+1:]
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc... |
<vulnerable_code> while t.tb_next:
t = t.tb_next
frame = t.tb_frame
self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, line)
def test_lineno_after_raise_simple(self):
def simple():
pass
self.lineno_after_raise(after_with, ... |
<vulnerable_code>static PyObject *
frame_getlineno(PyFrameObject *f, void *closure)
{
return PyLong_FromLong(PyFrame_GetLineNumber(f));
}
static PyObject *<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>
static PyObject *
frame_getlineno(PyFrameObje... |
<vulnerable_code> if (descr_check((PyDescrObject *)descr, obj, &res))
return res;
if (descr->d_member->flags & READ_RESTRICTED) {
if (PySys_Audit("object.__getattr__", "Os",
obj ? obj : Py_None, descr->d_member->name) < 0) {
return NULL;<commit_title>[PATCH 003/413] bpo-4... |
<vulnerable_code>
static PyMemberDef frame_memberlist[] = {
{"f_back", T_OBJECT, OFF(f_back), READONLY},
{"f_code", T_OBJECT, OFF(f_code), READONLY},
{"f_builtins", T_OBJECT, OFF(f_builtins), READONLY},
{"f_globals", T_OBJECT, OFF(f_globals... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.