buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_main(verbose=False): "https_svn_python_org_root.pem") NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nokia.pem") if (not os.path.exists(CERTFILE) or not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or not os.path.exists(NOKIACERT)): ...
def test_main(verbose=False): "https_svn_python_org_root.pem") NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nokia.pem") NULLBYTECERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nullbytecert.pem") if (not o...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
def test_dotted_attribute(self): # This avoids waiting for the socket timeout. self.test_simple1() class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2
def test_dotted_attribute(self): # This avoids waiting for the socket timeout. self.test_simple1() def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. conn = httplib.HTTPConnection(ADDR, PORT) conn.request('POST', '/RPC2 HTTP/...
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). type: bool default: 'no'
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). - This setting affects packages installed from a repository as well as "local" packages installed from the filesystem or a URL. ...
class DnfModule(YumDnf): results=[], ) if self.download_only: for package in self.base.transaction.install_set: response['results'].append("Downloaded: {0}".format(package))
class DnfModule(YumDnf): results=[], ) # Validate GPG. This is NOT done in dnf.Base (it's done in the # upstream CLI subclass of dnf.Base) if not self.disable_gpg_check: for package in self.base.transaction....
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, user=user_ref, tenant=tenant_ref, ...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, expires=auth_token_data['expires'], user=user_re...
# License for the specific language governing permissions and limitations # under the License. import uuid import default_fixtures from keystone import exception from keystone import identity from keystone import service
# License for the specific language governing permissions and limitations # under the License. import time import uuid import default_fixtures from keystone import config from keystone import exception from keystone import identity from keystone import service
from keystone.openstack.common import timeutils def _build_user_auth(token=None, username=None, password=None, tenant_name=None): """Build auth dictionary.
from keystone.openstack.common import timeutils CONF = config.CONF def _build_user_auth(token=None, username=None, password=None, tenant_name=None): """Build auth dictionary.
def test_scoped_remote_authn_invalid_user(self): self.api.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict)
def test_scoped_remote_authn_invalid_user(self): self.api.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict) class TokenExpirationTest(test.TestCase): def setUp(self): super(TokenExpirationTest, self).setUp() self.identity_api = kvs_identity.Identity() ...
def get_new_command(command): def side_effect(old_cmd, command): with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive: for file in archive.getnames(): try: os.remove(file) except OSError:
def get_new_command(command): def side_effect(old_cmd, command): with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive: for file in archive.getnames(): if not os.path.abspath(file).startswith(os.getcwd()): # it's unsafe to overwrite files outside of the current dire...
def get_new_command(command): def side_effect(old_cmd, command): with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive: for file in archive.namelist(): try: os.remove(file) except OSError:
def get_new_command(command): def side_effect(old_cmd, command): with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive: for file in archive.namelist(): if not os.path.abspath(file).startswith(os.getcwd()): # it's unsafe to overwrite files outside of the current directory ...
def test_side_effect(zip_error, script): @pytest.mark.parametrize('script,fixed', [ ('unzip foo', 'unzip foo -d foo'), ('unzip foo.zip', 'unzip foo.zip -d foo')]) def test_get_new_command(zip_error, script, fixed): assert get_new_command(Command(script=script)) == fixed
def test_side_effect(zip_error, script): @pytest.mark.parametrize('script,fixed', [ ('unzip foo', 'unzip foo -d foo'), (R"unzip foo\ bar.zip", R"unzip foo\ bar.zip -d 'foo bar'"), (R"unzip 'foo bar.zip'", R"unzip 'foo bar.zip' -d 'foo bar'"), ('unzip foo.zip', 'unzip foo.zip -d foo')]) def test_get_new...
import os import zipfile from thefuck.utils import for_app def _is_bad_zip(file):
import os import zipfile from thefuck.utils import for_app from thefuck.shells import quote def _is_bad_zip(file):
def _zip_file(command): # unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...] # ^ ^ files to unzip from the archive # archive to unzip for c in command.script.split()[1:]: if not c.startswith('-'): if c.endswith('.zip'): ret...
def _zip_file(command): # unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...] # ^ ^ files to unzip from the archive # archive to unzip for c in command.split_script[1:]: if not c.startswith('-'): if c.endswith('.zip'): retur...
def match(command): def get_new_command(command): return '{} -d {}'.format(command.script, _zip_file(command)[:-4]) def side_effect(old_cmd, command):
def match(command): def get_new_command(command): return '{} -d {}'.format(command.script, quote(_zip_file(command)[:-4])) def side_effect(old_cmd, command):
class SimpleTaskState(object): self.re_enable(task) # don't allow workers to override a scheduler disable elif task.scheduler_disable_time is not None: return if new_status == FAILED and task.can_disable() and task.status != DISABLED:
class SimpleTaskState(object): self.re_enable(task) # don't allow workers to override a scheduler disable elif task.scheduler_disable_time is not None and new_status != DISABLED: return if new_status == FAILED and task.can_disable() and task.status != DI...
class CentralPlannerTest(unittest.TestCase): self.setTime(101) self.assertEqual(FAILED, self.sch.task_list('', '')['A']['status']) def test_disable_by_worker(self): self.sch.add_task(worker=WORKER, task_id='A', status=DISABLED) self.assertEqual(len(self.sch.task_list('DISABLED', '')...
class CentralPlannerTest(unittest.TestCase): self.setTime(101) self.assertEqual(FAILED, self.sch.task_list('', '')['A']['status']) def test_no_automatic_re_enable_after_manual_disable(self): self.sch = CentralPlannerScheduler(disable_persist=100) self.setTime(0) self.sch.add...
from youtube_dl.utils import ( limit_length, escape_rfc3986, escape_url, )
from youtube_dl.utils import ( limit_length, escape_rfc3986, escape_url, js_to_json, )
class TestUtil(unittest.TestCase): ) self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0') if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): ) self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0') def test_js_to_json(self): inp = '''{ 'clip':{'provider':'pseudo'} }''' self.assertEqual(js_to_json(inp), '''{ ...
class ExtractorError(Exception): expected = True if video_id is not None: msg = video_id + ': ' + msg if not expected: msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete outpu...
class ExtractorError(Exception): expected = True if video_id is not None: msg = video_id + ': ' + msg if cause: msg += u' (caused by %r)' % cause if not expected: msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call y...
def js_to_json(code): ([{,]\s*) ("[^"]*"|\'[^\']*\'|[a-z0-9A-Z]+) (:\s*) ([0-9.]+|true|false|"[^"]*"|\'[^\']*\'|\[|\{) ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res) return res
def js_to_json(code): ([{,]\s*) ("[^"]*"|\'[^\']*\'|[a-z0-9A-Z]+) (:\s*) ([0-9.]+|true|false|"[^"]*"|\'[^\']*\'| (?=\[|\{) ) ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res) return res
class TestBash(object): assert 'TF_ALIAS=fuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) assert list(shell.get_history()) == ['ls', 'rm']
class TestBash(object): assert 'TF_ALIAS=fuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "alias fuck='TF_CMD=$(TF_ALIAS" in alias asser...
class TestZsh(object): assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines([': 1432613911:0;ls', ': 1432613916:0;rm']) assert list(shell.get_history()) == ['ls', 'rm']
class TestZsh(object): assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "alias fuck='TF_CMD=$(TF_ALIAS" in alias assert '$(TF_ALIAS...
from .generic import Generic class Bash(Generic): def app_alias(self, fuck): alias = "TF_ALIAS={0}" \ " alias {0}='PYTHONIOENCODING=utf-8" \ " TF_CMD=$(TF_SHELL_ALIASES=$(alias) thefuck $(fc -ln -1)) && " \ " eval $TF_CMD".format(fuck) if settings.al...
from .generic import Generic class Bash(Generic): def app_alias(self, fuck): # It is VERY important to have the variables declared WITHIN the alias alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ " TF_SHELL_ALIASES=$(alias)" \ ...
class Fish(Generic): return ['cd', 'grep', 'ls', 'man', 'open'] def app_alias(self, fuck): return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n' ' env TF_ALIAS={0} PYTHONIOENCODING=utf-8'
class Fish(Generic): return ['cd', 'grep', 'ls', 'man', 'open'] def app_alias(self, fuck): # It is VERY important to have the variables declared WITHIN the alias return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n...
from .generic import Generic class Zsh(Generic): def app_alias(self, alias_name): alias = "alias {0}='TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ ' TF_SHELL_ALIASES=$(alias)' \ " TF_CMD=$(thefuck $(fc -ln -1 | tail -n 1)) &&" \ " eval $TF_CMD"...
from .generic import Generic class Zsh(Generic): def app_alias(self, alias_name): # It is VERY important to have the variables declared WITHIN the alias alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ " TF_SHELL_ALIASES=$(alias)" \ ...
class CorrectedCommand(object): compatibility_call(self.side_effect, old_cmd, self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '>-not-set-<'))) print(self.script)
class CorrectedCommand(object): compatibility_call(self.side_effect, old_cmd, self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '!!not-set!!'))) print(self.script)
def test_match(stderr, stdout): def test_not_match(): assert not match(Command()) @pytest.mark.parametrize('before, after', [
def test_match(stderr, stdout): def test_not_match(): assert not match(Command()) assert not match(Command(script='sudo ls', stderr='Permission denied')) @pytest.mark.parametrize('before, after', [
patterns = ['permission denied', def match(command): for pattern in patterns: if pattern.lower() in command.stderr.lower()\ or pattern.lower() in command.stdout.lower():
patterns = ['permission denied', def match(command): if command.script_parts and command.script_parts[0] == 'sudo': return False for pattern in patterns: if pattern.lower() in command.stderr.lower()\ or pattern.lower() in command.stdout.lower():
def write(data, path, saltenv="base", index=0): ) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_dir, dest): return "Invalid path" dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path) ...
def write(data, path, saltenv="base", index=0): ) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_dir, dest, subdir=True): return "Invalid path" dest = os.path.join(__opts__["pillar_roots"][saltenv][index...
class WheelPillarRootsTest(TestCase, AdaptedConfigurationTestCaseMixin): assert os.path.exists(os.path.join(self.pillar_dir, "foo")) assert ret.find("Wrote data to file") != -1 def test_cvr_2021_25282(self): ret = self.wheel.cmd( "pillar_roots.write", kwarg={"data": "foo", "path...
class WheelPillarRootsTest(TestCase, AdaptedConfigurationTestCaseMixin): assert os.path.exists(os.path.join(self.pillar_dir, "foo")) assert ret.find("Wrote data to file") != -1 def test_write_subdir(self): ret = self.wheel.cmd( "pillar_roots.write", kwarg={"data": "foo: bar", "p...
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content) # These methods are part of the public API, with default implementations.
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) name = self._save(name, content) # Ensure that the name returned from the storage system is still valid. validate_file_name(name, allow_relative_path=True) return...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation("Detected path traversal ...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ name = str(name).replace('\\', '/') dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise Suspi...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirnam...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ filename = str(filename).replace('\\', '/') # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(...
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Store filenames with forward slashes, even on Windows. return str(name).replace('\\', '/')
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Ensure the saved path is always relative to the storage root. name = os.path.relpath(full_path, self.location) # Store filenames with forward slashe...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): file_name = '/tmp/../path' s = FileSystemStorage() msg = "Detected path traversal attempt in '/tmp/..'" with self.assertRaisesMessa...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ('tmp/../path', 'tmp/..'), ('tmp\\..\\path', 'tmp/..'), ('/tmp/../path', '/tmp/..'), ('\\tmp...
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') @unittest.skipUnless(symlinks_supported(), 'Must be able to symlink to run this test.') def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied."""
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_file_save_abs_path(self): test_name = 'path/to/test.file' f = ContentFile('file saved with path') f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual...
def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com')) class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urlopen() opening a fake ht...
def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY', 'http://s...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies def proxy_bypass_environment(host):
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY # (non-all-lowercase) as it may be set from the web server by a "Proxy:" # header from the cli...
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col, series in this.items(): new_data[col] = func(series.values, other.values) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): this, other = self.align(other, join="outer", axis=0, level=level, copy=False) new_data = {} for col in this.columns: new_data[col] = func(this[col], other) fill_value = self._get_op_result_fill_value(other, func)
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], float(right[col])) return self._constructor( new_data,
class SparseDataFrame(DataFrame): new_data = {} for col in left.columns: new_data[col] = func(left[col], right[col]) return self._constructor( new_data,
class TestSparseDataFrameArithmetic: assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) @pytest.mark.filterwarnings("ignore:Sparse:FutureWarning") @pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
class TestSparseDataFrameArithmetic: assert isinstance(res, pd.SparseDataFrame) tm.assert_frame_equal(res.to_dense(), df != 0) def test_add_series_retains_dtype(self): # SparseDataFrame._combine_match_columns used to incorrectly cast # to float d = {0: [2j, 3j], 1: [0, 1]} ...
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content) # These methods are part of the public API, with default implementations.
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) name = self._save(name, content) # Ensure that the name returned from the storage system is still valid. validate_file_name(name, allow_relative_path=True) return...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation("Detected path traversal ...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ name = str(name).replace('\\', '/') dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise Suspi...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirnam...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ filename = str(filename).replace('\\', '/') # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(...
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Store filenames with forward slashes, even on Windows. return str(name).replace('\\', '/')
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Ensure the saved path is always relative to the storage root. name = os.path.relpath(full_path, self.location) # Store filenames with forward slashe...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): file_name = '/tmp/../path' s = FileSystemStorage() msg = "Detected path traversal attempt in '/tmp/..'" with self.assertRaisesMessa...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ('tmp/../path', 'tmp/..'), ('tmp\\..\\path', 'tmp/..'), ('/tmp/../path', '/tmp/..'), ('\\tmp...
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') @unittest.skipUnless(symlinks_supported(), 'Must be able to symlink to run this test.') def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied."""
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_file_save_abs_path(self): test_name = 'path/to/test.file' f = ContentFile('file saved with path') f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual...
from bisect import bisect from hashlib import md5 DEFAULT_MEMCACHED_PORT = 11211 CONN_TIMEOUT = 0.3 IO_TIMEOUT = 2.0 PICKLE_FLAG = 1 NODE_WEIGHT = 50 PICKLE_PROTOCOL = 2 TRY_COUNT = 3
from bisect import bisect from hashlib import md5 try: import simplejson as json except ImportError: import json DEFAULT_MEMCACHED_PORT = 11211 CONN_TIMEOUT = 0.3 IO_TIMEOUT = 2.0 PICKLE_FLAG = 1 JSON_FLAG = 2 NODE_WEIGHT = 50 PICKLE_PROTOCOL = 2 TRY_COUNT = 3
class MemcacheRing(object): """ def __init__(self, servers, connect_timeout=CONN_TIMEOUT, io_timeout=IO_TIMEOUT, tries=TRY_COUNT): self._ring = {} self._errors = dict(((serv, []) for serv in servers)) self._error_limited = dict(((serv, 0) for serv in servers))
class MemcacheRing(object): """ def __init__(self, servers, connect_timeout=CONN_TIMEOUT, io_timeout=IO_TIMEOUT, tries=TRY_COUNT, allow_pickle=False, allow_unpickle=False): self._ring = {} self._errors = dict(((serv, []) for serv in servers)) self._erro...
def __init__(self, servers, connect_timeout=CONN_TIMEOUT, self._client_cache = dict(((server, []) for server in servers)) self._connect_timeout = connect_timeout self._io_timeout = io_timeout def _exception_occurred(self, server, e, action='talking'): if isinstance(e, socket.timeout...
def __init__(self, servers, connect_timeout=CONN_TIMEOUT, self._client_cache = dict(((server, []) for server in servers)) self._connect_timeout = connect_timeout self._io_timeout = io_timeout self._allow_pickle = allow_pickle self._allow_unpickle = allow_unpickle or allow_pickle ...
def set(self, key, value, serialize=True, timeout=0): :param key: key :param value: value :param serialize: if True, value is pickled before sending to memcache :param timeout: ttl in memcache """ key = md5hash(key) if timeout > 0: timeout += time.tim...
def set(self, key, value, serialize=True, timeout=0): :param key: key :param value: value :param serialize: if True, value is serialized with JSON before sending to memcache, or with pickle if configured to use pickle instead of JSON (to avoid...
def set(self, key, value, serialize=True, timeout=0): def get(self, key): """ Gets the object specified by key. It will also unpickle the object before returning if it is pickled in memcache. :param key: key :returns: value of the key in memcache
def set(self, key, value, serialize=True, timeout=0): def get(self, key): """ Gets the object specified by key. It will also unserialize the object before returning if it is serialized in memcache with JSON, or if it is pickled and unpickling is allowed. :param key: key ...
def get(self, key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: value = pickle.loads(value) fp.readline() line = fp.readline().strip().split() ...
def get(self, key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: if self._allow_unpickle: value = pickle.loads(value) else: ...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring is used :param serialize: if True, value is pickled before se...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring is used :param serialize: if True, value is serialized with J...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): for key, value in mapping.iteritems(): key = md5hash(key) flags = 0 if serialize: value = pickle.dumps(value, PICKLE_PROTOCOL) flags |= PICKLE_FLAG msg += ('set %s...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): for key, value in mapping.iteritems(): key = md5hash(key) flags = 0 if serialize and self._allow_pickle: value = pickle.dumps(value, PICKLE_PROTOCOL) flags |= PICKLE_FLAG ...
def get_multi(self, keys, server_key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: value = pickle.loads(value) responses[line[1]] = value fp.re...
def get_multi(self, keys, server_key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: if self._allow_unpickle: value = pickle.loads(value) ...
class MemcacheMiddleware(object): def __init__(self, app, conf): self.app = app self.memcache_servers = conf.get('memcache_servers') if not self.memcache_servers: path = os.path.join(conf.get('swift_dir', '/etc/swift'), 'memcache.conf') ...
class MemcacheMiddleware(object): def __init__(self, app, conf): self.app = app self.memcache_servers = conf.get('memcache_servers') serialization_format = conf.get('memcache_serialization_support') if not self.memcache_servers or serialization_format is None: path = os....
def get(self, section, option): if section == 'memcache': if option == 'memcache_servers': return '1.2.3.4:5' else: raise NoOptionError(option) else:
def get(self, section, option): if section == 'memcache': if option == 'memcache_servers': return '1.2.3.4:5' elif option == 'memcache_serialization_support': return '2' else: raise NoOptionError(option) else:
def test_conf_set_no_read(self): exc = None try: app = memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5'}) except Exception, err: exc = err finally:
def test_conf_set_no_read(self): exc = None try: app = memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5', 'memcache_serialization_support': '2'}) except Exception, err: exc = err finally:
# Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License");
# -*- coding: utf8 -*- # Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License");
def test_set_get(self): self.assertEquals(memcache_client.get('some_key'), [1, 2, 3]) memcache_client.set('some_key', [4, 5, 6]) self.assertEquals(memcache_client.get('some_key'), [4, 5, 6]) self.assert_(float(mock.cache.values()[0][1]) == 0) esttimeout = time.time() + 10 ...
def test_set_get(self): self.assertEquals(memcache_client.get('some_key'), [1, 2, 3]) memcache_client.set('some_key', [4, 5, 6]) self.assertEquals(memcache_client.get('some_key'), [4, 5, 6]) memcache_client.set('some_key', ['simple str', 'utf8 str éà']) # As per http://wiki.opens...
def test_multi(self): self.assertEquals(memcache_client.get_multi(('some_key2', 'some_key1', 'not_exists'), 'multi_key'), [[4, 5, 6], [1, 2, 3], None]) if __name__ == '__main__': unittest.main()
def test_multi(self): self.assertEquals(memcache_client.get_multi(('some_key2', 'some_key1', 'not_exists'), 'multi_key'), [[4, 5, 6], [1, 2, 3], None]) def test_serialization(self): memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'], ...
from django.utils.text import ( from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import Variable, VariableDoesNotExist from .library import Library register = Library()
from django.utils.text import ( from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import VARIABLE_ATTRIBUTE_SEPARATOR from .library import Library register = Library()
def striptags(value): def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, behave like Variable(arg).resolve >>> _property_resolver(1)('abc') 'b'
def striptags(value): def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b'
def _property_resolver(arg): try: float(arg) except ValueError: return Variable(arg).resolve else: return itemgetter(arg)
def _property_resolver(arg): try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_': raise AttributeError('Access to private variables is forbidden.') parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): ...
def dictsort(value, arg): """ try: return sorted(value, key=_property_resolver(arg)) except (TypeError, VariableDoesNotExist): return ''
def dictsort(value, arg): """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return ''
def dictsortreversed(value, arg): """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (TypeError, VariableDoesNotExist): return ''
def dictsortreversed(value, arg): """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return ''
from django.template.defaultfilters import dictsort from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsort( [{'age': 23, 'name': 'Barbara-Ann'},
from django.template.defaultfilters import _property_resolver, dictsort from django.test import SimpleTestCase class User: password = 'abc' _private = 'private' @property def test_property(self): return 'cde' def test_method(self): """This is just a test method.""" class Funct...
class FunctionTests(SimpleTestCase): def test_dictsort_complex_sorting_key(self): """ Since dictsort uses template.Variable under the hood, it can sort on keys like 'foo.bar'. """ data = [
class FunctionTests(SimpleTestCase): def test_dictsort_complex_sorting_key(self): """ Since dictsort uses dict.get()/getattr() under the hood, it can sort on keys like 'foo.bar'. """ data = [
class FunctionTests(SimpleTestCase): self.assertEqual(dictsort('Hello!', 'age'), '') self.assertEqual(dictsort({'a': 1}, 'age'), '') self.assertEqual(dictsort(1, 'age'), '')
class FunctionTests(SimpleTestCase): self.assertEqual(dictsort('Hello!', 'age'), '') self.assertEqual(dictsort({'a': 1}, 'age'), '') self.assertEqual(dictsort(1, 'age'), '') def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" self.assertEqual(dict...
class FunctionTests(SimpleTestCase): self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '')
class FunctionTests(SimpleTestCase): self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '') def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" ...
from PIL import Image @pytest.mark.parametrize( "test_file", ["Tests/images/sgi_overrun_expandrowF04.bin", "Tests/images/sgi_crash.bin"], ) def test_crashes(test_file): with open(test_file, "rb") as f:
from PIL import Image @pytest.mark.parametrize( "test_file", [ "Tests/images/sgi_overrun_expandrowF04.bin", "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", ], ) def test_crashes(te...
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...
class AsyncClientMixin(object): low['__user__'] = user low['__tag__'] = tag return self.low(fun, low, full_return=False) def cmd_async(self, low): '''
class AsyncClientMixin(object): low['__user__'] = user low['__tag__'] = tag try: return self.cmd_sync(low) except salt.exceptions.EauthAuthenticationError as exc: log.error(exc) def cmd_async(self, low): '''
class ClearFuncs(TransportMethods): ''' Send a master control function back to the wheel system ''' # All wheel ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
class ClearFuncs(TransportMethods): ''' Send a master control function back to the wheel system ''' jid = clear_load.get('__jid__', salt.utils.jid.gen_jid(self.opts)) # All wheel ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(c...
class ClearFuncs(TransportMethods): if error: # Authentication error occurred: do not continue. return {'error': error} # Authorize
class ClearFuncs(TransportMethods): if error: # Authentication error occurred: do not continue. data = {'error': error, 'jid': jid} self.event.fire_event(data, tagify([jid, "new"], "wheel")) return {'error': error} # Authorize
class ClearFuncs(TransportMethods): clear_load.get('kwarg', {}) ) if not wheel_check: return {'error': {'name': err_name, 'message': 'Authentication failure of type "{0}" occurred for ' ...
class ClearFuncs(TransportMethods): clear_load.get('kwarg', {}) ) if not wheel_check: err_data = { 'name': err_name, 'message': 'Authentication failure of type "{0}" occurred for ' 'user {1}.'.format(auth...
class ClearFuncs(TransportMethods): # Authorized. Do the job! try: jid = salt.utils.jid.gen_jid(self.opts) fun = clear_load.pop('fun') tag = tagify(jid, prefix='wheel') data = {'fun': "wheel.{0}".format(fun),
class ClearFuncs(TransportMethods): # Authorized. Do the job! try: fun = clear_load.pop('fun') tag = tagify(jid, prefix='wheel') data = {'fun': "wheel.{0}".format(fun),
class WheelClient(salt.client.mixins.SyncClientMixin, }) {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'} ''' fun = low.pop('fun') return self.asynchronous(fun, low) def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, fu...
class WheelClient(salt.client.mixins.SyncClientMixin, }) {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'} ''' fun = low.get('fun') return self.asynchronous(fun, low) def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, fu...
class NetapiClientTest(TestCase): def test_wheel_async(self): # Give this test a little breathing room time.sleep(3) low = {'client': 'wheel_async', 'fun': 'key.list_all'} low.update(self.eauth_creds) ret = self.netapi.run(low) self.assertIn('jid', ret) self....
class NetapiClientTest(TestCase): def test_wheel_async(self): # Give this test a little breathing room time.sleep(3) timeout = 60 opts = salt.config.master_config(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'master')) with salt.utils.event.get_event("master", opts=opts) as event:...
class HMACKey(Key): invalid_strings = [ b'-----BEGIN PUBLIC KEY-----', b'-----BEGIN CERTIFICATE-----', b'ssh-rsa' ]
class HMACKey(Key): invalid_strings = [ b'-----BEGIN PUBLIC KEY-----', b'-----BEGIN RSA PUBLIC KEY-----', b'-----BEGIN CERTIFICATE-----', b'ssh-rsa' ]
class TestHMACAlgorithm: with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN CERTIFICATE-----" with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256)
class TestHMACAlgorithm: with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN RSA PUBLIC KEY-----" with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN CERTIFICATE-----" with pytest.raises(JOSEError):...
def read_file(cls, file_path, config_name): with open(file_path) as file_stream: return file_stream.read() def read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False, ) -> List[jinja2.Template]: ...
def read_file(cls, file_path, config_name): with open(file_path) as file_stream: return file_stream.read() def read_template(self, filename: str) -> jinja2.Template: """Load a template file from disk. This function will attempt to load the given template from the default Synaps...
def read_templates( template directory. If `custom_template_directory` is supplied, that directory is tried first. Files read are treated as Jinja templates. These templates are not rendered yet. Args: filenames: A list of template filenames to read.
def read_templates( template directory. If `custom_template_directory` is supplied, that directory is tried first. Files read are treated as Jinja templates. The templates are not rendered yet and have autoescape enabled. Args: filenames: A list of template filename...
def read_templates( custom_template_directory: A directory to try to look for the templates before using the default Synapse template directory instead. autoescape: Whether to autoescape variables before inserting them into the template. Raises: ...
def read_templates( custom_template_directory: A directory to try to look for the templates before using the default Synapse template directory instead. Raises: ConfigError: if the file's path is incorrect or otherwise cannot be read. Returns: A list...
def read_templates( search_directories.insert(0, custom_template_directory) loader = jinja2.FileSystemLoader(search_directories) env = jinja2.Environment(loader=loader, autoescape=autoescape) # Update the environment with our custom filters env.filters.update(
def read_templates( search_directories.insert(0, custom_template_directory) loader = jinja2.FileSystemLoader(search_directories) env = jinja2.Environment(loader=loader, autoescape=jinja2.select_autoescape(),) # Update the environment with our custom filters env.filters.upda...
def read_templates( } ) for filename in filenames: # Load the template template = env.get_template(filename) templates.append(template) return templates def _format_ts_filter(value: int, format: str):
def read_templates( } ) # Load the templates return [env.get_template(filename) for filename in filenames] def _format_ts_filter(value: int, format: str):
def read_config(self, config, **kwargs): "recaptcha_siteverify_api", "https://www.recaptcha.net/recaptcha/api/siteverify", ) self.recaptcha_template = self.read_templates( ["recaptcha.html"], autoescape=True )[0] def generate_config_section(self, **kwargs...
def read_config(self, config, **kwargs): "recaptcha_siteverify_api", "https://www.recaptcha.net/recaptcha/api/siteverify", ) self.recaptcha_template = self.read_template("recaptcha.html") def generate_config_section(self, **kwargs): return """\
def __init__(self, *args): def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if consent_config is None: return
def __init__(self, *args): def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_template("terms.html") if consent_config is None: return
def read_config(self, config, **kwargs): self.session_lifetime = session_lifetime # The success template used during fallback auth. self.fallback_success_template = self.read_templates( ["auth_success.html"], autoescape=True )[0] def generate_config_section(self, genera...
def read_config(self, config, **kwargs): self.session_lifetime = session_lifetime # The success template used during fallback auth. self.fallback_success_template = self.read_template("auth_success.html") def generate_config_section(self, generate_secrets=False, **kwargs): if gener...
def make_unsubscribe_link( def safe_markup(raw_html: str) -> jinja2.Markup: return jinja2.Markup( bleach.linkify( bleach.clean(
def make_unsubscribe_link( def safe_markup(raw_html: str) -> jinja2.Markup: """ Sanitise a raw HTML string to a set of allowed tags and attributes, and linkify any bare URLs. Args raw_html: Unsafe HTML. Returns: A Markup object ready to safely use in a Jinja template. """ ret...
def safe_markup(raw_html: str) -> jinja2.Markup: def safe_text(raw_text: str) -> jinja2.Markup: """ Process text: treat it as HTML but escape any tags (ie. just escape the HTML) then linkify it. """ return jinja2.Markup( bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=Fa...
def safe_markup(raw_html: str) -> jinja2.Markup: def safe_text(raw_text: str) -> jinja2.Markup: """ Sanitise text (escape any HTML tags), and then linkify any bare URLs. Args raw_text: Unsafe text which might include HTML markup. Returns: A Markup object ready to safely use in a Jinja...
class WrappedRequest(object): return name in self.request.headers def get_header(self, name, default=None): return to_native_str(self.request.headers.get(name, default)) def header_items(self): return [ (to_native_str(k), [to_native_str(x) for x in v]) for k, v ...
class WrappedRequest(object): return name in self.request.headers def get_header(self, name, default=None): return to_native_str(self.request.headers.get(name, default), errors='replace') def header_items(self): return [ (to_native_str(k, errors...
class WrappedResponse(object): # python3 cookiejars calls get_all def get_all(self, name, default=None): return [to_native_str(v) for v in self.response.headers.getlist(name)] # python2 cookiejars calls getheaders getheaders = get_all
class WrappedResponse(object): # python3 cookiejars calls get_all def get_all(self, name, default=None): return [to_native_str(v, errors='replace') for v in self.response.headers.getlist(name)] # python2 cookiejars calls getheaders getheaders = get_all
class CookiesMiddlewareTest(TestCase): del self.mw def test_basic(self): headers = {'Set-Cookie': 'C1=value1; path=/'} req = Request('http://scrapytest.org/') assert self.mw.process_request(req, self.spider) is None assert 'Cookie' not in req.headers res = Response(...
class CookiesMiddlewareTest(TestCase): del self.mw def test_basic(self): req = Request('http://scrapytest.org/') assert self.mw.process_request(req, self.spider) is None assert 'Cookie' not in req.headers headers = {'Set-Cookie': 'C1=value1; path=/'} res = Response(...
class core(task.Config): class WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler() def create_remote_scheduler(self, host, port): return rpc.RemoteScheduler(host=host, port=port)
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, host, port): return rpc.RemoteScheduler(host=host, port=port)
class scheduler(Config): visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph')) def fix_time(x): # Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled state might store datetime objects
class scheduler(Config): visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph')) prune_on_get_work = parameter.BoolParameter(default=False) def fix_time(x): # Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled stat...
class Worker(object): def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.last_active = last_active # seconds since epoch self.started = time.time() ...
class Worker(object): def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.last_active = last_active or time.time() # seconds since epoch self.started...
class CentralPlannerScheduler(Scheduler): # TODO: remove tasks that can't be done, figure out if the worker has absolutely # nothing it can wait for worker_id = kwargs['worker'] # Return remaining tasks that have no FAILED descendents self.update(worker_id, {'host': host})
class CentralPlannerScheduler(Scheduler): # TODO: remove tasks that can't be done, figure out if the worker has absolutely # nothing it can wait for if self._config.prune_on_get_work: self.prune() worker_id = kwargs['worker'] # Return remaining tasks that have no FA...