buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
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[-...
def make_template_fragment_key(fragment_name: str, vary_on: List[str] = None) -> return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on)) class Cache: """This class is used to control the cache objects."""
def make_template_fragment_key(fragment_name: str, vary_on: List[str] = None) -> return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on)) def load_module( module: Union[str, Any], lookup_obj: Optional[Any] = None, return_back: bool = False ) -> Any: """Dynamic module loading. ...
def init_app(self, app: Flask, config=None) -> None: config.setdefault("CACHE_TYPE", "null") config.setdefault("CACHE_NO_NULL_WARNING", False) config.setdefault("CACHE_SOURCE_CHECK", False) if config["CACHE_TYPE"] == "null" and not config["CACHE_NO_NULL_WARNING"]: warnings.w...
def init_app(self, app: Flask, config=None) -> None: config.setdefault("CACHE_TYPE", "null") config.setdefault("CACHE_NO_NULL_WARNING", False) config.setdefault("CACHE_SOURCE_CHECK", False) config.setdefault("CACHE_SERIALIZER", "pickle") config.setdefault("CACHE_SERIALIZER_ERROR"...
def _set_cache(self, app: Flask, config) -> None: plain_name_used = False cache_factory = import_string(import_me) cache_args = config["CACHE_ARGS"][:] cache_options = {"default_timeout": config["CACHE_DEFAULT_TIMEOUT"]} if isinstance(cache_factory, type) and issubclass(cac...
def _set_cache(self, app: Flask, config) -> None: plain_name_used = False cache_factory = import_string(import_me) from . import serialization cache_args = config["CACHE_ARGS"][:] cache_options = { "default_timeout": config["CACHE_DEFAULT_TIMEOUT"], ...
def unlink(self, *args, **kwargs) -> bool: def cached( self, timeout: Optional[int] = None, key_prefix: str = "view/%s", unless: Optional[Callable] = None, forced_update: Optional[Callable] = None,
def unlink(self, *args, **kwargs) -> bool: def cached( self, timeout: Optional[int]=None, key_prefix: str = "view/%s", unless: Optional[Callable] = None, forced_update: Optional[Callable] = None,
def cached( cache_none: bool = False, make_cache_key: Optional[Callable] = None, source_check: Optional[bool] = None, ) -> Callable: """Decorator. Use this to cache a function. By default the cache key is `view/request.path`. You are able to use this decorator with any
def cached( cache_none: bool = False, make_cache_key: Optional[Callable] = None, source_check: Optional[bool] = None, force_tuple: bool = True, ) -> Callable: """Decorator. Use this to cache a function. By default the cache key is `view/request.path`. You are able to ...
def get_list(): formed with the function's source code hash in addition to other parameters that may be included in the formation of the key. """ def decorator(f):
def get_list(): formed with the function's source code hash in addition to other parameters that may be included in the formation of the key. :param force_tuple: Default True. Cast output from list to tuple. ...
def decorated_function(*args, **kwargs): found = False else: found = self.cache.has(cache_key) except Exception: if self.app.debug: raise
def decorated_function(*args, **kwargs): found = False else: found = self.cache.has(cache_key) elif force_tuple and isinstance(rv, list) and len(rv) == 2: # JSON compatibility ...
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ def iteritems_wrapper(mappingorseq):
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ import warnings from flask_caching.serialization import pickle, PickleError def iteritems_wrapper(mappingorseq):
def iteritems_wrapper(mappingorseq): return mappingorseq class BaseCache: """Baseclass for the cache systems. All the cache systems implement this API or a superset of it.
def iteritems_wrapper(mappingorseq): return mappingorseq def extract_serializer_args(data): result = dict() serializer_prefix = "serializer_" for key in tuple(data.keys()): if key.startswith(serializer_prefix): result[key] = data.pop(key) return result class BaseCache: ""...
class BaseCache: :param default_timeout: The default timeout (in seconds) that is used if no timeout is specified on :meth:`set`. A timeout of 0 indicates that the cache never expires. """ def __init__(self, default_timeout=300): self.default_...
class BaseCache: :param default_timeout: The default timeout (in seconds) that is used if no timeout is specified on :meth:`set`. A timeout of 0 indicates that the cache never expires. :param serializer_impl: Pickle-like serialization implementation. It sh...
import tempfile from time import time from flask_caching.backends.base import BaseCache try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore logger = logging.getLogger(__name__)
import tempfile from time import time from flask_caching.backends.base import BaseCache, extract_serializer_args logger = logging.getLogger(__name__)
def __init__( mode=0o600, hash_method=hashlib.md5, ignore_errors=False, ): super().__init__(default_timeout) self._path = cache_dir self._threshold = threshold self._mode = mode
def __init__( mode=0o600, hash_method=hashlib.md5, ignore_errors=False, **kwargs ): super().__init__( default_timeout, **extract_serializer_args(kwargs) ) self._path = cache_dir self._threshold = threshold self._mode = mode
def _prune(self): try: remove = False with open(fname, "rb") as f: expires = pickle.load(f) remove = (expires != 0 and expires <= now) or idx % 3 == 0 if remove: os.remove(fname)
def _prune(self): try: remove = False with open(fname, "rb") as f: expires, _ = self._serializer.load(f) remove = (expires != 0 and expires <= now) or idx % 3 == 0 if remove: os.remove(fname)
def get(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: pickle_time = pickle.load(f) expired = pickle_time != 0 and pickle_time < time() if not expired: hit_or_miss = "hit" ...
def get(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: data = self._serializer.load(f) if isinstance(data, int): # backward compatibility # should be removed in the next major release...
def set(self, key, value, timeout=None, mgmt_element=False): suffix=self._fs_transaction_suffix, dir=self._path ) with os.fdopen(fd, "wb") as f: pickle.dump(timeout, f, 1) pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) # https://github...
def set(self, key, value, timeout=None, mgmt_element=False): suffix=self._fs_transaction_suffix, dir=self._path ) with os.fdopen(fd, "wb") as f: self._serializer.dump((timeout, value), f) # https://github.com/sh4nks/flask-caching/issues/238#issuecomme...
def has(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: pickle_time = pickle.load(f) expired = pickle_time != 0 and pickle_time < time() if expired: self.delete(key)
def has(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: pickle_time, _ = self._serializer.load(f) expired = pickle_time != 0 and pickle_time < time() if expired: self.delete(key)
def has(self, key): result = True except FileNotFoundError: pass except (OSError, pickle.PickleError) as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else "" logger.debug("has key %r -> %s %s", key, result, ex...
def has(self, key): result = True except FileNotFoundError: pass except (OSError, self._serialization_error) as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else "" logger.debug("has key %r -> %s %s", key, res...
""" from time import time from flask_caching.backends.base import BaseCache, iteritems_wrapper try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore _test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match
""" from time import time from flask_caching.backends.base import ( BaseCache, extract_serializer_args, iteritems_wrapper, ) _test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match
class MemcachedCache(BaseCache): different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None): super().__init__(default_timeout) if servers is None or isinstance(servers, (list, tuple)): if servers is None: serve...
class MemcachedCache(BaseCache): different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None, **kwargs): super().__init__( default_timeout, **extract_serializer_args(kwargs) ) if servers is None or isinstance(servers, (l...
def __init__( password=None, **kwargs, ): super().__init__(default_timeout=default_timeout) if servers is None: servers = ["127.0.0.1:11211"]
def __init__( password=None, **kwargs, ): super().__init__( default_timeout=default_timeout, **extract_serializer_args(kwargs) ) if servers is None: servers = ["127.0.0.1:11211"]
def _set(self, key, value, timeout=None): # I didn't found a good way to avoid pickling/unpickling if # key is smaller than chunksize, because in case or <werkzeug.requests> # getting the length consume the data iterator. serialized = pickle.dumps(value, 2) values = {} le...
def _set(self, key, value, timeout=None): # I didn't found a good way to avoid pickling/unpickling if # key is smaller than chunksize, because in case or <werkzeug.requests> # getting the length consume the data iterator. serialized = self._serializer.dumps(value) values = {} ...
def _get(self, key): if not serialized: return None return pickle.loads(serialized)
def _get(self, key): if not serialized: return None return self._serializer.loads(serialized)
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ from flask_caching.backends.base import BaseCache from flask_caching.backends.base import iteritems_wrapper try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore cla...
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ from flask_caching.backends.base import ( BaseCache, extract_serializer_args, iteritems_wrapper ) class RedisCache(BaseCache):
def __init__( key_prefix=None, **kwargs ): super().__init__(default_timeout) if host is None: raise ValueError("RedisCache host parameter may not be None") if isinstance(host, str):
def __init__( key_prefix=None, **kwargs ): super().__init__(default_timeout, **extract_serializer_args(kwargs)) if host is None: raise ValueError("RedisCache host parameter may not be None") if isinstance(host, str):
def dump_object(self, value): t = type(value) if t == int: return str(value).encode("ascii") return b"!" + pickle.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be called with
def dump_object(self, value): t = type(value) if t == int: return str(value).encode("ascii") return b"!" + self._serializer.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be called with
def load_object(self, value): return None if value.startswith(b"!"): try: return pickle.loads(value[1:]) except pickle.PickleError: return None try: return int(value)
def load_object(self, value): return None if value.startswith(b"!"): try: return self._serializer.loads(value[1:]) except self._serialization_error: return None try: return int(value)
import logging from time import time from flask_caching.backends.base import BaseCache try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore logger = logging.getLogger(__name__)
import logging from time import time from flask_caching.backends.base import BaseCache, extract_serializer_args logger = logging.getLogger(__name__)
class SimpleCache(BaseCache): to ``False``. """ def __init__(self, threshold=500, default_timeout=300, ignore_errors=False): super().__init__(default_timeout) self._cache = {} self.clear = self._cache.clear self._threshold = threshold
class SimpleCache(BaseCache): to ``False``. """ def __init__( self, threshold=500, default_timeout=300, ignore_errors=False, **kwargs ): super().__init__(default_timeout, **extract_serializer_args(kwargs)) self._cache = {} self.clear = self._cache.c...
def get(self, key): if not expired: hit_or_miss = "hit" try: result = pickle.loads(value) except Exception as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else ""
def get(self, key): if not expired: hit_or_miss = "hit" try: result = self._serializer.loads(value) except Exception as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else ""
def get(self, key): def set(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) self._cache[key] = item logger.debug("set key %r", key) return True
def get(self, key): def set(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, self._serializer.dumps(value)) self._cache[key] = item logger.debug("set key %r", key) return True
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) updated = False should_add = key not in self._cache if should_add:
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): expires = self._normalize_timeout(timeout) self._prune() item = (expires, self._serializer.dumps(value)) updated = False should_add = key not in self._cache if should_add:
""" import platform from flask_caching.backends.base import BaseCache try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore class UWSGICache(BaseCache):
""" import platform from flask_caching.backends.base import BaseCache, extract_serializer_args class UWSGICache(BaseCache):
class UWSGICache(BaseCache): you only have to provide the name of the cache. """ def __init__(self, default_timeout=300, cache=""): super().__init__(default_timeout) if platform.python_implementation() == "PyPy": raise RuntimeError(
class UWSGICache(BaseCache): you only have to provide the name of the cache. """ def __init__(self, default_timeout=300, cache="", **kwargs): super().__init__(default_timeout, **extract_serializer_args(kwargs)) if platform.python_implementation() == "PyPy": raise RuntimeErr...
def get(self, key): rv = self._uwsgi.cache_get(key, self.cache) if rv is None: return return pickle.loads(rv) def delete(self, key): return self._uwsgi.cache_del(key, self.cache)
def get(self, key): rv = self._uwsgi.cache_get(key, self.cache) if rv is None: return return self._serializer.loads(rv) def delete(self, key): return self._uwsgi.cache_del(key, self.cache)
def delete(self, key): def set(self, key, value, timeout=None): return self._uwsgi.cache_update( key, pickle.dumps(value), self._normalize_timeout(timeout), self.cache, )
def delete(self, key): def set(self, key, value, timeout=None): return self._uwsgi.cache_update( key, self._serializer.dumps(value), self._normalize_timeout(timeout), self.cache, )
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): return self._uwsgi.cache_set( key, pickle.dumps(value), self._normalize_timeout(timeout), self.cache, )
def set(self, key, value, timeout=None): def add(self, key, value, timeout=None): return self._uwsgi.cache_set( key, self._serializer.dumps(value), self._normalize_timeout(timeout), self.cache, )
import pytest import flask_caching as fsc try: __import__("pytest_xprocess")
import pytest import flask_caching as fsc from flask_caching.serialization import json, JSONError, pickle, PickleError try: __import__("pytest_xprocess")
def xprocess(): pytest.skip("pytest-xprocess not installed.") @pytest.fixture def app(request): app = flask.Flask( request.module.__name__, template_folder=os.path.dirname(__file__) ) app.testing = True app.config["CACHE_TYPE"] = "simple" return app
def xprocess(): pytest.skip("pytest-xprocess not installed.") @pytest.fixture(params=[ {}, {'serializer_impl': pickle, 'serializer_error': PickleError}, {'serializer_impl': json, 'serializer_error': JSONError} ]) def serialization_args(request): return request.param.copy() @pytest.fixture(pa...
def test_generic_has(self, c): assert c.has("foo") in (False, 0) assert c.has("spam") in (False, 0) def test_generic_get_bytes(self, c): assert c.set("foo", b"bar") assert c.get("foo") == b"bar" class TestSimpleCache(GenericCacheTests): @pytest.fixture def make_cache(self)...
def test_generic_has(self, c): assert c.has("foo") in (False, 0) assert c.has("spam") in (False, 0) class TestSimpleCache(GenericCacheTests): @pytest.fixture def make_cache(self, serialization_args): return lambda: backends.SimpleCache(**serialization_args) def test_purge(self): ...
def test_purge(self): class TestFileSystemCache(GenericCacheTests): @pytest.fixture def make_cache(self, tmpdir): return lambda **kw: backends.FileSystemCache(cache_dir=str(tmpdir), **kw) def test_filesystemcache_hashes(self, make_cache, hash_method): cache = make_cache(hash_method=hash_me...
def test_purge(self): class TestFileSystemCache(GenericCacheTests): @pytest.fixture def make_cache(self, tmpdir, serialization_args): return lambda **kw: backends.FileSystemCache( cache_dir=str(tmpdir), **{**kw, **serialization_args} ) def test_filesystemcache_hashes(self, make...
def requirements(self, redis_server): pass @pytest.fixture(params=(None, False, True, gen_key_prefix)) def make_cache(self, request): key_prefix = "werkzeug-test-case:" if request.param is None: host = "localhost"
def requirements(self, redis_server): pass @pytest.fixture(params=(None, False, True, gen_key_prefix)) def make_cache(self, request, serialization_args): key_prefix = "werkzeug-test-case:" if request.param is None: host = "localhost"
def make_cache(self, request): else: host = redis.Redis() c = backends.RedisCache(host=host, key_prefix=key_prefix) yield lambda: c c.clear()
def make_cache(self, request): else: host = redis.Redis() c = backends.RedisCache(host=host, key_prefix=key_prefix, **serialization_args) yield lambda: c c.clear()
def requirements(self, memcache_server): pass @pytest.fixture def make_cache(self): c = backends.MemcachedCache(key_prefix="werkzeug-test-case:") yield lambda: c c.clear()
def requirements(self, memcache_server): pass @pytest.fixture def make_cache(self, serialization_args): c = backends.MemcachedCache(key_prefix="werkzeug-test-case:", **serialization_args) yield lambda: c c.clear()
import hashlib import time from flask import request def test_cached_view(app, cache):
import hashlib import time import pytest from flask import request, Response def test_cached_view(app, cache):
def cached_view(): assert the_time != rv.data.decode("utf-8") def test_cached_view_unless(app, cache): @app.route("/a") @cache.cached(5, unless=lambda: True)
def cached_view(): assert the_time != rv.data.decode("utf-8") @pytest.mark.parametrize('response,mime_type', ( ('123', 'text/plain'), ('["1"]', 'application/json'), ('<html></html>', 'text/html'), (b"\x00", 'application/octet-stream'), ('123', None) )) @pytest.mark.parametrize('status', (200, '200 OK'...
class EmptyLineTracker: # Don't insert empty lines between decorators. return 0, 0 newlines = 2 if current_line.depth: newlines -= 1
class EmptyLineTracker: # Don't insert empty lines between decorators. return 0, 0 if is_decorator and self.previous_line and self.previous_line.is_comment: # Don't insert empty lines between decorator comments. return 0, 0 newlin...
class BlackTestCase(unittest.TestCase): ) self.assertEqual(result.exit_code, 1) if __name__ == "__main__": unittest.main()
class BlackTestCase(unittest.TestCase): ) self.assertEqual(result.exit_code, 1) @patch("black.dump_to_file", dump_to_stderr) def test_comment_in_decorator(self) -> None: source, expected = read_data("comments6") actual = fs(source) self.assertFormatEqual(expected...
class CrawlerProcess(CrawlerRunner): def __init__(self, settings): super(CrawlerProcess, self).__init__(settings) install_shutdown_handlers(self._signal_shutdown) configure_logging(settings) log_scrapy_info(settings) def _signal_shutdown(self, signum, _): install_shutdow...
class CrawlerProcess(CrawlerRunner): def __init__(self, settings): super(CrawlerProcess, self).__init__(settings) install_shutdown_handlers(self._signal_shutdown) configure_logging(self.settings) log_scrapy_info(self.settings) def _signal_shutdown(self, signum, _): insta...
import warnings import unittest from scrapy.crawler import Crawler, CrawlerRunner from scrapy.settings import Settings, default_settings from scrapy.spiderloader import SpiderLoader from scrapy.utils.spider import DefaultSpider
import warnings import unittest from scrapy.crawler import Crawler, CrawlerRunner, CrawlerProcess from scrapy.settings import Settings, default_settings from scrapy.spiderloader import SpiderLoader from scrapy.utils.spider import DefaultSpider
class CrawlerRunnerTestCase(unittest.TestCase): self.assertEqual(len(w), 1) self.assertIn('Please use SPIDER_LOADER_CLASS', str(w[0].message))
class CrawlerRunnerTestCase(unittest.TestCase): self.assertEqual(len(w), 1) self.assertIn('Please use SPIDER_LOADER_CLASS', str(w[0].message)) class CrawlerProcessTest(unittest.TestCase): def test_crawler_process_accepts_dict(self): runner = CrawlerProcess({'foo': 'bar'}) s...
def __virtual__(): return __virtualname__ def _check_cb(cb_): """ If the callback is None or is not callable, return a lambda that returns
def __virtual__(): return __virtualname__ def _log_cmd(cmd): if not isinstance(cmd, list): return cmd.split()[0].strip() return cmd[0].strip() def _check_cb(cb_): """ If the callback is None or is not callable, return a lambda that returns
def _run( ) env[bad_env_key] = "" def _get_stripped(cmd): # Return stripped command string copies to improve logging. if isinstance(cmd, list): return [x.strip() if isinstance(x, str) else x for x in cmd] elif isinstance(cmd, str): return cmd.strip() ...
def _run( ) env[bad_env_key] = "" if output_loglevel is not None: # Always log the shell commands at INFO unless quiet logging is # requested. The command output is what will be controlled by the # 'loglevel' parameter. msg = "Executing command {}{}{} {}{}in director...
def _run( log.error( "Failed to decode stdout from command %s, non-decodable " "characters have been replaced", cmd, ) try:
def _run( log.error( "Failed to decode stdout from command %s, non-decodable " "characters have been replaced", _log_cmd(cmd), ) try:
def _run( log.error( "Failed to decode stderr from command %s, non-decodable " "characters have been replaced", cmd, ) if rstrip:
def _run( log.error( "Failed to decode stderr from command %s, non-decodable " "characters have been replaced", _log_cmd(cmd), ) if rstrip:
def _run( if not ignore_retcode and ret["retcode"] != 0: if output_loglevel < LOG_LEVELS["error"]: output_loglevel = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"]) log.error(log_callback(msg)) if ret["s...
def _run( if not ignore_retcode and ret["retcode"] != 0: if output_loglevel < LOG_LEVELS["error"]: output_loglevel = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(_log_cmd(cmd), ret["retcode"]) log.error(log_callback(msg)) ...
def run( if not ignore_retcode and ret["retcode"] != 0: if lvl < LOG_LEVELS["error"]: lvl = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"]) log.error(log_callback(msg)) if raise_err: ...
def run( if not ignore_retcode and ret["retcode"] != 0: if lvl < LOG_LEVELS["error"]: lvl = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(_log_cmd(cmd), ret["retcode"]) log.error(log_callback(msg)) if raise_err: ...
class CMDMODTestCase(TestCase, LoaderModuleMockMixin): umask=None, use_vt=False, )
class CMDMODTestCase(TestCase, LoaderModuleMockMixin): umask=None, use_vt=False, ) def test_cve_2021_25284(self): proc = MagicMock( return_value=MockTimedProc( stdout=b"foo", stderr=b"wtf", returncode=2 ...
import time import warnings from io import BytesIO from typing import AnyStr, Callable, Optional from urllib.parse import ( ParseResultBytes, unquote_to_bytes as unquote,
import time import warnings from io import BytesIO from typing import AnyStr, Callable, Optional, Tuple from urllib.parse import ( ParseResultBytes, unquote_to_bytes as unquote,
def toChunk(data): return (networkString(f"{len(data):x}"), b"\r\n", data, b"\r\n") def fromChunk(data): """ Convert chunk to string. @type data: C{bytes} @return: tuple of (result, remaining) - both C{bytes}.
def toChunk(data): return (networkString(f"{len(data):x}"), b"\r\n", data, b"\r\n") def _ishexdigits(b: bytes) -> bool: """ Is the string case-insensitively hexidecimal? It must be composed of one or more characters in the ranges a-f, A-F and 0-9. """ for c in b: if c not in b"012...
def fromChunk(data): byte string. """ prefix, rest = data.split(b"\r\n", 1) length = int(prefix, 16) if length < 0: raise ValueError("Chunk length must be >= 0, not %d" % (length,)) if rest[length : length + 2] != b"\r\n":
def fromChunk(data): byte string. """ prefix, rest = data.split(b"\r\n", 1) length = _hexint(prefix) if length < 0: raise ValueError("Chunk length must be >= 0, not %d" % (length,)) if rest[length : length + 2] != b"\r\n":
def noMoreData(self): maxChunkSizeLineLength = 1024 class _ChunkedTransferDecoder: """ Protocol for decoding I{chunked} Transfer-Encoding, as defined by RFC 7230,
def noMoreData(self): maxChunkSizeLineLength = 1024 _chunkExtChars = ( b"\t !\"#$%&'()*+,-./0123456789:;<=>?@" b"ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`" b"abcdefghijklmnopqrstuvwxyz{|}~" b"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" b"\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b...
def _dataReceived_CHUNK_LENGTH(self) -> bool: endOfLengthIndex = self._buffer.find(b";", 0, eolIndex) if endOfLengthIndex == -1: endOfLengthIndex = eolIndex try: length = int(self._buffer[0:endOfLengthIndex], 16) except ValueError: raise _MalformedChun...
def _dataReceived_CHUNK_LENGTH(self) -> bool: endOfLengthIndex = self._buffer.find(b";", 0, eolIndex) if endOfLengthIndex == -1: endOfLengthIndex = eolIndex rawLength = self._buffer[0:endOfLengthIndex] try: length = _hexint(rawLength) except ValueError: ...
def lineReceived(self, line): self.setRawMode() elif line[0] in b" \t": # Continuation of a multi line header. self.__header = self.__header + b"\n" + line # Regular header line. # Processing of header line is delayed to allow accumulating multi # ...
def lineReceived(self, line): self.setRawMode() elif line[0] in b" \t": # Continuation of a multi line header. self.__header += b" " + line.lstrip(b" \t") # Regular header line. # Processing of header line is delayed to allow accumulating multi # l...
def fail(): # Can this header determine the length? if header == b"content-length": try: length = int(data) except ValueError:
def fail(): # Can this header determine the length? if header == b"content-length": if not data.isdigit(): return fail() try: length = int(data) except ValueError:
def headerReceived(self, line): return False header = header.lower() data = data.strip() if not self._maybeChooseTransferDecoder(header, data): return False
def headerReceived(self, line): return False header = header.lower() data = data.strip(b" \t") if not self._maybeChooseTransferDecoder(header, data): return False
def test_extensions(self): p.dataReceived(b"3; x-foo=bar\r\nabc\r\n") self.assertEqual(L, [b"abc"]) def test_oversizedChunkSizeLine(self): """ L{_ChunkedTransferDecoder.dataReceived} raises
def test_extensions(self): p.dataReceived(b"3; x-foo=bar\r\nabc\r\n") self.assertEqual(L, [b"abc"]) def test_extensionsMalformed(self): """ L{_ChunkedTransferDecoder.dataReceived} raises L{_MalformedChunkedDataError} when the chunk extension fields contain invalid ch...
def test_malformedChunkSizeNegative(self): http._MalformedChunkedDataError, p.dataReceived, b"-3\r\nabc\r\n" ) def test_malformedChunkEnd(self): r""" L{_ChunkedTransferDecoder.dataReceived} raises
def test_malformedChunkSizeNegative(self): http._MalformedChunkedDataError, p.dataReceived, b"-3\r\nabc\r\n" ) def test_malformedChunkSizeHex(self): """ L{_ChunkedTransferDecoder.dataReceived} raises L{_MalformedChunkedDataError} when the chunk size is prefixed with ...
def testChunks(self): chunked = b"".join(http.toChunk(s)) self.assertEqual((s, b""), http.fromChunk(chunked)) self.assertRaises(ValueError, http.fromChunk, b"-5\r\nmalformed!\r\n") def testConcatenatedChunks(self): chunked = b"".join([b"".join(http.toChunk(t)) for t in self....
def testChunks(self): chunked = b"".join(http.toChunk(s)) self.assertEqual((s, b""), http.fromChunk(chunked)) self.assertRaises(ValueError, http.fromChunk, b"-5\r\nmalformed!\r\n") self.assertRaises(ValueError, http.fromChunk, b"0xa\r\nmalformed!\r\n") self.assertRaises(V...
def test_headersMultiline(self): Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is preserved. See RFC 7230 section ...
def test_headersMultiline(self): Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is replaced with a single space, per: ...
def process(self): ) self.assertEqual( request.requestHeaders.getRawHeaders(b"space"), [b"space space"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"spaces"), [b"spaces spaces spaces"], ) self.assertEqua...
def process(self): ) self.assertEqual( request.requestHeaders.getRawHeaders(b"space"), [b"space space"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"spaces"), [b"spaces spaces spaces"], ) self.assertEqual( ...
def test_duplicateContentLengths(self): ] ) def test_duplicateContentLengthsWithPipelinedRequests(self): """ Two pipelined requests, the first of which includes multiple
def test_duplicateContentLengths(self): ] ) def test_contentLengthMalformed(self): """ A request with a non-integer C{Content-Length} header fails with a 400 response without calling L{Request.process}. """ self.assertRequestRejected( [ ...
def test_sendHeaderSanitizesLinearWhitespace(self): transport.value().splitlines(), [b": ".join([sanitizedBytes, sanitizedBytes])], )
def test_sendHeaderSanitizesLinearWhitespace(self): transport.value().splitlines(), [b": ".join([sanitizedBytes, sanitizedBytes])], ) class HexHelperTests(unittest.SynchronousTestCase): """ Test the L{http._hexint} and L{http._ishexdigits} helper functions. """ ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import random import shlex
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import fcntl import os import random import shlex
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=...
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_T...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, ...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, filename=filename) # vault id here may not be the vault id ac...
class VaultEditor: return data # TODO: add docstrings for arg types since this code is picky about that def write_data(self, data, filename, shred=True): """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: return data def write_data(self, data, thefile, shred=True, mode=0o600): # TODO: add docstrings for arg types since this code is picky about that """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg filename: filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :returns: None ...
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg thefile: file descriptor or filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :re...
class PdfParser: whitespace_or_hex = br"[\000\011\012\014\015\0400-9a-fA-F]" whitespace_optional = whitespace + b"*" whitespace_mandatory = whitespace + b"+" newline_only = br"[\r\n]+" newline = whitespace_optional + newline_only + whitespace_optional re_trailer_end = re.compile( whitesp...
class PdfParser: whitespace_or_hex = br"[\000\011\012\014\015\0400-9a-fA-F]" whitespace_optional = whitespace + b"*" whitespace_mandatory = whitespace + b"+" whitespace_optional_no_nl = br"[\000\011\014\015\040]*" # no "\012" aka "\n" newline_only = br"[\r\n]+" newline = whitespace_optional_no_...
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or len(iterable), **tqdm_kwargs) return enumerate(tqdm_class(iterable, start, **tqdm_kwargs)) def _tzip...
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or len(iterable), **tqdm_kwargs) return enumerate(tqdm_class(iterable, **tqdm_kwargs), start) def _tzip...
def test_enumerate(): with closing(StringIO()) as our_file: a = range(9) assert list(tenumerate(a, file=our_file)) == list(enumerate(a)) @with_setup(pretest, posttest)
def test_enumerate(): with closing(StringIO()) as our_file: a = range(9) assert list(tenumerate(a, file=our_file)) == list(enumerate(a)) assert list(tenumerate(a, 42, file=our_file)) == list(enumerate(a, 42)) @with_setup(pretest, posttest)
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, ...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exc...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None,
class FastAPI(Starlette): response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True,...
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name,
class FastAPI(Starlette): response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, ...