buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_bp_middleware(app): assert response.status == 200 assert response.text == "FAIL" def test_bp_exception_handler(app): blueprint = Blueprint("test_middleware")
def test_bp_middleware(app): assert response.status == 200 assert response.text == "FAIL" def test_bp_middleware_order(app): blueprint = Blueprint("test_bp_middleware_order") order = list() @blueprint.middleware("request") def mw_1(request): order.append(1) @blueprint.middleware("re...
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "templates/utf8.html", "test.crt", "test.key",
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "static_foo.txt", "templates/utf8.html", "test.crt", "test.key",
class StaticFileTest(WebTestCase): response = self.get_and_head('/static/blarg') self.assertEqual(response.code, 404) @wsgi_safe class StaticDefaultFilenameTest(WebTestCase):
class StaticFileTest(WebTestCase): response = self.get_and_head('/static/blarg') self.assertEqual(response.code, 404) def test_path_traversal_protection(self): with ExpectLog(gen_log, ".*not in root static directory"): response = self.get_and_head('/static/../static_foo.txt') ...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ root = os.path.abspath(root) # os.path.abspath strips a trailing / # it needs to be temporarily added back for requests to root/ if not (absolute_path + os.path.sep).startswith(root): raise HT...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ # os.path.abspath strips a trailing /. # We must add it back to `root` so that we only match files # in a directory named `root` instead of files starting with # that prefix. root = os.path.abspat...
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 assert_series_equal( f"is not equal to {right._values}." ) raise AssertionError(msg) elif is_interval_dtype(left.dtype) or is_interval_dtype(right.dtype): assert_interval_array_equal(left.array, right.array) elif is_categorical_dtype(left.dtype) or is_categori...
def assert_series_equal( f"is not equal to {right._values}." ) raise AssertionError(msg) elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype): assert_interval_array_equal(left.array, right.array) elif is_categorical_dtype(left.dtype) or is_categor...
def assert_series_equal( check_dtype=check_dtype, obj=str(obj), ) elif is_extension_array_dtype(left.dtype) or is_extension_array_dtype(right.dtype): assert_extension_array_equal(left._values, right._values) elif needs_i8_conversion(left.dtype) or needs_i8_conversion(righ...
def assert_series_equal( check_dtype=check_dtype, obj=str(obj), ) elif is_extension_array_dtype(left.dtype) and is_extension_array_dtype(right.dtype): assert_extension_array_equal(left._values, right._values) elif needs_i8_conversion(left.dtype) or needs_i8_conversion(rig...
import pytest from pandas import DataFrame import pandas._testing as tm
import pytest import pandas as pd from pandas import DataFrame import pandas._testing as tm
def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture): msg = msg.format(obj=obj_fixture) with pytest.raises(AssertionError, match=msg): tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture)
def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture): msg = msg.format(obj=obj_fixture) with pytest.raises(AssertionError, match=msg): tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) def test_assert_frame_equal_extension_dtype_mismatch(): # http...
import pytest from pandas import Categorical, DataFrame, Series import pandas._testing as tm
import pytest import pandas as pd from pandas import Categorical, DataFrame, Series import pandas._testing as tm
ordered=False\\)""" _assert_series_equal_both(s1, s2, check_categorical=check_categorical) def test_series_equal_series_type(): class MySeries(Series): pass
ordered=False\\)""" _assert_series_equal_both(s1, s2, check_categorical=check_categorical) def test_assert_series_equal_extension_dtype_mismatch(): # https://github.com/pandas-dev/pandas/issues/32747 left = Series(pd.array([1, 2, 3], dtype="Int64")) right = left.astype(int) msg = """Attribute...
def set_user_password(self, context, user_id, user): def update_user_tenant(self, context, user_id, user): """Update the default tenant.""" # ensure that we're a member of that tenant tenant_id = user.get('tenantId') self.identity_api.add_user_to_tenant(context, tenant_id, user_id)
def set_user_password(self, context, user_id, user): def update_user_tenant(self, context, user_id, user): """Update the default tenant.""" self.assert_admin(context) # ensure that we're a member of that tenant tenant_id = user.get('tenantId') self.identity_api.add_user_to_t...
def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.floatx())
def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): # flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,) return K.cast(K.equal(K.flatten(y_true), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.fl...
def test_sparse_metrics(): assert K.eval(metric(y_a, y_b)).shape == (6,) def test_serialize(): '''This is a mock 'round trip' of serialize and deserialize. '''
def test_sparse_metrics(): assert K.eval(metric(y_a, y_b)).shape == (6,) @keras_test def test_sparse_categorical_accuracy_correctness(): y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx()) y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx()) # use one_hot embedding to convert...
def na_logical_op(x: np.ndarray, y, op): assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype)) x = ensure_object(x) y = ensure_object(y) result = libops.vec_binop(x, y, op) else: # let null fall thru assert lib.is_scalar(y)
def na_logical_op(x: np.ndarray, y, op): assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype)) x = ensure_object(x) y = ensure_object(y) result = libops.vec_binop(x.ravel(), y.ravel(), op) else: # let null fall thru assert lib.is_s...
def na_logical_op(x: np.ndarray, y, op): f"and scalar of type [{typ}]" ) return result def logical_op(
def na_logical_op(x: np.ndarray, y, op): f"and scalar of type [{typ}]" ) return result.reshape(x.shape) def logical_op(
def wrapped(self, *args, **kwargs): try: try: return_tuple = func(self, *args, **kwargs) display.vvv(return_tuple, host=self.host) # 0 = success # 1-254 = remote command return code # 255 coul...
def wrapped(self, *args, **kwargs): try: try: return_tuple = func(self, *args, **kwargs) if self._play_context.no_log: display.vvv('rc=%s, stdout & stderr censored due to no log' % return_tuple[0], host=self.host) ...
def wrapped(self, *args, **kwargs): break if SSH_ERROR: raise AnsibleConnectionFailure("Failed to connect to the host via ssh: %s" % to_native(return_tuple[2])) break
def wrapped(self, *args, **kwargs): break if SSH_ERROR: msg = "Failed to connect to the host via ssh: " if self._play_context.no_log: msg += '<error censored due to no log>' ...
class Block(PandasObject): mask = missing.mask_missing(values, to_replace) if not mask.any(): if inplace: return [self] return [self.copy()] try: blocks = self.putmask(mask, value, inplace=inplace) # Note: it is _not_ the case th...
class Block(PandasObject): mask = missing.mask_missing(values, to_replace) try: blocks = self.putmask(mask, value, inplace=inplace) # Note: it is _not_ the case that self._can_hold_element(value)
class TestDataFrameReplace: ) with pytest.raises(TypeError, match=msg): df.replace(lambda x: x.strip())
class TestDataFrameReplace: ) with pytest.raises(TypeError, match=msg): df.replace(lambda x: x.strip()) @pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"]) @pytest.mark.parametrize("value", [np.nan, pd.NA]) def test_replace_no_replacement_dtypes(...
class AnsibleModule(object): if k not in self.argument_spec: self.argument_spec[k] = v self._load_params() self._set_fallbacks()
class AnsibleModule(object): if k not in self.argument_spec: self.argument_spec[k] = v # Save parameter values that should never be logged self.no_log_values = set() self._load_params() self._set_fallbacks()
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) # Save parameter values that should never be logged self.no_log_values = set() self._handle_no_log_values() # check the locale as set by the curr...
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) self._handle_no_log_values() # check the locale as set by the current environment, and reset to
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) if pre is True: # this prevents setting defaults on required items if default is not None and k not in param: para...
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) # This prevents setting defaults on required items on the 1st run, # otherwise will set things without a default to None on the 2nd. if k not...
class AnsibleModule(object): else: fallback_args = item try: param[k] = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue def _load_params(self): '...
class AnsibleModule(object): else: fallback_args = item try: fallback_value = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue else: ...
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62) MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62) MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\ MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67) MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MS...
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62) MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62) MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\ MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67) HIGHEST_USERAUTH_MESSAGE_ID = 79 MSG_GLOBAL...
from paramiko.common import xffffffff, cMSG_CHANNEL_OPEN, cMSG_IGNORE, \ MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, \ MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, \ MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, \ MAX_WINDOW_SIZE, DEF...
from paramiko.common import xffffffff, cMSG_CHANNEL_OPEN, cMSG_IGNORE, \ MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, \ MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, \ MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, \ MAX_WINDOW_SIZE, DEF...
class Transport (threading.Thread, ClosingContextManager): max_packet_size = self.default_max_packet_size return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE) def run(self): # (use the exposed "run" method, because if we specify a thread target
class Transport (threading.Thread, ClosingContextManager): max_packet_size = self.default_max_packet_size return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE) def _ensure_authed(self, ptype, message): """ Checks message type against current auth state. ...
class Transport (threading.Thread, ClosingContextManager): continue if ptype in self._handler_table: self._handler_table[ptype](self, m) elif ptype in self._channel_handler_table: chanid = m.get_int() ...
class Transport (threading.Thread, ClosingContextManager): continue if ptype in self._handler_table: error_msg = self._ensure_authed(ptype, m) if error_msg: self._send_message(error_msg) ...
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") ...
def repercent_broken_unicode(path): we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode('utf-8') except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") pa...
def repercent_broken_unicode(path): we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode('utf-8') except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used...
from __future__ import unicode_literals import datetime import unittest from django.utils import six from django.utils.encoding import ( escape_uri_path, filepath_to_uri, force_bytes, force_text, iri_to_uri, smart_text, uri_to_iri, ) from django.utils.functional import SimpleLazyObject from django.utils.http ...
from __future__ import unicode_literals import datetime import sys import unittest from django.utils import six from django.utils.encoding import ( escape_uri_path, filepath_to_uri, force_bytes, force_text, iri_to_uri, repercent_broken_unicode, smart_text, uri_to_iri, ) from django.utils.functional import Sim...
class TestEncodingUtils(unittest.TestCase): self.assertEqual(smart_text(1), '1') self.assertEqual(smart_text('foo'), 'foo') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(unittest.TestCase): self.assertEqual(smart_text(1), '1') self.assertEqual(smart_text('foo'), 'foo') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested # function uses recursion. ...
def debug_build(program): program = os.path.basename(program) name = os.path.splitext(program)[0] return name.endswith("_d") def remove_python_envvars():
def debug_build(program): program = os.path.basename(program) name = os.path.splitext(program)[0] return name.casefold().endswith("_d".casefold()) def remove_python_envvars():
def get_expected_config(self, expected_preconfig, expected, env, api, if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG: expected['stdio_errors'] = 'surrogateescape' if sys.platform == 'win32': default_executable = self.test_exe elif expected['program_name']...
def get_expected_config(self, expected_preconfig, expected, env, api, if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG: expected['stdio_errors'] = 'surrogateescape' if MS_WINDOWS: default_executable = self.test_exe elif expected['program_name'] is not self....
def check_pre_config(self, configs, expected): pre_config = dict(configs['pre_config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: del pre_config[key] del expected[key] self.assertEqual(pre_config, expected)
def check_pre_config(self, configs, expected): pre_config = dict(configs['pre_config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: pre_config.pop(key, None) del expected[key] self.assertEqual(pre_config, expected)
def check_config(self, configs, expected): config = dict(configs['config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: del config[key] del expected[key] self.assertEqual(config, expected)
def check_config(self, configs, expected): config = dict(configs['config']) for key, value in list(expected.items()): if value is self.IGNORE_CONFIG: config.pop(key, None) del expected[key] self.assertEqual(config, expected)
def check_all_configs(self, testname, expected_config=None, self.check_pre_config(configs, expected_preconfig) self.check_config(configs, expected_config) self.check_global_config(configs) def test_init_default_config(self): self.check_all_configs("test_init_initialize_config", api=...
def check_all_configs(self, testname, expected_config=None, self.check_pre_config(configs, expected_preconfig) self.check_config(configs, expected_config) self.check_global_config(configs) return configs def test_init_default_config(self): self.check_all_configs("test_init_i...
def test_init_setpath(self): } self.default_program_name(config) env = {'TESTPATH': os.path.pathsep.join(paths)} self.check_all_configs("test_init_setpath", config, api=API_COMPAT, env=env, ignore_stderr=True)
def test_init_setpath(self): } self.default_program_name(config) env = {'TESTPATH': os.path.pathsep.join(paths)} self.check_all_configs("test_init_setpath", config, api=API_COMPAT, env=env, ignore_stderr=True)
def tmpdir_with_python(self): # Copy pythonXY.dll (or pythonXY_d.dll) ver = sys.version_info dll = f'python{ver.major}{ver.minor}' if debug_build(sys.executable): dll += '_d' dll += '.dll' dll = os.path.j...
def tmpdir_with_python(self): # Copy pythonXY.dll (or pythonXY_d.dll) ver = sys.version_info dll = f'python{ver.major}{ver.minor}' dll3 = f'python{ver.major}' if debug_build(sys.executable): dll += '_d' ...
def test_init_pyvenv_cfg(self): config['base_prefix'] = pyvenv_home config['prefix'] = pyvenv_home env = self.copy_paths_by_env(config) self.check_all_configs("test_init_compat_config", config, api=API_COMPAT, env=env, ...
def test_init_pyvenv_cfg(self): config['base_prefix'] = pyvenv_home config['prefix'] = pyvenv_home env = self.copy_paths_by_env(config) actual = self.check_all_configs("test_init_compat_config", config, api=API_COMPAT, e...
def find_meta(meta): package_dir={"": "src"}, install_requires=[ # Fix cryptographyMinimum in tox.ini when changing this! "cryptography>=1.9", "six>=1.5.2" ], extras_require={
def find_meta(meta): package_dir={"": "src"}, install_requires=[ # Fix cryptographyMinimum in tox.ini when changing this! "cryptography>=2.1.4", "six>=1.5.2" ], extras_require={
def __init__(self, callback): @wraps(callback) def wrapper(ok, store_ctx): cert = X509.__new__(X509) cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx) error_number = _lib.X509_STORE_CTX_get_error(store_ctx) error_depth = _lib.X509_STORE_CTX_get...
def __init__(self, callback): @wraps(callback) def wrapper(ok, store_ctx): x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx) _lib.X509_up_ref(x509) cert = X509._from_raw_x509_ptr(x509) error_number = _lib.X509_STORE_CTX_get_error(store_ctx) ...
def load_pkcs12(buffer, passphrase=None): pycert = None friendlyname = None else: pycert = X509.__new__(X509) pycert._x509 = _ffi.gc(cert[0], _lib.X509_free) friendlyname_length = _ffi.new("int*") friendlyname_buffer = _lib.X509_alias_get0(
def load_pkcs12(buffer, passphrase=None): pycert = None friendlyname = None else: pycert = X509._from_raw_x509_ptr(cert[0]) friendlyname_length = _ffi.new("int*") friendlyname_buffer = _lib.X509_alias_get0(
def load_pkcs12(buffer, passphrase=None): pycacerts = [] for i in range(_lib.sk_X509_num(cacerts)): pycacert = X509.__new__(X509) pycacert._x509 = _lib.sk_X509_value(cacerts, i) pycacerts.append(pycacert) if not pycacerts: pycacerts = None
def load_pkcs12(buffer, passphrase=None): pycacerts = [] for i in range(_lib.sk_X509_num(cacerts)): x509 = _lib.sk_X509_value(cacerts, i) pycacert = X509._from_raw_x509_ptr(x509) pycacerts.append(pycacert) if not pycacerts: pycacerts = None
def callback(self, connection, *args): assert verify.connection is clientConnection def test_set_verify_callback_exception(self): """ If the verify callback passed to `Context.set_verify` raises an
def callback(self, connection, *args): assert verify.connection is clientConnection def test_x509_in_verify_works(self): """ We had a bug where the X509 cert instantiated in the callback wrapper didn't __init__ so it was missing objects needed when calling get_subject. This...
def test_osx_proxy_bypass(self): bypass = {'exclude_simple': True, 'exceptions': []} self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) def test_basic_auth(self, quote_char='"'): opener = OpenerDirector() password_manager = MockPasswordManager() auth_handler = url...
def test_osx_proxy_bypass(self): bypass = {'exclude_simple': True, 'exceptions': []} self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) def check_basic_auth(self, headers, realm): with self.subTest(realm=realm, headers=headers): opener = OpenerDirector() p...
class AbstractBasicAuthHandler: # allow for double- and single-quoted realm values # (single quotes are a violation of the RFC, but appear in the wild) rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' 'realm=(["\']?)([^"\']*)\\2', re.I) # XXX could pre-emptively send auth info alrea...
class AbstractBasicAuthHandler: # allow for double- and single-quoted realm values # (single quotes are a violation of the RFC, but appear in the wild) rx = re.compile('(?:^|,)' # start of the string or ',' '[ \t]*' # optional whitespaces '([^ \t]+)' # scheme li...
def __init__(self, password_mgr=None): self.passwd = password_mgr self.add_password = self.passwd.add_password def http_error_auth_reqed(self, authreq, host, req, headers): # host may be an authority (without userinfo) or a URL with an # authority # XXX could be multiple hea...
def __init__(self, password_mgr=None): self.passwd = password_mgr self.add_password = self.passwd.add_password def _parse_realm(self, header): # parse WWW-Authenticate header: accept multiple challenges per header found_challenge = False for mo in AbstractBasicAuthHandler.rx...
class TestYoutubeDL(unittest.TestCase): 'extractor': 'TEST', 'duration': 30, 'filesize': 10 * 1024, } second = { 'id': '2',
class TestYoutubeDL(unittest.TestCase): 'extractor': 'TEST', 'duration': 30, 'filesize': 10 * 1024, 'playlist_id': '42', } second = { 'id': '2',
class TestYoutubeDL(unittest.TestCase): 'duration': 10, 'description': 'foo', 'filesize': 5 * 1024, } videos = [first, second]
class TestYoutubeDL(unittest.TestCase): 'duration': 10, 'description': 'foo', 'filesize': 5 * 1024, 'playlist_id': '43', } videos = [first, second]
class TestYoutubeDL(unittest.TestCase): res = get_videos(f) self.assertEqual(res, ['1']) def test_playlist_items_selection(self): entries = [{ 'id': compat_str(i),
class TestYoutubeDL(unittest.TestCase): res = get_videos(f) self.assertEqual(res, ['1']) f = match_filter_func('playlist_id = 42') res = get_videos(f) self.assertEqual(res, ['1']) def test_playlist_items_selection(self): entries = [{ 'id': compat_str(i),
def _match_one(filter_part, dct): m = operator_rex.search(filter_part) if m: op = COMPARISON_OPERATORS[m.group('op')] if m.group('strval') is not None: if m.group('op') not in ('=', '!='): raise ValueError( 'Operator %s does not support string valu...
def _match_one(filter_part, dct): m = operator_rex.search(filter_part) if m: op = COMPARISON_OPERATORS[m.group('op')] actual_value = dct.get(m.group('key')) if (m.group('strval') is not None or # If the original field is a string and matching comparisonvalue is # ...
def _match_one(filter_part, dct): raise ValueError( 'Invalid integer value %r in filter part %r' % ( m.group('intval'), filter_part)) actual_value = dct.get(m.group('key')) if actual_value is None: return m.group('none_i...
def _match_one(filter_part, dct): raise ValueError( 'Invalid integer value %r in filter part %r' % ( m.group('intval'), filter_part)) if actual_value is None: return m.group('none_inclusive') return op(actual_value, comp...
class PeriodicCallback(object): self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) def _update_next(self, current_time): if self._next_timeout <= current_time: callback_time_sec = self.callback_time / 1000.0 self._next_timeout += (math.floor((current...
class PeriodicCallback(object): self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) def _update_next(self, current_time): callback_time_sec = self.callback_time / 1000.0 if self._next_timeout <= current_time: # The period should be measured from the start...
class TestPeriodicCallbackMath(unittest.TestCase): def simulate_calls(self, pc, durations): """Simulate a series of calls to the PeriodicCallback. Pass a list of call durations in seconds. This method returns the times at which each call would be made. """ calls = [] ...
class TestPeriodicCallbackMath(unittest.TestCase): def simulate_calls(self, pc, durations): """Simulate a series of calls to the PeriodicCallback. Pass a list of call durations in seconds (negative values work to simulate clock adjustments during the call, or more or less equivalent...
class TestPeriodicCallbackMath(unittest.TestCase): self.assertEqual(self.simulate_calls(pc, call_durations), expected) class TestIOLoopConfiguration(unittest.TestCase): def run_python(self, *statements):
class TestPeriodicCallbackMath(unittest.TestCase): self.assertEqual(self.simulate_calls(pc, call_durations), expected) def test_clock_backwards(self): pc = PeriodicCallback(None, 10000) # Backwards jumps are ignored, potentially resulting in a # slightly slo...
class Categorical(ExtensionArray, PandasObject): raise ValueError("fill value must be in categories") values_codes = _get_codes_for_values(value, self.categories) indexer = np.where(values_codes != -1) codes[indexer] = values_codes[values_codes != -1]...
class Categorical(ExtensionArray, PandasObject): raise ValueError("fill value must be in categories") values_codes = _get_codes_for_values(value, self.categories) indexer = np.where(codes == -1) codes[indexer] = values_codes[indexer] # If...
class TestSeriesMissingData: exp = Series(Categorical(expected_output, categories=["a", "b"])) tm.assert_series_equal(s.fillna(fill_value), exp) def test_fillna_categorical_raise(self): data = ["a", np.nan, "b", np.nan, np.nan] s = Series(Categorical(data, categories=["a", "b"]))
class TestSeriesMissingData: exp = Series(Categorical(expected_output, categories=["a", "b"])) tm.assert_series_equal(s.fillna(fill_value), exp) @pytest.mark.parametrize( "fill_value, expected_output", [ (Series(["a", "b", "c", "d", "e"]), ["a", "b", "b", "d", "e"]), ...
def array_equivalent(left, right, strict_nan=False): if not isinstance(right_value, float) or not np.isnan(right_value): return False else: if np.any(left_value != right_value): return False return True # NaNs can occur in ...
def array_equivalent(left, right, strict_nan=False): if not isinstance(right_value, float) or not np.isnan(right_value): return False else: try: if np.any(left_value != right_value): return False ...
class Index(IndexOpsMixin, PandasObject): # if other is not object, use other's logic for coercion return other.equals(self) try: return array_equivalent( com.values_from_object(self), com.values_from_object(other) ) except Exception: ...
class Index(IndexOpsMixin, PandasObject): # if other is not object, use other's logic for coercion return other.equals(self) return array_equivalent( com.values_from_object(self), com.values_from_object(other) ) def identical(self, other): """
import pandas as pd from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range from pandas.util import testing as tm @pytest.mark.parametrize("notna_f", [notna, notnull]) def test_notna_notnull(notna_f):
import pandas as pd from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range from pandas.util import testing as tm now = pd.Timestamp.now() utcnow = pd.Timestamp.now("UTC") @pytest.mark.parametrize("notna_f", [notna, notnull]) def test_notna_notnull(notna_f):
def test_array_equivalent(): assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan])) def test_array_equivalent_compat(): # see gh-13388 m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)])
def test_array_equivalent(): assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan])) @pytest.mark.parametrize( "lvalue, rvalue", [ # There are 3 variants for each of lvalue and rvalue. We include all # three for the tz-naive `now` and exclude the datetim64 var...
part 3</font></u> cli_bool_option( {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='), ['--check-certificate=true']) def test_ohdave_rsa_encrypt(self): N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3af...
part 3</font></u> cli_bool_option( {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='), ['--check-certificate=true']) self.assertEqual( cli_bool_option( {}, '--check-certificate', 'nocheckcertificat...
def cli_option(params, command_option, param): def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None): param = params.get(param) assert isinstance(param, bool) if separator: return [command_option + separator + (true_value if param else false_valu...
def cli_option(params, command_option, param): def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None): param = params.get(param) if param is None: return [] assert isinstance(param, bool) if separator: return [command_option + separato...
class MWorker(salt.utils.process.SignalHandlingProcess): """ log.trace("Clear payload received with command %s", load["cmd"]) cmd = load["cmd"] if cmd.startswith("__"): return False if self.opts["master_stats"]: start = time.time() self.stats[c...
class MWorker(salt.utils.process.SignalHandlingProcess): """ log.trace("Clear payload received with command %s", load["cmd"]) cmd = load["cmd"] method = self.clear_funcs.get_method(cmd) if not method: return {}, {"fun": "send_clear"} if self.opts["master_stats...
class MWorker(salt.utils.process.SignalHandlingProcess): return {} cmd = data["cmd"] log.trace("AES payload received with command %s", data["cmd"]) if cmd.startswith("__"): return False if self.opts["master_stats"]: start = time.time() self...
class MWorker(salt.utils.process.SignalHandlingProcess): return {} cmd = data["cmd"] log.trace("AES payload received with command %s", data["cmd"]) method = self.aes_funcs.get_method(cmd) if not method: return {}, {"fun": "send"} if self.opts["master_stats...
class MWorker(salt.utils.process.SignalHandlingProcess): self.__bind() # TODO: rename? No longer tied to "AES", just "encrypted" or "private" requests class AESFuncs(object): """ Set up functions that are available when the load is encrypted with AES """ # The AES Functions: # def __i...
class MWorker(salt.utils.process.SignalHandlingProcess): self.__bind() class TransportMethods(object): """ Expose methods to the transport layer, methods with their names found in the class attribute 'expose_methods' will be exposed to the transport layer via 'get_method'. """ expose_...
class AESFuncs(object): return ret, {"fun": "send"} class ClearFuncs(object): """ Set up functions that are safe to execute when commands sent to the master without encryption and authentication """ # The ClearFuncs object encapsulates the functions that can be executed in # the clear...
class AESFuncs(object): return ret, {"fun": "send"} class ClearFuncs(TransportMethods): """ Set up functions that are safe to execute when commands sent to the master without encryption and authentication """ # These methods will be exposed to the transport layer by # MWorker._handle_...
from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf class ClearFuncsTestCase(TestCase): """ TestCase for salt.master.ClearFuncs class
from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf class TransportMethodsTest(TestCase): def test_transport_methods(self): class Foo(salt.master.TransportMethods): expose_methods = ["bar"] def bar(self): pass ...
class ClearFuncsTestCase(TestCase): def tearDownClass(cls): del cls.clear_funcs # runner tests @skipIf(True, "SLOWTEST skip")
class ClearFuncsTestCase(TestCase): def tearDownClass(cls): del cls.clear_funcs def tearDown(self): del self.clear_funcs def test_get_method(self): assert getattr(self.clear_funcs, "_send_pub", None) is not None assert self.clear_funcs.get_method("_send_pub") is None #...
default 'raise' def _with_freq(self, freq): """ Helper to set our freq in-place, returning self to allow method chaining. Parameters ----------
default 'raise' def _with_freq(self, freq): """ Helper to get a view on the same data, with a new freq. Parameters ----------
default 'raise' Returns ------- self """ # GH#29843 if freq is None:
default 'raise' Returns ------- Same type as self """ # GH#29843 if freq is None:
default 'raise' assert freq == "infer" freq = frequencies.to_offset(self.inferred_freq) self._freq = freq return self class DatetimeLikeArrayMixin(
default 'raise' assert freq == "infer" freq = frequencies.to_offset(self.inferred_freq) arr = self.view() arr._freq = freq return arr class DatetimeLikeArrayMixin(
from pandas.core.indexes.numeric import Int64Index from pandas.core.ops import get_op_result_name from pandas.core.tools.timedeltas import to_timedelta from pandas.tseries.frequencies import DateOffset, to_offset from pandas.tseries.offsets import Tick _index_doc_kwargs = dict(ibase._index_doc_kwargs)
from pandas.core.indexes.numeric import Int64Index from pandas.core.ops import get_op_result_name from pandas.core.tools.timedeltas import to_timedelta from pandas.tseries.frequencies import DateOffset from pandas.tseries.offsets import Tick _index_doc_kwargs = dict(ibase._index_doc_kwargs)
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): return self.freq.freqstr def _with_freq(self, freq): index = self.copy(deep=False) if freq is None: # Even if we _can_ have a freq, we might want to set it to None index._freq = None elif len(se...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): return self.freq.freqstr def _with_freq(self, freq): arr = self._data._with_freq(freq) return type(self)._simple_new(arr, name=self.name) def _shallow_copy(self, values=None, name: Label = lib.no_default): name = ...
class TestDatetimeIndex: idx_p = tm.round_trip_pickle(idx) tm.assert_index_equal(idx, idx_p) def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): # GH7774 index = date_range("20130101", periods=3, tz="US/Eastern")
class TestDatetimeIndex: idx_p = tm.round_trip_pickle(idx) tm.assert_index_equal(idx, idx_p) def test_pickle_after_set_freq(self): dti = date_range("20130101", periods=3, tz="US/Eastern", name="foo") dti = dti._with_freq(None) res = tm.round_trip_pickle(dti) tm.asse...
class TestTimedeltaIndex(DatetimeLike): def test_pickle_compat_construction(self): pass def test_isin(self): index = tm.makeTimedeltaIndex(4)
class TestTimedeltaIndex(DatetimeLike): def test_pickle_compat_construction(self): pass def test_pickle_after_set_freq(self): tdi = timedelta_range("1 day", periods=4, freq="s") tdi = tdi._with_freq(None) res = tm.round_trip_pickle(tdi) tm.assert_index_equal(res, tdi) ...
class LoadAuth(object): if rm_tok: self.rm_token(tok) return tdata
class LoadAuth(object): if rm_tok: self.rm_token(tok) return {} return tdata
class SSHClient(object): # Salt API should never offer a custom roster! self.opts["__disable_custom_roster"] = disable_custom_roster def _prep_ssh( self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs ): """ Prepare the arguments """ ...
class SSHClient(object): # Salt API should never offer a custom roster! self.opts["__disable_custom_roster"] = disable_custom_roster def sanitize_kwargs(self, kwargs): roster_vals = [ ("host", str), ("ssh_user", str), ("ssh_passwd", str), ("ss...
class NetapiSSHClientAuthTest(SSHCase): except AssertionError: self.mod_case.run_function("user.delete", [self.USERA], remove=True) self.skipTest("Could not add user or password, skipping test") def tearDown(self): del self.netapi self.mod_case.run_function("user.del...
class NetapiSSHClientAuthTest(SSHCase): except AssertionError: self.mod_case.run_function("user.delete", [self.USERA], remove=True) self.skipTest("Could not add user or password, skipping test") self.expfile = os.path.join(RUNTIME_VARS.TMP, "exploited") def tearDown(self): ...
class NetapiSSHClientAuthTest(SSHCase): ret = self.netapi.run(low) assert "localhost" in ret assert ret["localhost"]["return"] is True
class NetapiSSHClientAuthTest(SSHCase): ret = self.netapi.run(low) assert "localhost" in ret assert ret["localhost"]["return"] is True def test_ssh_cve_2021_3197_a(self): assert not os.path.exists(self.expfile) low = { "eauth": "auto", "username": sel...
class scheduler(Config): # These disables last for disable_persist seconds. disable_window = parameter.IntParameter(default=3600, config_path=dict(section='scheduler', name='disable-window-seconds')) disable_failures = parameter.IntParameter(default=None, ...
class scheduler(Config): # These disables last for disable_persist seconds. disable_window = parameter.IntParameter(default=3600, config_path=dict(section='scheduler', name='disable-window-seconds')) disable_failures = parameter.IntParameter(default=999999999, ...
class Task(object): self.failures.add_failure() def has_excessive_failures(self): if (self.failures.first_failure_time is not None and self.disable_hard_timeout): if (time.time() >= self.failures.first_failure_time + self.disable_hard_timeout): ...
class Task(object): self.failures.add_failure() def has_excessive_failures(self): if self.failures.first_failure_time is not None: if (time.time() >= self.failures.first_failure_time + self.disable_hard_timeout): return True
class Task(object): return False def can_disable(self): return (self.disable_failures is not None or self.disable_hard_timeout is not None) @property def pretty_id(self): param_str = ', '.join('{}={}'.format(key, value) for key, value in self.params.items())
class Task(object): return False @property def pretty_id(self): param_str = ', '.join('{}={}'.format(key, value) for key, value in self.params.items())
class SimpleTaskState(object): elif task.scheduler_disable_time is not None and new_status != DISABLED: return if new_status == FAILED and task.can_disable() and task.status != DISABLED: task.add_failure() if task.has_excessive_failures(): tas...
class SimpleTaskState(object): elif task.scheduler_disable_time is not None and new_status != DISABLED: return if new_status == FAILED and task.status != DISABLED: task.add_failure() if task.has_excessive_failures(): task.scheduler_disable_tim...
class CentralPlannerTest(unittest.TestCase): self.assertEqual(set([]), set(self.sch.task_list(status, ''))) self.assertEqual(3, len(self.sch.task_list(None, ''))) # None == All statuses
class CentralPlannerTest(unittest.TestCase): self.assertEqual(set([]), set(self.sch.task_list(status, ''))) self.assertEqual(3, len(self.sch.task_list(None, ''))) # None == All statuses def test_no_crash_on_only_disable_hard_timeout(self): """ Scheduler shouldn't crash with on...
def _decryptRecord(self, recordType, b): if self.version >= (3,2): #For TLS 1.1, remove explicit IV b = b[self._readState.encContext.block_size : ] #Check padding paddingGood = True paddingLength = b[-1]
def _decryptRecord(self, recordType, b): if self.version >= (3,2): #For TLS 1.1, remove explicit IV b = b[self._readState.encContext.block_size : ] if len(b) == 0: for result in self._sendError(\ AlertDescription.decryp...
Various other classes in this module support this usage: from __future__ import division, absolute_import __metaclass__ = type from zope.interface import implementer from twisted.python.compat import networkString
Various other classes in this module support this usage: from __future__ import division, absolute_import __metaclass__ = type import re from zope.interface import implementer from twisted.python.compat import networkString
class HTTPClientParser(HTTPParser): @implementer(IClientRequest) class Request: """
class HTTPClientParser(HTTPParser): _VALID_METHOD = re.compile( br"\A[%s]+\Z" % ( bytes().join( ( b"!", b"#", b"$", b"%", b"&", b"'", b"*", b"+", b"-", b".", b"^", b"_", b"`", b"|", b"~", b"\x30-\x39", b"\x41-\x5a", ...
class Request: connection, defaults to C{False}. @type persistent: L{bool} """ self.method = method self.uri = uri self.headers = headers self.bodyProducer = bodyProducer self.persistent = persistent
class Request: connection, defaults to C{False}. @type persistent: L{bool} """ self.method = _ensureValidMethod(method) self.uri = _ensureValidURI(uri) self.headers = headers self.bodyProducer = bodyProducer self.persistent = persistent
class Request: # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append(b' '.join([self.method, self.uri, b'HTTP/1.1\r\n'])) if not self.persistent: requestLines...
class Request: # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append( b' '.join( [ _ensureValidMethod(self.method), _ensur...
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse from twisted.web.http_headers import Headers from twisted.logger import Logger class PartialDownloadError(error.Error): """
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse from twisted.web.http_headers import Headers from twisted.logger import Logger from twisted.web._newclient import _ensureValidURI, _ensureValidMethod class PartialDownloadError(error.Error): """
class HTTPPageGetter(http.HTTPClient): _completelyDone = True _specialHeaders = set((b'host', b'user-agent', b'cookie', b'content-length')) def connectionMade(self): method = getattr(self.factory, 'method', b'GET') self.sendCommand(method, self.factory.path) if self.factory.scheme...
class HTTPPageGetter(http.HTTPClient): _completelyDone = True _specialHeaders = set( (b'host', b'user-agent', b'cookie', b'content-length'), ) def connectionMade(self): method = _ensureValidMethod(getattr(self.factory, 'method', b'GET')) self.sendCommand(method, _ensureValidUR...
class HTTPClientFactory(protocol.ClientFactory): # just in case a broken http/1.1 decides to keep connection alive self.headers.setdefault(b"connection", b"close") self.postdata = postdata self.method = method self.setURL(url)
class HTTPClientFactory(protocol.ClientFactory): # just in case a broken http/1.1 decides to keep connection alive self.headers.setdefault(b"connection", b"close") self.postdata = postdata self.method = _ensureValidMethod(method) self.setURL(url)
class HTTPClientFactory(protocol.ClientFactory): return "<%s: %s>" % (self.__class__.__name__, self.url) def setURL(self, url): self.url = url uri = URI.fromBytes(url) if uri.scheme and uri.host:
class HTTPClientFactory(protocol.ClientFactory): return "<%s: %s>" % (self.__class__.__name__, self.url) def setURL(self, url): _ensureValidURI(url.strip()) self.url = url uri = URI.fromBytes(url) if uri.scheme and uri.host:
def _makeGetterFactory(url, factoryFactory, contextFactory=None, @return: The factory created by C{factoryFactory} """ uri = URI.fromBytes(url) factory = factoryFactory(url, *args, **kwargs) if uri.scheme == b'https': from twisted.internet import ssl
def _makeGetterFactory(url, factoryFactory, contextFactory=None, @return: The factory created by C{factoryFactory} """ uri = URI.fromBytes(_ensureValidURI(url.strip())) factory = factoryFactory(url, *args, **kwargs) if uri.scheme == b'https': from twisted.internet import ssl
class _AgentBase(object): if not isinstance(method, bytes): raise TypeError('method={!r} is {}, but must be bytes'.format( method, type(method))) # Create minimal headers, if necessary: if headers is None: headers = Headers()
class _AgentBase(object): if not isinstance(method, bytes): raise TypeError('method={!r} is {}, but must be bytes'.format( method, type(method))) method = _ensureValidMethod(method) # Create minimal headers, if necessary: if headers is None: ...
class Agent(_AgentBase): @see: L{twisted.web.iweb.IAgent.request} """ parsedURI = URI.fromBytes(uri) try: endpoint = self._getEndpoint(parsedURI)
class Agent(_AgentBase): @see: L{twisted.web.iweb.IAgent.request} """ uri = _ensureValidURI(uri.strip()) parsedURI = URI.fromBytes(uri) try: endpoint = self._getEndpoint(parsedURI)
class ProxyAgent(_AgentBase): """ Issue a new request via the configured proxy. """ # Cache *all* connections under the same key, since we are only # connecting to a single destination, the proxy: key = ("http-proxy", self._proxyEndpoint)
class ProxyAgent(_AgentBase): """ Issue a new request via the configured proxy. """ uri = _ensureValidURI(uri.strip()) # Cache *all* connections under the same key, since we are only # connecting to a single destination, the proxy: key = ("http-proxy", self._prox...