buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
from twisted.python.failure import Failure
from scrapy.utils.defer import mustbe_deferred, defer_result
from scrapy.utils.request import request_fingerprint
from scrapy.utils.misc import arg_to_iter
logger = logging.getLogger(__name__)
| from twisted.python.failure import Failure
from scrapy.utils.defer import mustbe_deferred, defer_result
from scrapy.utils.request import request_fingerprint
from scrapy.utils.misc import arg_to_iter
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
class MediaPipeline(object):
dfd.addCallback(self._check_media_to_download, request, info)
dfd.addBoth(self._cache_result_and_execute_waiters, fp, info)
dfd.addErrback(lambda f: logger.error(
f.value, extra={'spider': info.spider, 'failure': f})
)
return dfd.addBoth(l... | class MediaPipeline(object):
dfd.addCallback(self._check_media_to_download, request, info)
dfd.addBoth(self._cache_result_and_execute_waiters, fp, info)
dfd.addErrback(lambda f: logger.error(
f.value, exc_info=failure_to_exc_info(f), extra={'spider': info.spider})
)
r... |
class MediaPipeline(object):
logger.error(
'%(class)s found errors processing %(item)s',
{'class': self.__class__.__name__, 'item': item},
extra={'spider': info.spider, 'failure': value}
)
return item | class MediaPipeline(object):
logger.error(
'%(class)s found errors processing %(item)s',
{'class': self.__class__.__name__, 'item': item},
exc_info=failure_to_exc_info(value),
extra={'spider': info.spider... |
# -*- coding: utf-8 -*-
import os
import sys
import logging
import warnings | # -*- coding: utf-8 -*-
import sys
import logging
import warnings |
from scrapy.exceptions import ScrapyDeprecationWarning
logger = logging.getLogger(__name__)
class FailureFormatter(logging.Filter):
"""Extract exc_info from Failure instances provided as contextual data
This filter mimics Twisted log.err formatting for its first `_stuff`
argument, which means that reprs ... | from scrapy.exceptions import ScrapyDeprecationWarning
logger = logging.getLogger(__name__)
def failure_to_exc_info(failure):
"""Extract exc_info from Failure instances"""
if isinstance(failure, Failure):
return (failure.type, failure.value, failure.tb)
class TopLevelFormatter(logging.Filter): |
class TopLevelFormatter(logging.Filter):
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'failure_formatter': {
'()': 'scrapy.utils.log.FailureFormatter',
},
},
'loggers': {
'scrapy': {
'level': 'DEBUG',
'f... | class TopLevelFormatter(logging.Filter):
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
'scrapy': {
'level': 'DEBUG',
},
'twisted': {
'level': 'ERROR', |
from twisted.python.failure import Failure
from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from scrapy.xlib.pydispatch.robustapply import robustApply
logger = logging.getLogger(__name__)
| from twisted.python.failure import Failure
from scrapy.xlib.pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from scrapy.xlib.pydispatch.robustapply import robustApply
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
|
def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named):
if dont_log is None or not isinstance(failure.value, dont_log):
logger.error("Error caught on signal handler: %(receiver)s",
{'receiver': recv},
extra={'spider': spider, ... | def send_catch_log_deferred(signal=Any, sender=Anonymous, *arguments, **named):
if dont_log is None or not isinstance(failure.value, dont_log):
logger.error("Error caught on signal handler: %(receiver)s",
{'receiver': recv},
exc_info=failure_to_exc_i... |
from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy.utils.request import request_fingerprint
from scrapy.pipelines.media import MediaPipeline
from scrapy.utils.signal import disconnect_all
from scrapy import signals
| from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy.utils.request import request_fingerprint
from scrapy.pipelines.media import MediaPipeline
from scrapy.utils.log import failure_to_exc_info
from scrapy.utils.signal import disconnect_all
from scrapy import signals
|
class BaseMediaPipelineTestCase(unittest.TestCase):
assert len(l.records) == 1
record = l.records[0]
assert record.levelname == 'ERROR'
assert record.failure is fail
# disable failure logging and check again
self.pipe.LOG_FAILED_RESULTS = False | class BaseMediaPipelineTestCase(unittest.TestCase):
assert len(l.records) == 1
record = l.records[0]
assert record.levelname == 'ERROR'
self.assertTupleEqual(record.exc_info, failure_to_exc_info(fail))
# disable failure logging and check again
self.pipe.LOG_FAILED_RESULT... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import logging
import unittest | # -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import logging
import unittest |
import unittest
from testfixtures import LogCapture
from twisted.python.failure import Failure
from scrapy.utils.log import (FailureFormatter, TopLevelFormatter,
LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
class FailureFormatterTest(unittest.TestCase):
... | import unittest
from testfixtures import LogCapture
from twisted.python.failure import Failure
from scrapy.utils.log import (failure_to_exc_info, TopLevelFormatter,
LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
class FailureToExcInfoTest(unittest.TestCase):
... |
class DataFrame(NDFrame):
# join indexes only using concat
if can_concat:
if how == "left":
res = concat(frames, axis=1, join="outer", verify_integrity=True)
return res.reindex(self.index, copy=False)
else:
... | class DataFrame(NDFrame):
# join indexes only using concat
if can_concat:
if how == "left":
res = concat(
frames, axis=1, join="outer", verify_integrity=True, sort=sort
)
return res.reindex(self.i... |
def test_join_left_sequence_non_unique_index():
)
tm.assert_frame_equal(joined, expected) | def test_join_left_sequence_non_unique_index():
)
tm.assert_frame_equal(joined, expected)
@pytest.mark.parametrize("sort_kw", [True, False, None])
def test_suppress_future_warning_with_sort_kw(sort_kw):
a = DataFrame({"col1": [1, 2]}, index=["c", "a"])
b = DataFrame({"col2": [4, 5]}, index=["b", "a"... |
class Task(object):
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
if params[param_name].significant:
params_str[param_name] = params[param_name].serialize(param_value)
return params_str
| class Task(object):
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
params_str[param_name] = params[param_name].serialize(param_value)
return params_str
|
class DummyTask(luigi.Task):
datehour_param = luigi.DateHourParameter()
timedelta_param = luigi.TimeDeltaParameter()
list_param = luigi.Parameter(is_list=True)
class TaskTest(unittest.TestCase): | class DummyTask(luigi.Task):
datehour_param = luigi.DateHourParameter()
timedelta_param = luigi.TimeDeltaParameter()
list_param = luigi.Parameter(is_list=True)
insignificant_param = luigi.Parameter(significant=False)
class TaskTest(unittest.TestCase): |
class TaskTest(unittest.TestCase):
date_param=datetime(2014, 9, 13).date(),
datehour_param=datetime(2014, 9, 13, 9),
timedelta_param=timedelta(44), # doesn't support seconds
list_param=['in', 'flames'])
original = DummyTask(**params)
other = DummyTask.fr... | class TaskTest(unittest.TestCase):
date_param=datetime(2014, 9, 13).date(),
datehour_param=datetime(2014, 9, 13, 9),
timedelta_param=timedelta(44), # doesn't support seconds
list_param=['in', 'flames'],
insignificant_param='test')
original = DummyTas... |
def _convert_listlike_datetimes(
return DatetimeIndex(arg, tz=tz, name=name)
except ValueError:
pass
return arg
| def _convert_listlike_datetimes(
return DatetimeIndex(arg, tz=tz, name=name)
except ValueError:
pass
elif tz:
# DatetimeArray, DatetimeIndex
return arg.tz_localize(tz)
return arg
|
class TestToDatetimeMisc:
tm.assert_index_equal(expected, idx5)
tm.assert_index_equal(expected, idx6)
class TestGuessDatetimeFormat:
@td.skip_if_not_us_locale | class TestToDatetimeMisc:
tm.assert_index_equal(expected, idx5)
tm.assert_index_equal(expected, idx6)
@pytest.mark.parametrize("klass", [DatetimeIndex, DatetimeArray])
def test_to_datetime_dta_tz(self, klass):
# GH#27733
dti = date_range("2015-04-05", periods=3).rename("foo")
... |
)
from .jwks_client import PyJWKClient
__version__ = "2.3.0"
__title__ = "PyJWT"
__description__ = "JSON Web Token implementation in Python" | )
from .jwks_client import PyJWKClient
__version__ = "2.4.0"
__title__ = "PyJWT"
__description__ = "JSON Web Token implementation in Python" |
der_to_raw_signature,
force_bytes,
from_base64url_uint,
raw_to_der_signature,
to_base64url_uint,
) | der_to_raw_signature,
force_bytes,
from_base64url_uint,
is_pem_format,
is_ssh_key,
raw_to_der_signature,
to_base64url_uint,
) |
def __init__(self, hash_alg):
def prepare_key(self, key):
key = force_bytes(key)
invalid_strings = [
b"-----BEGIN PUBLIC KEY-----",
b"-----BEGIN CERTIFICATE-----",
b"-----BEGIN RSA PUBLIC KEY-----",
b"ssh-rsa",
]
if any(string_value i... | def __init__(self, hash_alg):
def prepare_key(self, key):
key = force_bytes(key)
if is_pem_format(key) or is_ssh_key(key):
raise InvalidKeyError(
"The specified key is an asymmetric key or x509 certificate and"
" should not be used as an HMAC secret." |
def __init__(self, **kwargs):
pass
def prepare_key(self, key):
if isinstance(
key,
(Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey),
):
return key
if isinstance(key, (bytes, str)):
... | def __init__(self, **kwargs):
pass
def prepare_key(self, key):
if isinstance(key, (bytes, str)):
if isinstance(key, str):
key = key.encode("utf-8")
str_key = key.decode("utf-8")
if "-----BEGIN PUBLIC" in str_key:
... |
import base64
import binascii
from typing import Any, Union
try: | import base64
import binascii
import re
from typing import Any, Union
try: |
def raw_to_der_signature(raw_sig: bytes, curve: EllipticCurve) -> bytes:
s = bytes_to_number(raw_sig[num_bytes:])
return encode_dss_signature(r, s) | def raw_to_der_signature(raw_sig: bytes, curve: EllipticCurve) -> bytes:
s = bytes_to_number(raw_sig[num_bytes:])
return encode_dss_signature(r, s)
# Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252
_PEMS = {
b"CERTIFICATE",
b"TRUSTED CERT... |
class TestOKPAlgorithms:
def test_okp_ed25519_should_reject_non_string_key(self):
algo = OKPAlgorithm()
with pytest.raises(TypeError):
algo.prepare_key(None)
with open(key_path("testkey_ed25519")) as keyfile: | class TestOKPAlgorithms:
def test_okp_ed25519_should_reject_non_string_key(self):
algo = OKPAlgorithm()
with pytest.raises(InvalidKeyError):
algo.prepare_key(None)
with open(key_path("testkey_ed25519")) as keyfile: |
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import cPickle
from PyQt5.Qt import (
Qt, QListWidget, QListWidgetItem, QItemSelectionModel, QAction, | __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import json
from PyQt5.Qt import (
Qt, QListWidget, QListWidgetItem, QItemSelectionModel, QAction, |
def pos_key(b):
self.edited.emit(bm)
def bm_to_item(self, bm):
return bytearray(cPickle.dumps(bm, -1))
def item_to_bm(self, item):
return cPickle.loads(bytes(item.data(Qt.UserRole)))
def get_bookmarks(self):
return list(self) | def pos_key(b):
self.edited.emit(bm)
def bm_to_item(self, bm):
return bm.copy()
def item_to_bm(self, item):
return item.data(Qt.UserRole).copy()
def get_bookmarks(self):
return list(self) |
def get_bookmarks(self):
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['pickle'])], all_files=False, initial_filename='bookmarks.pickle')
if filename:
with open(fil... | def get_bookmarks(self):
def export_bookmarks(self):
filename = choose_save_file(
self, 'export-viewer-bookmarks', _('Export bookmarks'),
filters=[(_('Saved bookmarks'), ['calibre-bookmarks'])], all_files=False, initial_filename='bookmarks.calibre-bookmarks')
if filename:
... |
from calibre.srv.routes import endpoint, json
from calibre.srv.utils import get_library_data, get_use_roman
from calibre.utils.config import prefs, tweaks
from calibre.utils.icu import sort_key
from calibre.utils.localization import get_lang
from calibre.utils.search_query_parser import ParseException
| from calibre.srv.routes import endpoint, json
from calibre.srv.utils import get_library_data, get_use_roman
from calibre.utils.config import prefs, tweaks
from calibre.utils.icu import sort_key, numeric_sort_key
from calibre.utils.localization import get_lang
from calibre.utils.search_query_parser import ParseException... |
def field_names(ctx, rd, field):
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(db.all_field_names(field)) | def field_names(ctx, rd, field):
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(sorted(db.all_field_names(field), key=numeric_sort_key)) |
Tests for L{twisted.web.twcgi}.
"""
import sys, os
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import client, twcgi, server, resource
from twisted... | Tests for L{twisted.web.twcgi}.
"""
import sys
import os
import json
from io import BytesIO
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import cl... |
print
print "cgi output"
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
| print
print "cgi output"
'''
HEADER_OUTPUT_CGI = '''\
import json
import os
print("")
print("")
vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")}
print(json.dumps(vals))
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
|
class CGITests(unittest.TestCase):
return factory.deferred
def test_duplicateHeaderCGI(self):
"""
If a CGI script emits two instances of the same header, both are sent in | class CGITests(unittest.TestCase):
return factory.deferred
def test_noProxyPassthrough(self):
"""
The CGI script is never called with the Proxy header passed through.
"""
cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI)
portnum = self.startServer(cgiFilename)
... |
class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length'):
envname = "HTTP_" + envname
env[envname] = ... | class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length', 'proxy'):
envname = "HTTP_" + envname
env[en... |
from youtube_dl import YoutubeDL
from youtube_dl.compat import compat_str
from youtube_dl.extractor import YoutubeIE
from youtube_dl.postprocessor.common import PostProcessor
from youtube_dl.utils import match_filter_func
TEST_URL = 'http://localhost/sample.mp4'
| from youtube_dl import YoutubeDL
from youtube_dl.compat import compat_str
from youtube_dl.extractor import YoutubeIE
from youtube_dl.postprocessor.common import PostProcessor
from youtube_dl.utils import ExtractorError, match_filter_func
TEST_URL = 'http://localhost/sample.mp4'
|
class TestFormatSelection(unittest.TestCase):
downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
self.assertEqual(downloaded_ids, ['B', 'C', 'D'])
class TestYoutubeDL(unittest.TestCase):
def test_subtitles(self): | class TestFormatSelection(unittest.TestCase):
downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
self.assertEqual(downloaded_ids, ['B', 'C', 'D'])
ydl = YDL({'format': 'best[height<40]'})
try:
ydl.process_ie_result(info_dict)
except ExtractorE... |
class YoutubeDL(object):
format_spec = selector.selector
def selector_function(formats):
if format_spec == 'all':
for f in formats:
yield f | class YoutubeDL(object):
format_spec = selector.selector
def selector_function(formats):
formats = list(formats)
if not formats:
return
if format_spec == 'all':
for f in formats:
... |
def test_urlsplit_normalization(self):
urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')
for scheme in ["http", "https", "ftp"]:
for c in denorm_chars:
url = "{}://netloc{}false.netloc/path".format(scheme, c)
with self.subTest(url=url, char='{:04X}'.fo... | def test_urlsplit_normalization(self):
urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')
for scheme in ["http", "https", "ftp"]:
for netloc in ["netloc{}false.netloc", "n{}user@netloc"]:
for c in denorm_chars:
url = "{}://{}/path".format(scheme, ne... |
def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.rpartition('@')[2] # ignore anything to the left of '@'
n = n.replace(':', '') # ignore characters already included
n... | def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.replace('@', '') # ignore characters already included
n = n.replace(':', '') # but not the surrounding text
n = n.r... |
from rencode import rencode_orig
# Hack to deal with python 2 and 3 differences with unicode literals.
if sys.version < '3':
import codecs
def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
unicode = str
def u(x):
return x
class TestRencode(unittest.TestCase):
def test_enc... | from rencode import rencode_orig
class TestRencode(unittest.TestCase):
def _cmp(self, *values):
for v in values:
self.assertEqual(rencode.dumps(v), rencode_orig.dumps(v))
def _reload(self, *values):
for v in values:
self.assertEqual(rencode.loads(rencode.dumps(v)), v)... |
def test_encode_float_invalid_size(self):
self.assertRaises(ValueError, rencode.dumps, 1234.56, 36)
def test_encode_fixed_str(self):
self.assertEqual(rencode.dumps(b"foobarbaz"), rencode_orig.dumps(b"foobarbaz"))
def test_encode_str(self):
self.assertEqual(rencode.dumps(b"f"*255), renc... | def test_encode_float_invalid_size(self):
self.assertRaises(ValueError, rencode.dumps, 1234.56, 36)
def test_encode_fixed_str(self):
self._cmp(b"foobarbaz")
def test_encode_str(self):
self._cmp(b"f"*255, b"\0")
def test_encode_unicode(self):
self._cmp(u"fööbar")
def t... |
def test_decode_float_64bit(self):
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([44])))
def test_decode_fixed_str(self):
self.assertEqual(rencode.loads(rencode.dumps(b"foobarbaz")), b"foobarbaz")
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([130])))
def ... | def test_decode_float_64bit(self):
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([44])))
def test_decode_fixed_str(self):
self._reload(b"foobarbaz")
self.assertRaises(IndexError, rencode.loads, bytes(bytearray([130])))
def test_decode_str(self):
self._reload(b"f"... |
def test_version_exposed(self):
assert rencode_orig.__version__
self.assertEqual(rencode.__version__[1:], rencode_orig.__version__[1:], "version number does not match")
if __name__ == '__main__':
unittest.main() | def test_version_exposed(self):
assert rencode_orig.__version__
self.assertEqual(rencode.__version__[1:], rencode_orig.__version__[1:], "version number does not match")
def test_invalidtypecode(self):
s = b';\x2f\x7f'
try:
rencode.loads(s)
except Exception:
... |
import logging
from six.moves.urllib.parse import urljoin
from w3lib.url import safe_url_string
| import logging
from six.moves.urllib.parse import urljoin, urlparse
from w3lib.url import safe_url_string
|
class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['location'])
redirected_url = urljoin(request.url, location)
| class RedirectMiddleware(BaseRedirectMiddleware):
if 'Location' not in response.headers or response.status not in allowed_status:
return response
location = safe_url_string(response.headers['Location'])
if response.headers['Location'].startswith(b'//'):
request_scheme = ... |
class RedirectMiddlewareTest(unittest.TestCase):
del rsp.headers['Location']
assert self.mw.process_response(req, rsp, self.spider) is rsp
def test_max_redirect_times(self):
self.mw.max_redirect_times = 1 | class RedirectMiddlewareTest(unittest.TestCase):
del rsp.headers['Location']
assert self.mw.process_response(req, rsp, self.spider) is rsp
def test_redirect_302_relative(self):
url = 'http://www.example.com/302'
url2 = '///i8n.example2.com/302'
url3 = 'http://i8n.example2.co... |
__metaclass__ = type
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.utils.collection_loader import AnsibleCollectionLoader
def _ensure_default_collection(collection_list=None): | __metaclass__ = type
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.utils.collection_loader import AnsibleCollectionLoader
from ansible.template import is_template, Environment
from ansible.utils.display import Display
display = Display()
def _ens... |
def _ensure_default_collection(collection_list=None):
class CollectionSearch:
# this needs to be populated before we can resolve tasks/roles/etc
_collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection)
def _load_collections(self, attr, ds):
#... | def _ensure_default_collection(collection_list=None):
class CollectionSearch:
# this needs to be populated before we can resolve tasks/roles/etc
_collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection,
always_post_validat... |
class CollectionSearch:
if not ds: # don't return an empty collection list, just return None
return None
return ds | class CollectionSearch:
if not ds: # don't return an empty collection list, just return None
return None
# This duplicates static attr checking logic from post_validate()
# because if the user attempts to template a collection name, it will
# error before it ever gets to th... |
def test_write(self):
eq(self.object.read(3), b'bar')
eq(self.object.read(3), b'baz')
class TestCommand(object):
def setUp(self): | def test_write(self):
eq(self.object.read(3), b'bar')
eq(self.object.read(3), b'baz')
class TestIoCtxSelfManagedSnaps(object):
def setUp(self):
self.rados = Rados(conffile='')
self.rados.connect()
self.rados.create_pool('test_pool')
assert self.rados.pool_exists('tes... |
def test_rounding_errors():
assert (255, 255) == ImageColor.getcolor("white", "LA")
assert (163, 33) == ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA")
Image.new("LA", (1, 1), "white") | def test_rounding_errors():
assert (255, 255) == ImageColor.getcolor("white", "LA")
assert (163, 33) == ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA")
Image.new("LA", (1, 1), "white")
def test_color_too_long():
# Arrange
color_too_long = "hsl(" + "1" * 100 + ")"
# Act / Assert
with py... |
def getrgb(color):
:param color: A color string
:return: ``(red, green, blue[, alpha])``
"""
color = color.lower()
rgb = colormap.get(color, None) | def getrgb(color):
:param color: A color string
:return: ``(red, green, blue[, alpha])``
"""
if len(color) > 100:
raise ValueError("color specifier is too long")
color = color.lower()
rgb = colormap.get(color, None) |
import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
HttpResponseRedirect,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse import unquote
... | import stat
from django.http import (
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils._os import safe_join
from django.utils.http import http_date, parse_http_date
from django.utils.six.moves.urllib.parse im... |
def serve(request, path, document_root=None, show_indexes=False):
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not ... | def serve(request, path, document_root=None, show_indexes=False):
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path)).lstrip('/')
fullpath = safe_join(document_root, path)
if os.path.isdir(fullpath):
... |
class StaticTests(SimpleTestCase):
def test_index(self):
response = self.client.get('/%s/' % self.prefix)
self.assertContains(response, 'Index of /')
class StaticHelperTest(StaticTests): | class StaticTests(SimpleTestCase):
def test_index(self):
response = self.client.get('/%s/' % self.prefix)
self.assertContains(response, 'Index of ./')
class StaticHelperTest(StaticTests): |
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from electrum import util
if platform.system() == 'Windows': | from PyQt5 import QtGui
from PyQt5 import QtWidgets
from electrum import util
from electrum.i18n import _
if platform.system() == 'Windows': |
MONOSPACE_FONT = 'monospace'
class Console(QtWidgets.QPlainTextEdit):
def __init__(self, prompt='>> ', startup_message='', parent=None):
QtWidgets.QPlainTextEdit.__init__(self, parent) | MONOSPACE_FONT = 'monospace'
class OverlayLabel(QtWidgets.QLabel):
STYLESHEET = '''
QLabel, QLabel link {
color: rgb(0, 0, 0);
background-color: rgb(248, 240, 200);
border: 1px solid;
border-color: rgb(255, 114, 47);
padding: 2px;
}
'''
def __init__(self... |
def __init__(self, prompt='>> ', startup_message='', parent=None):
self.updateNamespace({'run':self.run_script})
self.set_json(False)
def set_json(self, b):
self.is_json = b
| def __init__(self, prompt='>> ', startup_message='', parent=None):
self.updateNamespace({'run':self.run_script})
self.set_json(False)
warning_text = "<h1>{}</h1><br>{}<br><br>{}".format(
_("Warning!"),
_("Do not paste code here that you don't understand. Executing the wr... |
class _Window(PandasObject, SelectionMixin):
except (ValueError, TypeError):
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
# Always convert inf to nan
values[np.isinf(values)] = np.NaN
return values
| class _Window(PandasObject, SelectionMixin):
except (ValueError, TypeError):
raise TypeError("cannot handle this type -> {0}".format(values.dtype))
# Convert inf to nan for C funcs
inf = np.isinf(values)
if inf.any():
values = np.where(inf, np.nan, values... |
class TestRolling(Base):
result = df.rolling(2, axis=axis_frame).count()
tm.assert_frame_equal(result, expected) | class TestRolling(Base):
result = df.rolling(2, axis=axis_frame).count()
tm.assert_frame_equal(result, expected)
def test_readonly_array(self):
# GH-27766
arr = np.array([1, 3, np.nan, 3, 5])
arr.setflags(write=False)
result = pd.Series(arr).rolling(2).mean()
... |
class WebSocketTest(WebSocketBaseTestCase):
response = self.fetch('/echo')
self.assertEqual(response.code, 400)
def test_bad_websocket_version(self):
response = self.fetch('/echo',
headers={'Connection': 'Upgrade', | class WebSocketTest(WebSocketBaseTestCase):
response = self.fetch('/echo')
self.assertEqual(response.code, 400)
def test_missing_websocket_key(self):
response = self.fetch('/echo',
headers={'Connection': 'Upgrade',
'Upgrad... |
class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
self._accept_connection()
except ValueError:
gen_log.debug("Malformed WebSocket request received", | class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
except ValueError:
self.handler.set_status(400)
log_msg = "Missing/Invalid WebSocket headers"
self.handler.finish(log_msg)
gen_... |
class CkMinions:
def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None):
"""
Return a Bool. This function returns if the expression sent in is
within the scope of the valid expression
"""
v_minions = set(self.check_minions(valid, "compound").get("minion... | class CkMinions:
def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None):
"""
Validate the target minions against the possible valid minions.
If ``minions`` is provided, they will be compared against the valid
minions. Otherwise, ``expr`` and ``tgt_type`` will b... |
import salt.utils.minions
import salt.utils.network
from tests.support.mock import patch | import pytest
import salt.utils.minions
import salt.utils.network
from tests.support.mock import patch |
def test_connected_ids():
with patch_net, patch_list, patch_fetch:
ret = ckminions.connected_ids()
assert ret == {minion} | def test_connected_ids():
with patch_net, patch_list, patch_fetch:
ret = ckminions.connected_ids()
assert ret == {minion}
# These validate_tgt tests make the assumption that CkMinions.check_minions is
# correct. In other words, these tests are only worthwhile if check_minions is
# also... |
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
start = right[0]
if end < start:
return type(self)(data=[])
else:
lslice = slice(*left.slice_locs(start, end))
left_chunk = left.values[lslice]
return self._shallow_copy(left_chunk)
... | class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
start = right[0]
if end < start:
return type(self)(data=[], dtype=self.dtype, freq=self.freq)
else:
lslice = slice(*left.slice_locs(start, end))
left_chunk = left._values[lslice]
ret... |
class TestGetItem:
def test_dti_business_getitem(self):
rng = pd.bdate_range(START, END)
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5])
tm.assert_index_equal(smaller, exp)
assert smaller.freq == rng.freq
| class TestGetItem:
def test_dti_business_getitem(self):
rng = pd.bdate_range(START, END)
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="B")
tm.assert_index_equal(smaller, exp)
assert smaller.freq == exp.freq
assert smaller.freq == rng.freq
|
class TestGetItem:
def test_dti_custom_getitem(self):
rng = pd.bdate_range(START, END, freq="C")
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5])
tm.assert_index_equal(smaller, exp)
assert smaller.freq == rng.freq
sliced = rng[::5] | class TestGetItem:
def test_dti_custom_getitem(self):
rng = pd.bdate_range(START, END, freq="C")
smaller = rng[:5]
exp = DatetimeIndex(rng.view(np.ndarray)[:5], freq="C")
tm.assert_index_equal(smaller, exp)
assert smaller.freq == exp.freq
assert smaller.freq == rng.fr... |
class TestDatetimeIndexSetOps:
assert result.freq is None
assert result.tz == expected.tz
def test_intersection_empty(self):
# empty same freq GH2129
rng = date_range("6/1/2000", "6/15/2000", freq="T")
result = rng[0:0].intersection(rng)
assert len(result) ==... | class TestDatetimeIndexSetOps:
assert result.freq is None
assert result.tz == expected.tz
# parametrize over both anchored and non-anchored freqs, as they
# have different code paths
@pytest.mark.parametrize("freq", ["T", "B"])
def test_intersection_empty(self, tz_aware_fixture... |
class TestBusinessDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011")
result = a.intersection(b)
tm.assert_index_equal(result, b)
def test_month_range_union_tz_pytz(self, sort):
from pytz import timezone | class TestBusinessDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011")
result = a.intersection(b)
tm.assert_index_equal(result, b)
assert result.freq == b.freq
def test_month_range_union_tz_pytz(self, sort):
from pytz import timezone |
class TestCustomDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011", freq="C")
result = a.intersection(b)
tm.assert_index_equal(result, b) | class TestCustomDatetimeIndex:
b = bdate_range("12/10/2011", "12/20/2011", freq="C")
result = a.intersection(b)
tm.assert_index_equal(result, b)
assert result.freq == b.freq |
class TestTimedeltaIndex:
result = index_1 & index_2
expected = timedelta_range("1 day 01:00:00", periods=3, freq="h")
tm.assert_index_equal(result, expected)
def test_intersection_equal(self, sort):
# GH 24471 Test intersection outcome given the sort keyword | class TestTimedeltaIndex:
result = index_1 & index_2
expected = timedelta_range("1 day 01:00:00", periods=3, freq="h")
tm.assert_index_equal(result, expected)
assert result.freq == expected.freq
def test_intersection_equal(self, sort):
# GH 24471 Test intersection outcome gi... |
class TestTimedeltaIndex:
TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"),
TimedeltaIndex(["1 hour", "2 hour"], name=None),
),
# reveresed index
(
TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx... | class TestTimedeltaIndex:
TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"),
TimedeltaIndex(["1 hour", "2 hour"], name=None),
),
# reversed index
(
TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx"... |
class TestTimedeltaIndex:
tm.assert_index_equal(result, expected)
assert result.name == expected.name
# if reveresed order, frequency is still the same
if all(base == rng[::-1]) and sort is None:
assert isinstance(result.freq, Hour)
else: | class TestTimedeltaIndex:
tm.assert_index_equal(result, expected)
assert result.name == expected.name
# if reversed order, frequency is still the same
if all(base == rng[::-1]) and sort is None:
assert isinstance(result.freq, Hour)
else: |
class RobotsTxtMiddleware(object):
rp_dfd.callback(rp)
def _robots_error(self, failure, netloc):
self._parsers.pop(netloc).callback(None) | class RobotsTxtMiddleware(object):
rp_dfd.callback(rp)
def _robots_error(self, failure, netloc):
rp_dfd = self._parsers[netloc]
self._parsers[netloc] = None
rp_dfd.callback(None) |
class RobotsTxtMiddlewareTest(unittest.TestCase):
deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called))
return deferred
def test_ignore_robotstxt_request(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
def ignore_request(request, spider): | class RobotsTxtMiddlewareTest(unittest.TestCase):
deferred.addCallback(lambda _: self.assertTrue(middleware._logerror.called))
return deferred
def test_robotstxt_immediate_error(self):
self.crawler.settings.set('ROBOTSTXT_OBEY', True)
err = error.DNSLookupError('Robotstxt address no... |
from autobahn.util import _maybe_tls_reason
import txaio
__all__ = ("WebSocketProtocol", | from autobahn.util import _maybe_tls_reason
import txaio
import hyperlink
__all__ = ("WebSocketProtocol", |
def processHandshake(self):
#
# https://localhost:9000/?redirect=https%3A%2F%2Ftwitter.com%2F&after=3
#
url = self.http_request_params['redirect'][0]
if 'after' in self.http_request_params and len(sel... | def processHandshake(self):
#
# https://localhost:9000/?redirect=https%3A%2F%2Ftwitter.com%2F&after=3
#
url = hyperlink.URL.from_text(self.http_request_params['redirect'][0])
url = url.to_uri().normal... |
# Imports
#-----------------------------------------------------------------------------
try:
from http.cookies import SimpleCookie # Py 3
except ImportError: | # Imports
#-----------------------------------------------------------------------------
try:
from urllib.parse import urlparse # Py 3
except ImportError:
from urlparse import urlparse # Py 2
try:
from http.cookies import SimpleCookie # Py 3
except ImportError: |
#-----------------------------------------------------------------------------
class ZMQStreamHandler(websocket.WebSocketHandler):
def clear_cookie(self, *args, **kwargs):
"""meaningless for websockets"""
pass | #-----------------------------------------------------------------------------
class ZMQStreamHandler(websocket.WebSocketHandler):
def same_origin(self):
"""Check to see that origin and host match in the headers."""
# The difference between version 8 and 13 is that in 8 the
# client sends... |
def allow_draft76(self):
class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
def open(self, kernel_id):
self.kernel_id = cast_unicode(kernel_id, 'ascii')
self.session = Session(config=self.config)
self.save_on_message = self.on_message | def allow_draft76(self):
class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
def open(self, kernel_id):
# Check to see that origin matches host directly, including ports
if not self.same_origin():
self.log.warn("Cross Origin WebSocket Attempt.")
raise web.... |
def on_first_message(self, msg):
if self.get_current_user() is None:
self.log.warn("Couldn't authenticate WebSocket connection")
raise web.HTTPError(403)
self.on_message = self.save_on_message | def on_first_message(self, msg):
if self.get_current_user() is None:
self.log.warn("Couldn't authenticate WebSocket connection")
raise web.HTTPError(403)
self.on_message = self.save_on_message |
class TestFish(object):
mock.return_value.stdout.read.side_effect = [(
b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n'
b'man\nmath\npopd\npushd\nruby'),
b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git']
return mock
@pytest.mark.p... | class TestFish(object):
mock.return_value.stdout.read.side_effect = [(
b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n'
b'man\nmath\npopd\npushd\nruby'),
(b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git\n'
b'alias alias_with_equal... |
class TestFish(object):
'pushd': 'pushd',
'ruby': 'ruby',
'g': 'git',
'fish_key_reader': '/usr/bin/fish_key_reader'}
def test_app_alias(self, shell):
a... | class TestFish(object):
'pushd': 'pushd',
'ruby': 'ruby',
'g': 'git',
'fish_key_reader': '/usr/bin/fish_key_reader',
'alias_w... |
def _get_functions(overridden):
def _get_aliases(overridden):
aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip().split('\n')
for alias in alias_out:
name, value = alias.replace('alias ', '', 1).split(' ', 1)
... | def _get_functions(overridden):
def _get_aliases(overridden):
aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip()
if not alias_out:
return aliases
for alias in alias_out.split('\n'):
for separator in ... |
class core(task.Config):
class _WorkerSchedulerFactory(object):
def create_local_scheduler(self):
return scheduler.CentralPlannerScheduler(prune_on_get_work=True)
def create_remote_scheduler(self, url):
return rpc.RemoteScheduler(url) | class core(task.Config):
class _WorkerSchedulerFactory(object):
def create_local_scheduler(self):
return scheduler.CentralPlannerScheduler(prune_on_get_work=True, record_task_history=False)
def create_remote_scheduler(self, url):
return rpc.RemoteScheduler(url) |
class SchedulerTest(unittest.TestCase):
cps = luigi.scheduler.CentralPlannerScheduler()
self.assertEqual({'a': 100, 'b': 200}, cps._resources)
def test_load_recovers_tasks_index(self):
cps = luigi.scheduler.CentralPlannerScheduler()
cps.add_task(worker='A', task_id='1') | class SchedulerTest(unittest.TestCase):
cps = luigi.scheduler.CentralPlannerScheduler()
self.assertEqual({'a': 100, 'b': 200}, cps._resources)
@with_config({'scheduler': {'record_task_history': 'True'},
'task_history': {'db_connection': 'sqlite:////none/existing/path/hist.db'}})
... |
def test_parser_feed():
# Assert
assert p.image.size == (640, 480) | def test_parser_feed():
# Assert
assert p.image.size == (640, 480)
@pytest.mark.parametrize(
"test_file",
[
"Tests/images/crash-4fb027452e6988530aa5dabee76eecacb3b79f8a.j2k",
"Tests/images/crash-7d4c83eb92150fb8f1653a697703ae06ae7c4998.j2k",
"Tests/images/crash-ccca68ff40171fd... |
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... |
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings | import base64
import binascii
import hashlib
import importlib
import warnings
from collections import OrderedDict
from django.conf import settings |
def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = preferred.must_update(encoded)
is_correct = hasher.verify(pass... | def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
hasher_changed = hasher.algorithm != preferred.algorithm
must_update = hasher_changed or preferred.must_update(encoded)
is_correct = hasher.verify(password, e... |
class BasePasswordHasher(object):
def must_update(self, encoded):
return False
class PBKDF2PasswordHasher(BasePasswordHasher):
""" | class BasePasswordHasher(object):
def must_update(self, encoded):
return False
def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example... |
class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
""" | class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
def harden_runtime(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
extra_iterations = self.iteratio... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password
# truncation as d... | class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, force_bytes(data))
return constant_time_compare(encoded, encoded_2)
def safe_su... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
""" | class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
def harden_runtime(self, password, encoded):
_, data = encoded.split('$', 1)
salt = data[:29] # Length of the salt in bcrypt.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.