buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def namespace_facts(facts): ''' return all facts inside 'ansible_facts' w/o an ansible_ prefix ''' deprefixed = {} for k in facts: if k in ('ansible_local',): # exceptions to 'deprefixing' deprefixed[k] = module_response_deepcopy(facts[k]) else: deprefixed...
def namespace_facts(facts): ''' return all facts inside 'ansible_facts' w/o an ansible_ prefix ''' deprefixed = {} for k in facts: if k.startswith('ansible_') and k not in ('ansible_local',): deprefixed[k[8:]] = module_response_deepcopy(facts[k]) else: deprefixed[k] =...
def main(): 'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1', 'test/utils/shippable/timing.py', 'test/integration/targets/old_style_modules_posix/library/helloworld.sh', # Python 3-only. Only run by release engineers 'hacking/release-an...
def main(): 'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1', 'test/utils/shippable/timing.py', 'test/integration/targets/old_style_modules_posix/library/helloworld.sh', 'test/integration/targets/gathering_facts/library/bogus_facts', # P...
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import notna from pandas.core import algorithms from pandas.core.algorithms import unique
from pandas.core.dtypes.generic import ( ) from pandas.core.dtypes.missing import notna from pandas.arrays import IntegerArray from pandas.core import algorithms from pandas.core.algorithms import unique
def _convert_listlike_datetimes( elif unit is not None: if format is not None: raise ValueError("cannot specify both format and unit") arg = getattr(arg, "values", arg) result, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors) if errors == "ignore": ...
def _convert_listlike_datetimes( elif unit is not None: if format is not None: raise ValueError("cannot specify both format and unit") arg = getattr(arg, "_values", arg) # GH 30050 pass an ndarray to tslib.array_with_unit_to_datetime # because it expects an ndarray argum...
def test_should_cache_errors(unique_share, check_count, err_message): with pytest.raises(AssertionError, match=err_message): tools.should_cache(arg, unique_share, check_count)
def test_should_cache_errors(unique_share, check_count, err_message): with pytest.raises(AssertionError, match=err_message): tools.should_cache(arg, unique_share, check_count) def test_nullable_integer_to_datetime(): # Test for #30050 ser = pd.Series([1, 2, None, 2 ** 61, None]) ser = ser.ast...
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...
def test_match(wrong): assert match(Command(wrong, stderr=git_stash_err)) @pytest.mark.parametrize('wrong,fixed', [ ('git stash opp', 'git stash pop'), ('git stash Some message', 'git stash save Some message'),
def test_match(wrong): assert match(Command(wrong, stderr=git_stash_err)) def test_not_match(): assert not match(Command("git", stderr=git_stash_err)) @pytest.mark.parametrize('wrong,fixed', [ ('git stash opp', 'git stash pop'), ('git stash Some message', 'git stash save Some message'),
from thefuck.specific.git import git_support @git_support def match(command): return (command.script.split()[1] == 'stash' and 'usage:' in command.stderr) # git's output here is too complicated to be parsed (see the test file) stash_commands = (
from thefuck.specific.git import git_support @git_support def match(command): splited_script = command.script.split() if len(splited_script) > 1: return (splited_script[1] == 'stash' and 'usage:' in command.stderr) else: return False # git's output here is too complicated t...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError): pass asdt, reso = parse_time_string(key, self.freq)
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError, OverflowError): pass asdt, reso = parse_time_string(key, self.freq)
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): """ if isinstance(key, str): try: return self._get_string_slice(key) except (TypeError, KeyError, ValueError, OverflowError): pass try: asdt, r...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): """ if isinstance(key, str): try: loc = self._get_string_slice(key) return loc except (TypeError, ValueError): pass try: asdt,...
class TestIndexing: ps0 = [p0, p1, p2] idx0 = pd.PeriodIndex(ps0) for p in ps0: assert p in idx0 assert str(p) in idx0 assert "2017-09-01 00:00:01" in idx0 assert "2017-09" in idx0
class TestIndexing: ps0 = [p0, p1, p2] idx0 = pd.PeriodIndex(ps0) ser = pd.Series(range(6, 9), index=idx0) for p in ps0: assert p in idx0 assert str(p) in idx0 # GH#31172 # Higher-resolution period-like are _not_ considered as contained ...
def should_series_dispatch(left, right, op): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype): # in particular case where right is an array of DateOffsets return True return False
def should_series_dispatch(left, right, op): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if (is_datetime64_dtype(ldtype) and is_object_dtype(rdtype)) or ( is_datetime64_dtype(rdtype) and is_object_dtype(ldtype) ): # in particular case where one is a...
def id_func(x): # ------------------------------------------------------------------ @pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
def id_func(x): # ------------------------------------------------------------------ @pytest.fixture( params=[ ("foo", None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ] ) def names(request): """ A 3-tuple of names, the first two for operands, the l...
class TestDatetime64DateOffsetArithmetic: tm.assert_equal(result, exp) tm.assert_equal(result2, exp) # TODO: __sub__, __rsub__ def test_dt64arr_add_mixed_offset_array(self, box_with_array): # GH#10699 # array of offsets s = DatetimeIndex([Timestamp("2000-1-1"), Timestamp...
class TestDatetime64DateOffsetArithmetic: tm.assert_equal(result, exp) tm.assert_equal(result2, exp) @pytest.mark.parametrize( "other", [ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]), np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()])...
class TestTimestampSeriesArithmetic: # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) def test_dt64_series_add_intlike(self, tz, op): # GH#19123 dti = pd.DatetimeIndex(["2016-...
class TestTimestampSeriesArithmetic: # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) def test_dt64_series_add_intlike(self, tz_naive_fixture, op): # GH#19123 tz = tz_naive_fixture dti = pd.DatetimeIndex(["2016-01-02", "2016...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result, exp) assert result.freq == exp.freq @pytest.mark.parametrize( "names", [("foo", None, None), ("baz", "bar", None), ("bar", "bar", "bar")] ) @pytest.mark.parametrize("tz", [None, "America/Chicago"]) def test...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result, exp) assert result.freq == exp.freq def test_dti_add_series(self, tz_naive_fixture, names): # GH#13905 tz = tz_naive_fixture index = DatetimeIndex( ["2016-06-28 05:30", "2016-06-28 05:31"], ...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result4, expected) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")] ) def test_dti_addsub_offset_arra...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result4, expected) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) def test_dti_addsub_offset_arraylike( self, tz_naive_fixture, names, op, index_or_series ):
class TestTimedeltaArraylikeAddSubOps: result = tdarr - tdi tm.assert_equal(result, expected) @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ], ) def test_t...
class TestTimedeltaArraylikeAddSubOps: result = tdarr - tdi tm.assert_equal(result, expected) def test_td64arr_add_sub_tdi(self, box, names): # GH#17250 make sure result dtype is correct # GH#19043 make sure names are propagated correctly if box is pd.DataFrame and names[1] ...
class TestTimedeltaArraylikeAddSubOps: # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")] ) def test_td64arr_ad...
class TestTimedeltaArraylikeAddSubOps: # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets def test_td64arr_add_offset_index(self, names, box): # GH#18849, GH#19744 if box is pd.DataFrame and names[1] != names[0]:...
class TestTimedeltaArraylikeMulDivOps: with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ...
class TestTimedeltaArraylikeMulDivOps: with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser def test_td64arr_mul_int_series(self, box_df_fail, names): # GH#19042 test for correct name attachment box = box_df_fail # broadcasts along wrong axis, but doesn't...
class TestTimedeltaArraylikeMulDivOps: tm.assert_equal(result, expected) # TODO: Should we be parametrizing over types for `ser` too? @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701...
class TestTimedeltaArraylikeMulDivOps: tm.assert_equal(result, expected) # TODO: Should we be parametrizing over types for `ser` too? def test_float_series_rdiv_td64arr(self, box_with_array, names): # GH#19042 test for correct name attachment # TODO: the direct operation TimedeltaIndex ...
RETURN = """ - values from the environment variables. type: list """ import os from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase):
RETURN = """ - values from the environment variables. type: list """ from ansible.plugins.lookup import LookupBase from ansible.utils import py3compat class LookupModule(LookupBase):
class LookupModule(LookupBase): ret = [] for term in terms: var = term.split()[0] ret.append(os.getenv(var, '')) return ret
class LookupModule(LookupBase): ret = [] for term in terms: var = term.split()[0] ret.append(py3compat.environ.get(var, '')) return ret
class Axes(_AxesBase): zdelta = 0.1 def line_props_with_rcdefaults(subkey, explicit, zdelta=0): d = {k.split('.')[-1]: v for k, v in rcParams.items() if k.startswith(f'boxplot.{subkey}')} d['zorder'] = zorder + zdelta if explicit is not None: ...
class Axes(_AxesBase): zdelta = 0.1 def line_props_with_rcdefaults(subkey, explicit, zdelta=0, use_marker=True): d = {k.split('.')[-1]: v for k, v in rcParams.items() if k.startswith(f'boxplot.{subkey}')} d['zorder'] = zor...
class Axes(_AxesBase): cbook.normalize_kwargs( boxprops, mpatches.PathPatch._alias_map)) else: final_boxprops = line_props_with_rcdefaults('boxprops', boxprops) final_whiskerprops = line_props_with_rcdefaults( 'whiskerprops', whiskerpro...
class Axes(_AxesBase): cbook.normalize_kwargs( boxprops, mpatches.PathPatch._alias_map)) else: final_boxprops = line_props_with_rcdefaults('boxprops', boxprops, use_marker=False) final_whisker...
def test_boxplot_bad_ci_2(): ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) @image_comparison(['boxplot_mod_artists_after_plotting.png'], remove_text=True, savefig_kwarg={'dpi': 40}, style='default') def test_boxplot_mod_artist_after_plotting():
def test_boxplot_bad_ci_2(): ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) def test_boxplot_marker_behavior(): plt.rcParams['lines.marker'] = 's' plt.rcParams['boxplot.flierprops.marker'] = 'o' plt.rcParams['boxplot.meanprops.marker'] = '^' fig, ax = plt.subplots() test_data = np.arange...
class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin): """ logger.info("Inserting file: %s", f) colnames = '' if len(self.columns) > 0: colnames = ",".join([x[0] for x in self.columns]) colnames = '({})'.format(colnames)
class S3CopyToTable(rdbms.CopyToTable, _CredentialsMixin): """ logger.info("Inserting file: %s", f) colnames = '' if self.columns and len(self.columns) > 0: colnames = ",".join([x[0] for x in self.columns]) colnames = '({})'.format(colnames)
class DummyS3CopyToTableBase(luigi.contrib.redshift.S3CopyToTable): user = 'dummy_user' password = 'dummy_password' table = luigi.Parameter(default='dummy_table') columns = ( ('some_text', 'varchar(255)'), ('some_int', 'int'), ) copy_options = ''
class DummyS3CopyToTableBase(luigi.contrib.redshift.S3CopyToTable): user = 'dummy_user' password = 'dummy_password' table = luigi.Parameter(default='dummy_table') columns = luigi.TupleParameter( default=( ('some_text', 'varchar(255)'), ('some_int', 'int'), ) )...
class TestS3CopyToTable(unittest.TestCase): (task.table,), ) class TestS3CopyToSchemaTable(unittest.TestCase): @mock.patch("luigi.contrib.redshift.S3CopyToTable.copy")
class TestS3CopyToTable(unittest.TestCase): (task.table,), ) @mock.patch("luigi.contrib.redshift.RedshiftTarget") def test_s3_copy_with_valid_columns(self, mock_redshift_target): task = DummyS3CopyToTableKey() task.run() # The mocked connection cursor passed to ...
class AuthenticationForm(forms.Form): if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: # An authentication backend may reject inactive users. Check # if the...
class AuthenticationForm(forms.Form): if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login']...
class UserCreationFormTest(TestDataMixin, TestCase): ) class AuthenticationFormTest(TestDataMixin, TestCase): def test_invalid_username(self):
class UserCreationFormTest(TestDataMixin, TestCase): ) # To verify that the login form rejects inactive users, use an authentication # backend that allows them. @override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend']) class AuthenticationFormTest(TestDataMixin, Te...
class AuthenticationFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])]) def test_login_failed(self): signal_calls = []
class AuthenticationFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])]) # Use an authentication backend that rejects inactive users. @override_settings(AUTHENTICATION_BACKENDS=['django.cont...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'} validates_explain_options = False # A query will error on invalid options. supports_deferrabl...
class DatabaseFeatures(BaseDatabaseFeatures): only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'} supports_deferrable_unique_constraints = True has_json_operators = True json_key_contains_...
from django.db.backends.base.operations import BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'varchar' explain_prefix = 'EXPLAIN' cast_data_types = { 'AutoField': 'integer', 'BigAutoField': 'bigint',
from django.db.backends.base.operations import BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'varchar' explain_prefix = 'EXPLAIN' explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", ...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): prefix = super().explain_query_prefix(format) extra = {} if format: extra['FORMAT'] = format if op...
class DatabaseOperations(BaseDatabaseOperations): return super().subtract_temporals(internal_type, lhs, rhs) def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): "true" if value else...
__all__ = ['Query', 'RawQuery'] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") def get_field_names_from_opts(opts): return set(chain.from_iterable(
__all__ = ['Query', 'RawQuery'] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def g...
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() q.explain_query = True q.explain_format = format q.explain_options = options
class Query(BaseExpression): def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"In...
class ExplainTests(TestCase): @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = 'DOES NOT E...
class ExplainTests(TestCase): @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = '...
class ExplainTests(TestCase): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific') def test_mysql_text_to_traditional(self): # En...
class ExplainTests(TestCase): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; -...
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...
class ImagesPipeline(FilesPipeline): # ImagesPipeline. They may be overridden by settings. MIN_WIDTH = 0 MIN_HEIGHT = 0 EXPIRES = 0 THUMBS = {} DEFAULT_IMAGES_URLS_FIELD = 'image_urls' DEFAULT_IMAGES_RESULT_FIELD = 'images'
class ImagesPipeline(FilesPipeline): # ImagesPipeline. They may be overridden by settings. MIN_WIDTH = 0 MIN_HEIGHT = 0 EXPIRES = 90 THUMBS = {} DEFAULT_IMAGES_URLS_FIELD = 'image_urls' DEFAULT_IMAGES_RESULT_FIELD = 'images'
class ImagesPipelineTestCaseCustomSettings(unittest.TestCase): default_pipeline_settings = dict( MIN_WIDTH=0, MIN_HEIGHT=0, EXPIRES=0, THUMBS={}, IMAGES_URLS_FIELD='image_urls', IMAGES_RESULT_FIELD='images'
class ImagesPipelineTestCaseCustomSettings(unittest.TestCase): default_pipeline_settings = dict( MIN_WIDTH=0, MIN_HEIGHT=0, EXPIRES=90, THUMBS={}, IMAGES_URLS_FIELD='image_urls', IMAGES_RESULT_FIELD='images'
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...
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None try: new_deps = self._run_get_new_deps() if new_deps is None: status = RUNNING else: ...
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None new_deps = self._run_get_new_deps() if new_deps is None: status = DONE self.task.trigger_event( ...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(saved_tasks, [t]) def test_success_handler(self): saved_tasks = [] @EmptyTask.event_handler(Event.SUCCESS) def save_task(task): print("Saving task...") sav...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(saved_tasks, [t]) def _run_empty_task(self, fail): successes = [] failures = [] exceptions = [] @EmptyTask.event_handler(Event.SUCCESS) def success(task): ...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(dummies[0], "foo") def test_processing_time_handler(self): @EmptyTask.event_handler(Event.PROCESSING_TIME) def save_task(task, processing_time): self.result = task, processing_...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(dummies[0], "foo") def _run_processing_time_handler(self, fail): result = [] @EmptyTask.event_handler(Event.PROCESSING_TIME) def save_task(task, processing_time): resu...
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'...
def test_rounding_errors(): assert (255, 255) == ImageColor.getcolor("white", "LA") assert (163, 33) == ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA") Image.new("LA", (1, 1), "white")
def test_rounding_errors(): assert (255, 255) == ImageColor.getcolor("white", "LA") assert (163, 33) == ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA") Image.new("LA", (1, 1), "white") def test_color_too_long(): # Arrange color_too_long = "hsl(" + "1" * 100 + ")" # Act / Assert with py...