buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
import stat
import shutil
import tempfile
import socket
# Import third party libs
if sys.platform.startswith('win'): | import stat
import shutil
import tempfile
import socket
import ctypes
# Import third party libs
if sys.platform.startswith('win'): |
from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
)
# Import 3rd-party libs | from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
clean_path
)
# Import 3rd-party libs |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
'''
salt.utils.clean_path works as expected
'''
def setUp(self):
self.tmpdir = tempfile... |
class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, thetamax = thetamax, thetamin | class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
self._unstale_viewLim()
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, theta... |
def test_polar_invertedylim():
def test_polar_invertedylim_rorigin():
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_ylim(2, 0)
ax.set_rorigin(3)
| def test_polar_invertedylim():
def test_polar_invertedylim_rorigin():
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.yaxis.set_inverted(True)
# Set the rlims to inverted (2, 0) without calling set_rlim, to check that
# viewlims are correctly unstaled before draw()ing.
... |
_simple_palette = re.compile(b'^\xff+\x00\xff*$')
# --------------------------------------------------------------------
# Support classes. Suitable for PNG and related formats like MNG etc. |
_simple_palette = re.compile(b'^\xff+\x00\xff*$')
# Maximum decompressed size for a iTXt or zTXt chunk.
# Eliminates decompression bombs where compressed chunks can expand 1000x
MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
# Set the maximum total text chunk size.
MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
def _safe_zlib_decompre... |
def __init__(self, fp):
self.im_tile = None
self.im_palette = None
def chunk_iCCP(self, pos, length):
# ICC profile | def __init__(self, fp):
self.im_tile = None
self.im_palette = None
self.text_memory = 0
def check_text_memory(self, chunklen):
self.text_memory += chunklen
if self.text_memory > MAX_TEXT_MEMORY:
raise ValueError("Too much memory used in text chunks: %s>MAX_TEXT_... |
def chunk_iCCP(self, pos, length):
raise SyntaxError("Unknown compression method %s in iCCP chunk" %
comp_method)
try:
icc_profile = zlib.decompress(s[i+2:])
except zlib.error:
icc_profile = None # FIXME
self.im_info["icc_profile... | def chunk_iCCP(self, pos, length):
raise SyntaxError("Unknown compression method %s in iCCP chunk" %
comp_method)
try:
icc_profile = _safe_zlib_decompress(s[i+2:])
except zlib.error:
icc_profile = None # FIXME
self.im_info["icc_p... |
def chunk_tEXt(self, pos, length):
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
return s
def chunk_zTXt(self, pos, length): | def chunk_tEXt(self, pos, length):
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_zTXt(self, pos, length): |
def chunk_zTXt(self, pos, length):
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = zlib.decompress(v[1:])
except zlib.error:
v = b""
| def chunk_zTXt(self, pos, length):
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = _safe_zlib_decompress(v[1:])
except zlib.error:
v = b""
|
def chunk_zTXt(self, pos, length):
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
return s
def chunk_iTXt(self, pos, length): | def chunk_zTXt(self, pos, length):
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_iTXt(self, pos, length): |
def chunk_iTXt(self, pos, length):
if cf != 0:
if cm == 0:
try:
v = zlib.decompress(v)
except zlib.error:
return s
else: | def chunk_iTXt(self, pos, length):
if cf != 0:
if cm == 0:
try:
v = _safe_zlib_decompress(v)
except zlib.error:
return s
else: |
def chunk_iTXt(self, pos, length):
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
return s
| def chunk_iTXt(self, pos, length):
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
self.check_text_memory(len(v))
return s
|
def test_bad_itxt(self):
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' +
zlib.compress(b"egg")[:1]) + TAIL)
self.assertEqual(im.info, {})
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' +
zlib.compress(b"egg")) + T... | def test_bad_itxt(self):
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' +
zlib.compress(b"egg")[:1]) + TAIL)
self.assertEqual(im.info, {'spam':''})
im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' +
zlib.compress(b"e... |
import traceback
# Import 3rd-party libs
import jinja2
import jinja2.ext
# Import Salt libs
import salt.utils.data | import traceback
# Import 3rd-party libs
import jinja2
import jinja2.ext
import jinja2.sandbox
# Import Salt libs
import salt.utils.data |
def render_jinja_tmpl(tmplstr, context, tmplpath=None):
opt_jinja_env_helper(opt_jinja_env, "jinja_env")
if opts.get("allow_undefined", False):
jinja_env = jinja2.Environment(**env_args)
else:
jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined, **env_args)
tojson_filte... | def render_jinja_tmpl(tmplstr, context, tmplpath=None):
opt_jinja_env_helper(opt_jinja_env, "jinja_env")
if opts.get("allow_undefined", False):
jinja_env = jinja2.sandbox.SandboxedEnvironment(**env_args)
else:
jinja_env = jinja2.sandbox.SandboxedEnvironment(
undefined=jinja2... |
def render_jinja_tmpl(tmplstr, context, tmplpath=None):
except (
jinja2.exceptions.TemplateRuntimeError,
jinja2.exceptions.TemplateSyntaxError,
) as exc:
trace = traceback.extract_tb(sys.exc_info()[2])
line, out = _get_jinja_error(trace, context=decoded_context) | def render_jinja_tmpl(tmplstr, context, tmplpath=None):
except (
jinja2.exceptions.TemplateRuntimeError,
jinja2.exceptions.TemplateSyntaxError,
jinja2.exceptions.SecurityError,
) as exc:
trace = traceback.extract_tb(sys.exc_info()[2])
line, out = _get_jinja_error(trace, c... |
import logging
import os
import sys
import salt.utils.files
# Import Salt libs | import logging
import os
import sys
import pytest
import salt.utils.files
# Import Salt libs |
class RenderTestCase(TestCase):
res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx)
self.assertEqual(res.strip(), "OK")
class MockRender(object):
def __call__(self, tplstr, context, tmplpath=None): | class RenderTestCase(TestCase):
res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx)
self.assertEqual(res.strip(), "OK")
def test_render_jinja_cve_2021_25283(self):
tmpl = """{{ [].__class__ }}"""
ctx = dict(self.context)
ctx["var"] = "OK"
with pytest.raises(sal... |
class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=others)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
... | class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=idx)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
el... |
def test_string_array_extract():
result = result.astype(object)
tm.assert_equal(result, expected) | def test_string_array_extract():
result = result.astype(object)
tm.assert_equal(result, expected)
@pytest.mark.parametrize("klass", [tuple, list, np.array, pd.Series, pd.Index])
def test_cat_different_classes(klass):
# https://github.com/pandas-dev/pandas/issues/33425
s = pd.Series(["a", "b", "c"])
... |
class Parameter(object):
return [str(v) for v in x]
return str(x)
def parse_from_input(self, param_name, x):
"""
Parses the parameter value from input ``x``, handling defaults and is_list.
| class Parameter(object):
return [str(v) for v in x]
return str(x)
def parse_from_input(self, param_name, x, task_name=None):
"""
Parses the parameter value from input ``x``, handling defaults and is_list.
|
class Parameter(object):
:raises MissingParameterException: if x is false-y and no default is specified.
"""
if not x:
if self.has_value:
return self.value
elif self.is_bool:
return False
elif self.is_list: | class Parameter(object):
:raises MissingParameterException: if x is false-y and no default is specified.
"""
if not x:
if self.has_task_value(param_name=param_name, task_name=task_name):
return self.task_value(param_name=param_name, task_name=task_name)
el... |
class Parameter(object):
description.append('for all instances of class %s' % task_name)
elif self.description:
description.append(self.description)
if self.has_value:
description.append(" [default: %s]" % (self.value,))
if self.is_list:
action = ... | class Parameter(object):
description.append('for all instances of class %s' % task_name)
elif self.description:
description.append(self.description)
if self.has_task_value(param_name=param_name, task_name=task_name):
value = self.task_value(param_name=param_name, task... |
class Parameter(object):
dest = self.parser_dest(param_name, task_name, glob=False)
if dest is not None:
value = getattr(args, dest, None)
params[param_name] = self.parse_from_input(param_name, value)
def set_global_from_args(self, param_name, task_name, args, is_without_sec... | class Parameter(object):
dest = self.parser_dest(param_name, task_name, glob=False)
if dest is not None:
value = getattr(args, dest, None)
params[param_name] = self.parse_from_input(param_name, value, task_name=task_name)
def set_global_from_args(self, param_name, task_name,... |
class Parameter(object):
if dest is not None:
value = getattr(args, dest, None)
if value:
self.set_global(self.parse_from_input(param_name, value))
else: # either False (bools) or None (everything else)
self.reset_global()
| class Parameter(object):
if dest is not None:
value = getattr(args, dest, None)
if value:
self.set_global(self.parse_from_input(param_name, value, task_name=task_name))
else: # either False (bools) or None (everything else)
self.reset_global()... |
class TestRemoveGlobalParameters(unittest.TestCase):
class TestParamWithDefaultFromConfig(unittest.TestCase):
def testNoSection(self):
self.assertRaises(ParameterException, lambda: luigi.Parameter(config_path=dict(section="foo", name="bar")).value)
| class TestRemoveGlobalParameters(unittest.TestCase):
class TestParamWithDefaultFromConfig(unittest.TestCase):
def run_and_check(self, args):
run_exit_status = luigi.run(['--local-scheduler', '--no-lock'] + args)
return run_exit_status
def testNoSection(self):
self.assertRaises(Paramet... |
class TestParamWithDefaultFromConfig(unittest.TestCase):
self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back)
self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back)
class OverrideEnvStuff(unittest.TestCase):
| class TestParamWithDefaultFromConfig(unittest.TestCase):
self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back)
self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back)
@with_config({"MyClass": {"p_not_global": "123"}})
def testCommandLineWithDefault(self):
... |
class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self._get_values(key)
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? | class Series(base.IndexOpsMixin, generic.NDFrame):
indexer = self.index.get_indexer_for(key)
return self.iloc[indexer]
else:
return self.iloc[key]
if isinstance(key, (list, tuple)):
# TODO: de-dup with tuple case handled above? |
class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = (
r"Buffer has wrong number of dimensions \(expected 1, "
r"got 3\)|"
"Cannot index with multidimensional key|"
r"Wrong number of dimensions. values.ndim != ndim \[... | class TestFancy:
idxr = idxr(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = "|".join(
[
r"Buffer has wrong number of dimensions \(expected 1, got 3\)",
"Cannot index with multidimensional key",
r"Wrong number of dimensions. valu... |
class ResponseTypes(object):
def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition).split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_filename(filename)
except IndexError: | class ResponseTypes(object):
def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition,
encoding='latin-1', errors='replace').split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_fi... |
import unittest
from scrapy.responsetypes import responsetypes
| # -*- coding: utf-8 -*-
import unittest
from scrapy.responsetypes import responsetypes
|
class ResponseTypesTest(unittest.TestCase):
def test_from_content_disposition(self):
mappings = [
('attachment; filename="data.xml"', XmlResponse),
('attachment; filename=data.xml', XmlResponse),
]
for source, cls in mappings:
retcls = responsetypes.from_... | class ResponseTypesTest(unittest.TestCase):
def test_from_content_disposition(self):
mappings = [
(b'attachment; filename="data.xml"', XmlResponse),
(b'attachment; filename=data.xml', XmlResponse),
(u'attachment;filename=data£.tar.gz'.encode('utf-8'), Response),
... |
class DataFrame(NDFrame):
# ----------------------------------------------------------------------
# Arithmetic / combination related
def _combine_frame(self, other, func, fill_value=None, level=None):
# at this point we have `self._indexed_same(other)`
if fill_value is None: | class DataFrame(NDFrame):
# ----------------------------------------------------------------------
# Arithmetic / combination related
def _combine_frame(self, other: "DataFrame", func, fill_value=None):
# at this point we have `self._indexed_same(other)`
if fill_value is None: |
class DataFrame(NDFrame):
return new_data
def _combine_match_index(self, other, func):
# at this point we have `self.index.equals(other.index)`
if ops.should_series_dispatch(self, other, func): | class DataFrame(NDFrame):
return new_data
def _combine_match_index(self, other: Series, func):
# at this point we have `self.index.equals(other.index)`
if ops.should_series_dispatch(self, other, func): |
class DataFrame(NDFrame):
new_data = ops.dispatch_to_series(self, other, func)
else:
# fastpath --> operate directly on values
with np.errstate(all="ignore"):
new_data = func(self.values.T, other.values).T
return new_data
def _construct_result(sel... | class DataFrame(NDFrame):
new_data = ops.dispatch_to_series(self, other, func)
else:
# fastpath --> operate directly on values
other_vals = other.values.reshape(-1, 1)
with np.errstate(all="ignore"):
new_data = func(self.values, other_vals)
... |
def mask_zero_div_zero(x, y, result):
return result
if zmask.any():
shape = result.shape
# Flip sign if necessary for -0.0
zneg_mask = zmask & np.signbit(y)
zpos_mask = zmask & ~zneg_mask
nan_mask = (zmask & (x == 0)).ravel()
with np.errstate(invalid="ignor... | def mask_zero_div_zero(x, y, result):
return result
if zmask.any():
# Flip sign if necessary for -0.0
zneg_mask = zmask & np.signbit(y)
zpos_mask = zmask & ~zneg_mask
nan_mask = zmask & (x == 0)
with np.errstate(invalid="ignore"):
neginf_mask = (zpos_ma... |
class TestFrameFlexComparisons:
class TestFrameFlexArithmetic:
def test_df_add_td64_columnwise(self):
# GH 22534 Check that column-wise addition broadcasts correctly
dti = pd.date_range("2016-01-01", periods=10) | class TestFrameFlexComparisons:
class TestFrameFlexArithmetic:
def test_floordiv_axis0(self):
# make sure we df.floordiv(ser, axis=0) matches column-wise result
arr = np.arange(3)
ser = pd.Series(arr)
df = pd.DataFrame({"A": ser, "B": ser})
result = df.floordiv(ser, axis=0... |
class FileBasedCache(BaseCache):
def _createdir(self):
if not os.path.exists(self._dir):
try:
os.makedirs(self._dir, 0o700)
except FileExistsError:
pass
def _key_to_file(self, key, version=None):
""" | class FileBasedCache(BaseCache):
def _createdir(self):
if not os.path.exists(self._dir):
# Set the umask because os.makedirs() doesn't apply the "mode" argument
# to intermediate-level directories.
old_umask = os.umask(0o077)
try:
os.makedirs(... |
import os
import pickle
import re
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
from django.conf import settings
from django.core import management, signals | import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals |
class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
with mock.patch('builtins.open', side_effect=IOError):
with self.asser... | class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
@skipIf(
sys.platform == 'win32',
'Windows only partially supports umasks and chmod.',
)
def test_cache_dir_permissions(self):
... |
def delete(self, req, id):
content_type="text/plain")
image = self.get_image_meta_or_404(req, id)
if image['protected']:
msg = _("Image is protected")
logger.debug(msg) | def delete(self, req, id):
content_type="text/plain")
image = self.get_image_meta_or_404(req, id)
if not (req.context.is_admin
or image['owner'] == None
or image['owner'] == req.context.owner):
msg = _("Unable to delete image ... |
def getallmatchingheaders(self, name):
lst.append(line)
return lst
def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
... | def getallmatchingheaders(self, name):
lst.append(line)
return lst
def _read_headers(fp):
"""Reads potential header lines into a list from a file pointer.
Length of line is limited by _MAXLINE, and number of
headers is limited by _MAXHEADERS.
"""
headers = []
while True... |
def parse_headers(fp, _class=HTTPMessage):
raise HTTPException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring)
| def parse_headers(fp, _class=HTTPMessage):
raise HTTPException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
return headers
def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants ... |
def begin(self):
if status != CONTINUE:
break
# skip the header from the 100 response
while True:
skip = self.fp.readline(_MAXLINE + 1)
if len(skip) > _MAXLINE:
raise LineTooLong("header line")
skip =... | def begin(self):
if status != CONTINUE:
break
# skip the header from the 100 response
skipped_headers = _read_headers(self.fp)
if self.debuglevel > 0:
print("headers:", skipped_headers)
del skipped_headers
self.code = s... |
def test_overflowing_header_line(self):
resp = client.HTTPResponse(FakeSocket(body))
self.assertRaises(client.LineTooLong, resp.begin)
def test_overflowing_chunked_line(self):
body = (
'HTTP/1.1 200 OK\r\n' | def test_overflowing_header_line(self):
resp = client.HTTPResponse(FakeSocket(body))
self.assertRaises(client.LineTooLong, resp.begin)
def test_overflowing_header_limit_after_100(self):
body = (
'HTTP/1.1 100 OK\r\n'
'r\n' * 32768
)
resp = client.HTTP... |
def readline(self, limit):
class OfflineTest(TestCase):
def test_all(self):
# Documented objects defined in the module should be in __all__
expected = {"responses"} # White-list documented dict() object
# HTTPMessage, parse_headers(), and the HTTP status code constants are
# intenti... | def readline(self, limit):
class OfflineTest(TestCase):
def test_all(self):
# Documented objects defined in the module should be in __all__
expected = {"responses"} # Allowlist documented dict() object
# HTTPMessage, parse_headers(), and the HTTP status code constants are
# intentio... |
from django.utils.six.moves.urllib.parse import (
urlparse,
)
ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() | from django.utils.six.moves.urllib.parse import (
urlparse,
)
if six.PY2:
from urlparse import (
ParseResult, SplitResult, _splitnetloc, _splitparams, scheme_chars,
uses_params,
)
_coerce_args = None
else:
from urllib.parse import (
ParseResult, SplitResult, _coerce_args, _s... |
def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def _is_safe_url(url, host):
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.starts... | def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
def _urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params... |
class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, ... | class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'http:999999999',
'ftp:9999999999',
... |
class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s s... | class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
'path/http:2222222222'):
self.assertTrue(http.is... |
import os
import salt.payload
import salt.utils.files
import salt.utils.path
from salt.ext import six
log = logging.getLogger(__name__) | import os
import salt.payload
import salt.utils.files
import salt.utils.path
import salt.utils.verify
from salt.ext import six
log = logging.getLogger(__name__) |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
"""
t_path = os.path.join(opts["token_dir"], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
"""
t_path = os.path.join(opts["token_dir"], tok)
if not salt.utils.verify.clean_path(opts["token_dir"], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
# Import python libs
import os
import re
import socket | from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
import socket |
import stat
import sys
import salt.defaults.exitcodes
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
from salt.exceptions import CommandExecutionError, SaltClientError, SaltSystemExit
# Import salt libs
from salt.log import is_console_configured
from salt.log.setup im... | import stat
import sys
import salt.defaults.exitcodes
import salt.ext.six
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
from salt.exceptions import CommandExecutionError, SaltClientError, SaltSystemExit
from salt.log import is_console_configured
from salt.log.setup im... |
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
"""
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ""
for part in path.split(os.path.sep)[1:]:
if base != "":
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
__opts__["config_dir"], os.path.dirname(__opts__["default_include"])
)
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
log.debug("Creating directory %s", dir_path... | def update_config(file_name, yaml_contents):
__opts__["config_dir"], os.path.dirname(__opts__["default_include"])
)
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False,)
if not os.path.exists(dir_path):
log.debug("Creating directory %s", dir_pat... |
def find(path, saltenv="base"):
return ret
for root in __opts__["file_roots"][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, "rb") as fp_: | def find(path, saltenv="base"):
return ret
for root in __opts__["file_roots"][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
dest = os.path.join(__opts__["file_roots"][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
... | def write(data, path, saltenv="base", index=0):
return (
"The path passed in {0} is not relative to the environment " "{1}"
).format(path, saltenv)
root = __opts__["file_roots"][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, dest, subdir... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), "Evil file created" | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), "Evil file created"
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config("master")
self.conf_dir ... |
class BadTestModuleNamesTestCase(TestCase):
"integration.logging.test_jid_logging",
"integration.logging.handlers.test_logstash_mod",
"integration.master.test_event_return",
"integration.minion.test_blackout",
"integration.minion.test_executor",
"i... | class BadTestModuleNamesTestCase(TestCase):
"integration.logging.test_jid_logging",
"integration.logging.handlers.test_logstash_mod",
"integration.master.test_event_return",
"integration.master.test_clear_funcs",
"integration.minion.test_blackout",
... |
class BadTestModuleNamesTestCase(TestCase):
"integration.reactor.test_reactor",
"integration.returners.test_noop_return",
"integration.runners.test_runner_returns",
"unit.utils.scheduler.test_error",
"unit.utils.scheduler.test_eval",
"unit.utils.sc... | class BadTestModuleNamesTestCase(TestCase):
"integration.reactor.test_reactor",
"integration.returners.test_noop_return",
"integration.runners.test_runner_returns",
"integration.scheduler.test_error",
"integration.scheduler.test_eval",
"integration... |
class BadTestModuleNamesTestCase(TestCase):
"integration.ssh.test_raw",
"integration.ssh.test_saltcheck",
"integration.ssh.test_state",
"integration.ssh.test_pre_flight",
"integration.states.test_compiler",
"integration.states.test_handle_error",
... | class BadTestModuleNamesTestCase(TestCase):
"integration.ssh.test_raw",
"integration.ssh.test_saltcheck",
"integration.ssh.test_state",
"integration.states.test_compiler",
"integration.states.test_handle_error",
"integration.states.test_handle_iord... |
Test the verification routines
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import getpass
import os
import shutil | Test the verification routines
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import ctypes
import getpass
import os
import shutil |
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-b
from salt.utils.verify import (
check_max_open_files,
check_user,
log,
valid_id,
verify_env, | from salt.ext.six.moves import range # pylint: disable=import-error,redefined-b
from salt.utils.verify import (
check_max_open_files,
check_user,
clean_path,
log,
valid_id,
verify_env, |
from salt.utils.verify import (
from tests.support.helpers import TstSuiteLoggingHandler, requires_network
from tests.support.mock import MagicMock, patch
# Import Salt Testing libs
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf | from salt.utils.verify import (
from tests.support.helpers import TstSuiteLoggingHandler, requires_network
from tests.support.mock import MagicMock, patch
# Import Salt Testing libs
# Import Salt Testing libs
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf |
else:
import resource
class TestVerify(TestCase):
"""
Verify module tests | else:
import resource
# Import third party libs
if sys.platform.startswith("win"):
import win32file
else:
import resource
class TestVerify(TestCase):
"""
Verify module tests |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
"""
salt.utils.clean_path works as expected
"""
def setUp(self):
self.tmpdir = tempfil... |
from typing import (
Callable,
Collection,
Dict,
Generic,
Iterable,
Iterator, | from typing import (
Callable,
Collection,
Dict,
Generator,
Generic,
Iterable,
Iterator, |
def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf
def get_future_imports(node: Node) -> Set[str]:
"""Return a set of __future__ imports in the file."""
imports = set()
for child in node.children:
if child.type != syms.simple_stmt:
break | def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[Leaf
def get_future_imports(node: Node) -> Set[str]:
"""Return a set of __future__ imports in the file."""
imports: Set[str] = set()
def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
for chil... |
def get_future_imports(node: Node) -> Set[str]:
module_name = first_child.children[1]
if not isinstance(module_name, Leaf) or module_name.value != "__future__":
break
for import_from_child in first_child.children[3:]:
if isinstance(import_from_child, L... | def get_future_imports(node: Node) -> Set[str]:
module_name = first_child.children[1]
if not isinstance(module_name, Leaf) or module_name.value != "__future__":
break
imports |= set(get_imports_from_children(first_child.children[3:]))
else:
break
... |
#!/usr/bin/env python2
from __future__ import unicode_literals
u'hello'
U"hello" | #!/usr/bin/env python2
from __future__ import unicode_literals as _unicode_literals
from __future__ import absolute_import
from __future__ import print_function as lol, with_function
u'hello'
U"hello" |
Ur"hello"
#!/usr/bin/env python2
from __future__ import unicode_literals
"hello"
"hello" | Ur"hello"
#!/usr/bin/env python2
from __future__ import unicode_literals as _unicode_literals
from __future__ import absolute_import
from __future__ import print_function as lol, with_function
"hello"
"hello" |
class BlackTestCase(unittest.TestCase):
self.assertEqual(set(), black.get_future_imports(node))
node = black.lib2to3_parse("from some.module import black\n")
self.assertEqual(set(), black.get_future_imports(node))
def test_debug_visitor(self) -> None:
source, _ = read_data("debug_vi... | class BlackTestCase(unittest.TestCase):
self.assertEqual(set(), black.get_future_imports(node))
node = black.lib2to3_parse("from some.module import black\n")
self.assertEqual(set(), black.get_future_imports(node))
node = black.lib2to3_parse(
"from __future__ import unicode_li... |
import bz2
from collections import abc
import gzip
from io import BufferedIOBase, BytesIO
import mmap
import os
import pathlib | import bz2
from collections import abc
import gzip
from io import BufferedIOBase, BytesIO, RawIOBase
import mmap
import os
import pathlib |
def get_handle(
try:
from s3fs import S3File
need_text_wrapping = (BufferedIOBase, S3File)
except ImportError:
need_text_wrapping = BufferedIOBase # type: ignore
handles: List[IO] = list()
f = path_or_buf | def get_handle(
try:
from s3fs import S3File
need_text_wrapping = (BufferedIOBase, RawIOBase, S3File)
except ImportError:
need_text_wrapping = (BufferedIOBase, RawIOBase) # type: ignore
handles: List[IO] = list()
f = path_or_buf |
def get_handle(
from io import TextIOWrapper
g = TextIOWrapper(f, encoding=encoding, newline="")
if not isinstance(f, BufferedIOBase):
handles.append(g)
f = g
| def get_handle(
from io import TextIOWrapper
g = TextIOWrapper(f, encoding=encoding, newline="")
if not isinstance(f, (BufferedIOBase, RawIOBase)):
handles.append(g)
f = g
|
Module contains tools for processing files into DataFrames or other objects
from collections import abc, defaultdict
import csv
import datetime
from io import BufferedIOBase, StringIO, TextIOWrapper
import re
import sys
from textwrap import fill | Module contains tools for processing files into DataFrames or other objects
from collections import abc, defaultdict
import csv
import datetime
from io import BufferedIOBase, RawIOBase, StringIO, TextIOWrapper
import re
import sys
from textwrap import fill |
class CParserWrapper(ParserBase):
# Handle the file object with universal line mode enabled.
# We will handle the newline character ourselves later on.
if isinstance(src, BufferedIOBase):
src = TextIOWrapper(src, encoding=encoding, newline="")
kwds["enco... | class CParserWrapper(ParserBase):
# Handle the file object with universal line mode enabled.
# We will handle the newline character ourselves later on.
if isinstance(src, (BufferedIOBase, RawIOBase)):
src = TextIOWrapper(src, encoding=encoding, newline="")
... |
def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt):
)
def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding):
# gh-23779: Python csv engine shouldn't error on files opened in binary.
parser = all_parsers
fpath = os.path.join(csv_dir_path, fname) | def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt):
)
def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding):
# gh-23779: Python csv engine shouldn't error on files opened in binary.
# gh-31575: Python csv engine shouldn't error on files opened in raw binary.
parser =... |
def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding):
result = parser.read_csv(fb, encoding=encoding)
tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("pass_encoding", [True, False])
def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding): | def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding):
result = parser.read_csv(fb, encoding=encoding)
tm.assert_frame_equal(expected, result)
with open(fpath, mode="rb", buffering=0) as fb:
result = parser.read_csv(fb, encoding=encoding)
tm.assert_frame_equal(expect... |
def authenticate(self, context, auth=None):
context, token_id, dict(id=token_id,
user=user_ref,
tenant=tenant_ref,
metadata=metadata_ref))
# TODO(termie): opti... | def authenticate(self, context, auth=None):
context, token_id, dict(id=token_id,
user=user_ref,
tenant=tenant_ref,
metadata=metadata_ref,
... |
# License for the specific language governing permissions and limitations
# under the License.
import uuid
import nose.exc | # License for the specific language governing permissions and limitations
# under the License.
import time
import uuid
import nose.exc |
def test_disable_user_invalidates_token(self):
self.get_client,
self.user_foo)
def test_user_create_update_delete(self):
from keystoneclient import exceptions as client_exceptions
| def test_disable_user_invalidates_token(self):
self.get_client,
self.user_foo)
def test_token_expiry_maintained(self):
foo_client = self.get_client(self.user_foo)
orig_token = foo_client.service_catalog.catalog['token']
time.sleep(1.01)
... |
from pandas.core.dtypes.common import (
ensure_object,
is_bool_dtype,
is_complex_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
is_datetimelike_v_numeric,
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer_dtype,
is_object_dtype,
is_period_dtype,
... | from pandas.core.dtypes.common import (
ensure_object,
is_bool_dtype,
is_complex_dtype,
is_datetimelike_v_numeric,
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer_dtype,
is_object_dtype,
is_scalar,
is_string_dtype,
is_string_like_dtype,
needs_i8_c... |
def _isna_new(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(
obj,
(
ABCSeries,
np.ndarray,
ABCIndexClass,
ABCExtensionArray,
ABCDatetimeArr... | def _isna_new(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj)
elif isinstance(obj, ABCDataFrame):
retu... |
def _isna_new(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike(np.asarray(obj))
else:
return obj is None
def _isna_old(obj): | def _isna_new(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike(np.asarray(obj))
else:
return False
def _isna_old(obj): |
def _isna_old(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike_old(np.asarray(obj))
else:
return obj is None
_isna = _isna_new | def _isna_old(obj):
elif hasattr(obj, "__array__"):
return _isna_ndarraylike_old(np.asarray(obj))
else:
return False
_isna = _isna_new |
def _use_inf_as_na(key):
def _isna_ndarraylike(obj):
is_extension = is_extension_array_dtype(obj)
if not is_extension:
# Avoid accessing `.values` on things like
# PeriodIndex, which may be expensive.
values = getattr(obj, "_values", obj)
else:
values = obj
dtype = va... | def _use_inf_as_na(key):
def _isna_ndarraylike(obj):
is_extension = is_extension_array_dtype(obj.dtype)
values = getattr(obj, "_values", obj)
dtype = values.dtype
if is_extension:
result = values.isna()
elif is_string_dtype(dtype):
result = _isna_string_dtype(values, dtype, old=Fa... |
def _isna_ndarraylike_old(obj):
dtype = values.dtype
if is_string_dtype(dtype):
# Working around NumPy ticket 1542
shape = values.shape
if is_string_like_dtype(dtype):
result = np.zeros(values.shape, dtype=bool)
else:
result = np.empty(shape, dtype=bool)... | def _isna_ndarraylike_old(obj):
dtype = values.dtype
if is_string_dtype(dtype):
result = _isna_string_dtype(values, dtype, old=True)
elif needs_i8_conversion(dtype):
# this is the NaT pattern
result = values.view("i8") == iNaT
else: |
def _isna_ndarraylike_old(obj):
return result
def notna(obj):
"""
Detect non-missing values for an array-like object. | def _isna_ndarraylike_old(obj):
return result
def _isna_string_dtype(values: np.ndarray, dtype: np.dtype, old: bool) -> np.ndarray:
# Working around NumPy ticket 1542
shape = values.shape
if is_string_like_dtype(dtype):
result = np.zeros(values.shape, dtype=bool)
else:
result = np... |
def na_value_for_dtype(dtype, compat: bool = True):
if is_extension_array_dtype(dtype):
return dtype.na_value
if (
is_datetime64_dtype(dtype)
or is_datetime64tz_dtype(dtype)
or is_timedelta64_dtype(dtype)
or is_period_dtype(dtype)
):
return NaT
elif is_fl... | def na_value_for_dtype(dtype, compat: bool = True):
if is_extension_array_dtype(dtype):
return dtype.na_value
if needs_i8_conversion(dtype):
return NaT
elif is_float_dtype(dtype):
return np.nan |
class TestIsNA:
exp = np.zeros(len(mask), dtype=bool)
tm.assert_numpy_array_equal(mask, exp)
@pytest.mark.parametrize(
"value, expected",
[ | class TestIsNA:
exp = np.zeros(len(mask), dtype=bool)
tm.assert_numpy_array_equal(mask, exp)
def test_isna_old_datetimelike(self):
# isna_old should work for dt64tz, td64, and period, not just tznaive
dti = pd.date_range("2016-01-01", periods=3)
dta = dti._data
dta[-... |
class Errors(object):
E168 = ("Unknown field: {field}")
E169 = ("Can't find module: {module}")
E170 = ("Cannot apply transition {name}: invalid for the current state.")
@add_codes | class Errors(object):
E168 = ("Unknown field: {field}")
E169 = ("Can't find module: {module}")
E170 = ("Cannot apply transition {name}: invalid for the current state.")
E171 = ("Matcher.add received invalid on_match callback argument: expected "
"callable or None, but got: {arg_type}")
@ad... |
def test_matcher_schema_token_attributes(en_vocab, pattern, text):
assert len(matcher) == 1
matches = matcher(doc)
assert len(matches) == 1 | def test_matcher_schema_token_attributes(en_vocab, pattern, text):
assert len(matcher) == 1
matches = matcher(doc)
assert len(matches) == 1
def test_matcher_valid_callback(en_vocab):
"""Test that on_match can only be None or callable."""
matcher = Matcher(en_vocab)
with pytest.raises(ValueErro... |
# Copyright (C) 1998-2005 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License | # Copyright (C) 1998-2006 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License |
def main():
# page don't work.
if true_filename.endswith('/index.html') and parts[-1] <> 'index.html':
action += SLASH
print Utils.maketext(
'private.html',
{'action' : action,
'realname': mlist.real_name,
'message' : message,
... | def main():
# page don't work.
if true_filename.endswith('/index.html') and parts[-1] <> 'index.html':
action += SLASH
# Escape web input parameter to avoid cross-site scripting.
print Utils.maketext(
'private.html',
{'action' : Utils.websafe(action),... |
class FileSystemStorage(Storage):
directory = os.path.dirname(full_path)
try:
if self.directory_permissions_mode is not None:
# os.makedirs applies the global umask, so we reset it,
# for consistency with file_permissions_mode behavior.
old_uma... | class FileSystemStorage(Storage):
directory = os.path.dirname(full_path)
try:
if self.directory_permissions_mode is not None:
# Set the umask because os.makedirs() doesn't apply the "mode"
# argument to intermediate-level directories.
old_umask... |
class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_directory/the_file", ContentFile("data"))
dir_mo... | class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save('the_directory/subdir/the_file', ContentFile('data'))
... |
import sys
import tempfile
import unittest
from io import StringIO
from unittest import mock
from django.conf import settings | import sys
import tempfile
import unittest
from io import StringIO
from pathlib import Path
from unittest import mock
from django.conf import settings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.