buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def load(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
"""
loader = Loader(stream)
try:
return loader.get_single_data()
finally:
loader.dispose()
def load_all(stream, Loader=Loader):
"""
Parse all Y... | def load(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
By default resolve only basic YAML tags, if an alternate Loader is
provided, may be dangerous.
"""
loader = Loader(stream)
try:
return loader.get_single_da... |
def load_all(stream, Loader=Loader):
yield loader.get_data()
finally:
loader.dispose()
def safe_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve only basic YAML tags.
"""
return load(stream, SafeLoader)
def... | def load_all(stream, Loader=Loader):
yield loader.get_data()
finally:
loader.dispose()
safe_load_all = load_all
def danger_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
When used on untrusted input, can result in arbitra... |
def dump_all(documents, stream=None, Dumper=Dumper,
dumper.dispose()
if getvalue:
return getvalue()
def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([d... | def dump_all(documents, stream=None, Dumper=Dumper,
dumper.dispose()
if getvalue:
return getvalue()
safe_dump_all = dump_all
def danger_dump_all(documents, stream=None, **kwds):
"""
Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
If stream is... |
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper']
from _yaml import CParser, CEmitter
|
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader', 'CDangerLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper', 'CDangerDumper']
from _yaml import CParser, CEmitter
|
def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class CSafeLoader(CParser, SafeConstructor, Resolver):
def __init__(self, stream):
CParser.__init__(self, stream)
SafeConstructor.__init__(self)
Resolver.__init__(self)
class CLoader(CPa... | def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class CLoader(CParser, SafeConstructor, Resolver):
def __init__(self, stream):
CParser.__init__(self, stream)
SafeConstructor.__init__(self)
Resolver.__init__(self)
CSafeLoader = CLoader
... |
def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class CSafeDumper(CEmitter, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, | def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class CDumper(CEmitter, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, |
def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class CDumper(CEmitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_style=None, default_flow_... | def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
CSafeDumper = CDumper
class CDangerDumper(CEmitter, Serializer, Representer, Resolver):
def __init__(self, stream,
defau... |
def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
| def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self) |
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
from .emitter import *
from .serializer import * |
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper', 'DangerDumper']
from .emitter import *
from .serializer import * |
def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, | def __init__(self, stream,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class Dumper(Emitter, Serializer, SafeRepresenter, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None, |
def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
class Dumper(Emitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_style=None, default_flow_st... | def __init__(self, stream,
SafeRepresenter.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
SafeDumper = Dumper
class DangerDumper(Emitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_s... |
def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self)
| def __init__(self, stream,
Representer.__init__(self, default_style=default_style,
default_flow_style=default_flow_style)
Resolver.__init__(self) |
__all__ = ['BaseLoader', 'SafeLoader', 'Loader']
from .reader import *
from .scanner import * |
__all__ = ['BaseLoader', 'SafeLoader', 'Loader', 'DangerLoader']
from .reader import *
from .scanner import * |
def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) | def __init__(self, stream):
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class Loader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) |
def __init__(self, stream):
Composer.__init__(self)
SafeConstructor.__init__(self)
Resolver.__init__(self)
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) | def __init__(self, stream):
Composer.__init__(self)
SafeConstructor.__init__(self)
Resolver.__init__(self)
SafeLoader = Loader
class DangerLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream) |
def __init__(self, stream):
Composer.__init__(self)
Constructor.__init__(self)
Resolver.__init__(self)
| def __init__(self, stream):
Composer.__init__(self)
Constructor.__init__(self)
Resolver.__init__(self) |
def _make_objects():
NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, \
FixedOffset, today, execute
class MyLoader(yaml.Loader):
pass
class MyDumper(yaml.Dumper):
pass
class MyTestClass1: | def _make_objects():
NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, \
FixedOffset, today, execute
class MyLoader(yaml.DangerLoader):
pass
class MyDumper(yaml.DangerDumper):
pass
class MyTestClass1: |
def test_constructor_types(data_filename, code_filename, verbose=False):
sys.modules['test_constructor'] = sys.modules['__main__']
import test_appliance
test_appliance.run(globals())
| def test_constructor_types(data_filename, code_filename, verbose=False):
sys.modules['test_constructor'] = sys.modules['__main__']
import test_appliance
test_appliance.run(globals()) |
def test_recursive(recursive_filename, verbose=False):
value2 = None
output2 = None
try:
output1 = yaml.dump(value1)
value2 = yaml.load(output1)
output2 = yaml.dump(value2)
assert output1 == output2, (output1, output2)
finally:
if verbose: | def test_recursive(recursive_filename, verbose=False):
value2 = None
output2 = None
try:
output1 = yaml.danger_dump(value1)
value2 = yaml.danger_load(output1)
output2 = yaml.danger_dump(value2)
assert output1 == output2, (output1, output2)
finally:
if verbose: |
def test_recursive(recursive_filename, verbose=False):
if __name__ == '__main__':
import test_appliance
test_appliance.run(globals())
| def test_recursive(recursive_filename, verbose=False):
if __name__ == '__main__':
import test_appliance
test_appliance.run(globals()) |
def _make_objects():
NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, \
FixedOffset, today, execute
class MyLoader(yaml.Loader):
pass
class MyDumper(yaml.Dumper):
pass
class MyTestClass1: | def _make_objects():
NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, \
FixedOffset, today, execute
class MyLoader(yaml.DangerLoader):
pass
class MyDumper(yaml.DangerDumper):
pass
class MyTestClass1: |
def test_constructor_types(data_filename, code_filename, verbose=False):
sys.modules['test_constructor'] = sys.modules['__main__']
import test_appliance
test_appliance.run(globals())
| def test_constructor_types(data_filename, code_filename, verbose=False):
sys.modules['test_constructor'] = sys.modules['__main__']
import test_appliance
test_appliance.run(globals()) |
def test_recursive(recursive_filename, verbose=False):
value2 = None
output2 = None
try:
output1 = yaml.dump(value1)
value2 = yaml.load(output1)
output2 = yaml.dump(value2)
assert output1 == output2, (output1, output2)
finally:
if verbose: | def test_recursive(recursive_filename, verbose=False):
value2 = None
output2 = None
try:
output1 = yaml.danger_dump(value1)
value2 = yaml.danger_load(output1)
output2 = yaml.danger_dump(value2)
assert output1 == output2, (output1, output2)
finally:
if verbose: |
def test_recursive(recursive_filename, verbose=False):
if __name__ == '__main__':
import test_appliance
test_appliance.run(globals())
| def test_recursive(recursive_filename, verbose=False):
if __name__ == '__main__':
import test_appliance
test_appliance.run(globals()) |
def test_apply_index(cls, n):
ser = pd.Series(rng)
res = rng + offset
res_v2 = offset.apply_index(rng)
assert (res == res_v2).all()
assert res[0] == rng[0] + offset | def test_apply_index(cls, n):
ser = pd.Series(rng)
res = rng + offset
assert res.freq is None # not retained
res_v2 = offset.apply_index(rng)
assert (res == res_v2).all()
assert res[0] == rng[0] + offset |
class MonthOffset(SingleConstructorOffset):
@apply_index_wraps
def apply_index(self, i):
shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt)
# TODO: going through __new__ raises on call to _validate_frequency;
# are we passing incorrect freq?
return type(i)._simple_... | class MonthOffset(SingleConstructorOffset):
@apply_index_wraps
def apply_index(self, i):
shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt)
return type(i)._simple_new(shifted, dtype=i.dtype)
class MonthEnd(MonthOffset): |
class QuarterOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.startingMonth, self._day_opt
)
# TODO: going through __new__ raises on call to _validate_frequency;
# are we passing incorrect freq?
return type(dtindex)._simple_new(
... | class QuarterOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.startingMonth, self._day_opt
)
return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype)
class BQuarterEnd(QuarterOffset): |
class YearOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.month, self._day_opt, modby=12
)
# TODO: going through __new__ raises on call to _validate_frequency;
# are we passing incorrect freq?
return type(dtindex)._simple_new(
... | class YearOffset(DateOffset):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.month, self._day_opt, modby=12
)
return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype)
def is_on_offset(self, dt: datetime) -> bool:
if self.normalize and not _is_norma... |
def pivot_table(
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
if table.index.nlevels > 1:
# Related GH #17123
# If index_names are integers, determine whether the integers refer
# to the level position or name. | def pivot_table(
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
# GH17038, this check should only happen if index is defined (not None)
if table.index.nlevels > 1 and index:
# Related GH #17123
# If index_names are integers, determine whether the ... |
class TestPivotTable:
totals = table.loc[("All", ""), value_col]
assert totals == self.data[value_col].mean()
# no rows
rtable = self.data.pivot_table(
columns=["AA", "BB"], margins=True, aggfunc=np.mean
)
assert isinstance(rtable, Series)
ta... | class TestPivotTable:
totals = table.loc[("All", ""), value_col]
assert totals == self.data[value_col].mean()
table = self.data.pivot_table(index=["AA", "BB"], margins=True, aggfunc="mean")
for item in ["DD", "EE", "FF"]:
totals = table.loc[("All", ""), item] |
class TestPivotTable:
tm.assert_frame_equal(expected, result)
def test_pivot_integer_columns(self):
# caused by upstream bug in unstack
| class TestPivotTable:
tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("cols", [(1, 2), ("a", "b"), (1, "b"), ("a", 1)])
def test_pivot_table_multiindex_only(self, cols):
# GH 17038
df2 = DataFrame({cols[0]: [1, 2, 3], cols[1]: [1, 2, 3], "v": [4, 5, 6]})
resul... |
def get_weighted_roll_func(cfunc: Callable) -> Callable:
def validate_baseindexer_support(func_name: Optional[str]) -> None:
# GH 32865: These functions work correctly with a BaseIndexer subclass
BASEINDEXER_WHITELIST = {
"min",
"max",
"mean", | def get_weighted_roll_func(cfunc: Callable) -> Callable:
def validate_baseindexer_support(func_name: Optional[str]) -> None:
# GH 32865: These functions work correctly with a BaseIndexer subclass
BASEINDEXER_WHITELIST = {
"count",
"min",
"max",
"mean", |
class _Rolling_and_Expanding(_Rolling):
)
def count(self):
if isinstance(self.window, BaseIndexer):
validate_baseindexer_support("count")
blocks, obj = self._create_blocks()
results = [] | class _Rolling_and_Expanding(_Rolling):
)
def count(self):
# GH 32865. Using count with custom BaseIndexer subclass
# implementations shouldn't end up here
assert not isinstance(self.window, BaseIndexer)
blocks, obj = self._create_blocks()
results = [] |
class Rolling(_Rolling_and_Expanding):
def count(self):
# different impl for freq counting
if self.is_freq_type:
window_func = self._get_roll_func("roll_count")
return self._apply(window_func, center=self.center, name="count")
| class Rolling(_Rolling_and_Expanding):
def count(self):
# different impl for freq counting
# GH 32865. Use a custom count function implementation
# when using a BaseIndexer subclass as a window
if self.is_freq_type or isinstance(self.window, BaseIndexer):
window_func = s... |
def test_win_type_not_implemented():
df.rolling(indexer, win_type="boxcar")
@pytest.mark.parametrize("func", ["count", "skew", "cov", "corr"])
def test_notimplemented_functions(func):
# GH 32865
class CustomIndexer(BaseIndexer): | def test_win_type_not_implemented():
df.rolling(indexer, win_type="boxcar")
@pytest.mark.parametrize("func", ["skew", "cov", "corr"])
def test_notimplemented_functions(func):
# GH 32865
class CustomIndexer(BaseIndexer): |
def test_notimplemented_functions(func):
@pytest.mark.parametrize(
"func,np_func,expected,np_kwargs",
[
("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan], {},),
(
"max", | def test_notimplemented_functions(func):
@pytest.mark.parametrize(
"func,np_func,expected,np_kwargs",
[
("count", len, [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, np.nan], {},),
("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan], {},),
(
"max", |
jwplayer("mediaplayer").setup({"abouttext":"Visit Indie DB","aboutlink":"http:\/
_TEST_CASES = [
(
# https://github.com/rg3/youtube-dl/issues/13919
'float_duration',
'http://unknown/manifest.mpd',
[{
'manifest_url': ... | jwplayer("mediaplayer").setup({"abouttext":"Visit Indie DB","aboutlink":"http:\/
_TEST_CASES = [
(
# https://github.com/rg3/youtube-dl/issues/13919
# Also tests duplicate representation ids, see
# https://github.com/rg3/youtube-dl/issues/15111
... |
class InfoExtractor(object):
f['url'] = initialization_url
f['fragments'].append({location_key(initialization_url): initialization_url})
f['fragments'].extend(representation_ms_info['fragments'])
try:... | class InfoExtractor(object):
f['url'] = initialization_url
f['fragments'].append({location_key(initialization_url): initialization_url})
f['fragments'].extend(representation_ms_info['fragments'])
# Ac... |
class FrameApply:
from pandas import Series
if not should_reduce:
EMPTY_SERIES = Series([])
try:
r = self.f(EMPTY_SERIES, *self.args, **self.kwds)
except Exception:
pass
else:
should_reduce = not isinstance... | class FrameApply:
from pandas import Series
if not should_reduce:
try:
r = self.f(Series([]))
except Exception:
pass
else:
should_reduce = not isinstance(r, Series)
if should_reduce:
if len(self.agg... |
class TestDataFrameApply:
# Ensure that x.append hasn't been called
assert x == []
def test_apply_deprecate_reduce(self):
empty_frame = DataFrame()
| class TestDataFrameApply:
# Ensure that x.append hasn't been called
assert x == []
@pytest.mark.parametrize("func", ["sum", "prod", "any", "all"])
def test_apply_funcs_over_empty(self, func):
# GH 28213
df = DataFrame(columns=["a", "b", "c"])
result = df.apply(getattr(n... |
from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.utils.inspect import ( | from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils._os import safe_join
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from djan... |
class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(directory) / template
if template_file.exists():
templ... | class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(safe_join(directory, template))
if template_file.exists():
... |
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertEqual(response.status_code, 200)
@override_settings(TEMPLATES=[{
'NAME': 'ONE',
'BACKEND': 'django.template.backends.django.DjangoTemplates', | class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertEqual(response.status_code, 200)
@unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.')
class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_login(se... |
class DatetimeLikeArrayMixin(
def _validate_insert_value(self, value):
if isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
elif is_valid_nat_for_dtype(value, self.dtype):
# GH#18295
value = NaT
elif lib.is_scalar(value) and isn... | class DatetimeLikeArrayMixin(
def _validate_insert_value(self, value):
if isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
self._check_compatible_with(value, setitem=True)
# TODO: if we dont have compat, should we raise or astype(object)?
... |
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
-------
new_index : Index
"""
item = self._data._validate_insert_value(item)
freq = None
if isinstance(item, self._data._scalar_type) or item is NaT:
self._data._check_compatible_with(item, seti... | class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
-------
new_index : Index
"""
if isinstance(item, str):
# TODO: Why are strings special?
# TODO: Should we attempt _scalar_from_string?
return self.astype(object).insert(loc, item)
... |
class TestInsert:
assert result.name == expected.name
assert result.tz == expected.tz
assert result.freq is None | class TestInsert:
assert result.name == expected.name
assert result.tz == expected.tz
assert result.freq is None
@pytest.mark.parametrize(
"item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)]
)
def test_insert_mismatched_types_rai... |
class TestTimedeltaIndexInsert:
with pytest.raises(TypeError, match="incompatible label"):
idx.insert(0, np.datetime64("NaT"))
def test_insert_dont_cast_strings(self):
# To match DatetimeIndex and PeriodIndex behavior, dont try to
# parse strings to Timedelta | class TestTimedeltaIndexInsert:
with pytest.raises(TypeError, match="incompatible label"):
idx.insert(0, np.datetime64("NaT"))
@pytest.mark.parametrize(
"item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")]
)
def test_insert_mismatched_types_raises(self,... |
class TestInsertIndexCoercion(CoercionBase):
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo"))
msg = "cannot insert DatetimeIndex with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, 1... | class TestInsertIndexCoercion(CoercionBase):
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo"))
msg = "cannot insert DatetimeArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, 1... |
class TestInsertIndexCoercion(CoercionBase):
)
# ToDo: must coerce to object
msg = "cannot insert TimedeltaIndex with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01"))
# ToDo: must coerce to object
msg = ... | class TestInsertIndexCoercion(CoercionBase):
)
# ToDo: must coerce to object
msg = "cannot insert TimedeltaArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01"))
# ToDo: must coerce to object
msg = ... |
class TestPartialSetting:
df = orig.copy()
# don't allow not string inserts
msg = "cannot insert DatetimeIndex with incompatible label"
with pytest.raises(TypeError, match=msg):
df.loc[100.0, :] = df.iloc[0] | class TestPartialSetting:
df = orig.copy()
# don't allow not string inserts
msg = "cannot insert DatetimeArray with incompatible label"
with pytest.raises(TypeError, match=msg):
df.loc[100.0, :] = df.iloc[0] |
import time
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.functional import cached_property
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class Datab... | import time
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.crypto import get_random_string
from django.utils.functional import cached_property
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = ... |
class DatabaseCreation(BaseDatabaseCreation):
]
# Ignore "user already exists" error when keepdb is on
acceptable_ora_err = 'ORA-01920' if keepdb else None
self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err)
# Most test-suites can be... | class DatabaseCreation(BaseDatabaseCreation):
]
# Ignore "user already exists" error when keepdb is on
acceptable_ora_err = 'ORA-01920' if keepdb else None
success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err)
# If the passwo... |
class DatabaseCreation(BaseDatabaseCreation):
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, default)
if val is None:
val = TEST_DATABASE_PREFIX + settings_dict[prefixed]
return val
| class DatabaseCreation(BaseDatabaseCreation):
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, default)
if val is None and prefixed:
val = TEST_DATABASE_PREFIX + settings_dict[prefixed]
return val
|
class DatabaseCreation(BaseDatabaseCreation):
return self._test_settings_get('USER', prefixed='USER')
def _test_database_passwd(self):
return self._test_settings_get('PASSWORD', default=PASSWORD)
def _test_database_tblspace(self):
return self._test_settings_get('TBLSPACE', prefixed='US... | class DatabaseCreation(BaseDatabaseCreation):
return self._test_settings_get('USER', prefixed='USER')
def _test_database_passwd(self):
password = self._test_settings_get('PASSWORD')
if password is None and self._test_user_create():
# Oracle passwords are limited to 30 chars and ... |
'transparent': (0, 0, 0, 0),
}
RGBA = re.compile(r'rgba\([ \n\r\t]*(.+?)[ \n\r\t]*\)')
RGB = re.compile(r'rgb\([ \n\r\t]*(.+?)[ \n\r\t]*\)')
HEX_RRGGBB = re.compile('#[0-9a-f]{6}')
HEX_RGB = re.compile('#[0-9a-f]{3}')
| 'transparent': (0, 0, 0, 0),
}
RGBA = re.compile(r'rgba\((.+?)\)')
RGB = re.compile(r'rgb\((.+?)\)')
HEX_RRGGBB = re.compile('#[0-9a-f]{6}')
HEX_RGB = re.compile('#[0-9a-f]{3}')
|
def color(string, opacity=1):
if match:
r, g, b, a = tuple(
float(i.strip(' %')) / 100 if '%' in i else float(i) / 255
for i in match.group(1).split(','))
return (r, g, b, a * 255 * opacity)
match = RGB.search(string)
if match:
r, g, b = tuple(
fl... | def color(string, opacity=1):
if match:
r, g, b, a = tuple(
float(i.strip(' %')) / 100 if '%' in i else float(i) / 255
for i in match.group(1).strip().split(','))
return (r, g, b, a * 255 * opacity)
match = RGB.search(string)
if match:
r, g, b = tuple(
... |
import os
from shutil import rmtree
import string
import tempfile
from typing import List, Optional, Union, cast
import warnings
import zipfile
| import os
from shutil import rmtree
import string
import tempfile
from typing import Any, List, Optional, Union, cast
import warnings
import zipfile
|
from pandas._config.localization import ( # noqa:F401
)
import pandas._libs.testing as _testing
from pandas._typing import FrameOrSeries
from pandas.compat import _get_lzma_file, _import_lzma
from pandas.core.dtypes.common import ( | from pandas._config.localization import ( # noqa:F401
)
import pandas._libs.testing as _testing
from pandas._typing import FilePathOrBuffer, FrameOrSeries
from pandas.compat import _get_lzma_file, _import_lzma
from pandas.core.dtypes.common import ( |
def reset_display_options():
pd.reset_option("^display.", silent=True)
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOrSeries:
"""
Pickle an object and then read it again.
Parameters
----------
obj : pandas object
The object to pickle and then re-read.
... | def reset_display_options():
pd.reset_option("^display.", silent=True)
def round_trip_pickle(
obj: Any, path: Optional[FilePathOrBuffer] = None
) -> FrameOrSeries:
"""
Pickle an object and then read it again.
Parameters
----------
obj : any object
The object to pickle and then re-... |
def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr
pandas object
The original object that was pickled and then re-read.
"""
if path is None:
path = f"__{rands(10)}__.pickle"
with ensure_clean(path) as path:
pd.to_pickle(obj, path)
return pd.r... | def round_trip_pickle(obj: FrameOrSeries, path: Optional[str] = None) -> FrameOr
pandas object
The original object that was pickled and then re-read.
"""
_path = path
if _path is None:
_path = f"__{rands(10)}__.pickle"
with ensure_clean(_path) as path:
pd.to_pickle(obj, _path... |
""" pickle compat """
import pickle
import warnings
from pandas.compat import pickle_compat as pc
from pandas.io.common import get_handle, stringify_path
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
"""
Pickle (serialize) object to file.
| """ pickle compat """
import pickle
from typing import Any, Optional
import warnings
from pandas._typing import FilePathOrBuffer
from pandas.compat import pickle_compat as pc
from pandas.io.common import get_filepath_or_buffer, get_handle
def to_pickle(
obj: Any,
filepath_or_buffer: FilePathOrBuffer,
co... |
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
----------
obj : any object
Any python object.
path : str
File path where the pickled object will be stored.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
A string repres... | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
----------
obj : any object
Any python object.
filepath_or_buffer : str, path object or file-like object
File path, URL, or buffer where the pickled object will be stored.
.. versionchanged:: 1.0.0
... |
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
>>> import os
>>> os.remove("./dummy.pkl")
"""
path = stringify_path(path)
f, fh = get_handle(path, "wb", compression=compression, is_text=False)
if protocol < 0:
protocol = pickle.HIGHEST_PROTOCOL
try: | def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
>>> import os
>>> os.remove("./dummy.pkl")
"""
fp_or_buf, _, compression, should_close = get_filepath_or_buffer(
filepath_or_buffer, compression=compression, mode="wb"
)
if not isinstance(fp_or_buf, str) and... |
def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
f.close()
for _f in fh:
_f.close()
def read_pickle(path, compression="infer"):
"""
Load pickled pandas object (or any object) from file.
| def to_pickle(obj, path, compression="infer", protocol=pickle.HIGHEST_PROTOCOL):
f.close()
for _f in fh:
_f.close()
if should_close:
try:
fp_or_buf.close()
except ValueError:
pass
def read_pickle(
filepath_or_buffer: FileP... |
def read_pickle(path, compression="infer"):
Parameters
----------
path : str
File path where the pickled object will be loaded.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer', then use
gzip, bz2... | def read_pickle(path, compression="infer"):
Parameters
----------
filepath_or_buffer : str, path object or file-like object
File path, URL, or buffer where the pickled object will be loaded from.
.. versionchanged:: 1.0.0
Accept URL. URL is not limited to S3 and GCS.
compre... |
def read_pickle(path, compression="infer"):
>>> import os
>>> os.remove("./dummy.pkl")
"""
path = stringify_path(path)
f, fh = get_handle(path, "rb", compression=compression, is_text=False)
# 1) try standard library Pickle
# 2) try pickle_compat (older pandas version) to handle subclass cha... | def read_pickle(path, compression="infer"):
>>> import os
>>> os.remove("./dummy.pkl")
"""
fp_or_buf, _, compression, should_close = get_filepath_or_buffer(
filepath_or_buffer, compression=compression
)
if not isinstance(fp_or_buf, str) and compression == "infer":
compression = N... |
def read_pickle(path, compression="infer"):
f.close()
for _f in fh:
_f.close() | def read_pickle(path, compression="infer"):
f.close()
for _f in fh:
_f.close()
if should_close:
try:
fp_or_buf.close()
except ValueError:
pass |
import zipfile
import pytest
from pandas.compat import _get_lzma_file, _import_lzma, is_platform_little_endian
import pandas as pd
from pandas import Index | import zipfile
import pytest
from pandas.compat import _get_lzma_file, _import_lzma, is_platform_little_endian
import pandas.util._test_decorators as td
import pandas as pd
from pandas import Index |
def test_unicode_decode_error(datapath):
# just test the columns are correct since the values are random
excols = pd.Index(["a", "b", "c"])
tm.assert_index_equal(df.columns, excols) | def test_unicode_decode_error(datapath):
# just test the columns are correct since the values are random
excols = pd.Index(["a", "b", "c"])
tm.assert_index_equal(df.columns, excols)
# ---------------------
# tests for buffer I/O
# ---------------------
def test_pickle_buffer_roundtrip():
with tm.ens... |
def Ghostscript(tile, size, fp, scale=1):
import tempfile, os, subprocess
file = tempfile.mktemp()
# Build ghostscript command
command = ["gs", | def Ghostscript(tile, size, fp, scale=1):
import tempfile, os, subprocess
out_fd, file = tempfile.mkstemp()
os.close(out_fd)
# Build ghostscript command
command = ["gs", |
class Image:
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile
if not file:
file = tempfile.mktemp()
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)
else:
file = file + "." + format
... | class Image:
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile, os
if not file:
f, file = tempfile.mkstemp(format or '')
os.close(f)
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)... |
class IptcImageFile(ImageFile.ImageFile):
self.fp.seek(offset)
# Copy image data to temporary file
outfile = tempfile.mktemp()
o = open(outfile, "wb")
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header | class IptcImageFile(ImageFile.ImageFile):
self.fp.seek(offset)
# Copy image data to temporary file
o_fd, outfile = tempfile.mkstemp(text=False)
o = os.fdopen(o_fd)
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header |
class JpegImageFile(ImageFile.ImageFile):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
file = tempfile.mktemp()
os.system("djpeg %s >%s" % (self.filename, file))
try:
self.im = Image.core.open_ppm(file)
finally:
... | class JpegImageFile(ImageFile.ImageFile):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
f, path = tempfile.mkstemp()
os.close(f)
if os.path.exists(self.filename):
os.system("djpeg '%s' >'%s'" % (self.filename, path))
else:... |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'((... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<p>I <3 python, what about you?</p>')
self.assertEqual('<p>I <3 python...</p>', truncator.words(3, '...', html=True))
def test_wrap(self):
digits = '1234 67 9'
self.assertEqual(text.wrap(digits, 100), '1234 67 9'... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<p>I <3 python, what about you?</p>')
self.assertEqual('<p>I <3 python...</p>', truncator.words(3, '...', html=True))
re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>'
truncator = text.Truncator(re_tag_catast... |
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.models.constants import OnConflict
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "varchar"
explain_prefix = "EXPLAIN"
cast_data_types = {
"AutoField": "integer",
"BigAutoField": "bigint", | from django.db.models.constants import OnConflict
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "varchar"
explain_prefix = "EXPLAIN"
explain_options = frozenset(
[
"ANALYZE",
"BUFFERS",
"COSTS",
"SETTINGS",
... |
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):
if opts is None: | __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_info = ExplainInfo(format, options)
compiler = q.get_compiler(using=using)
return "\n".join(compiler.explain_query()) | 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.explain(test=1, test2=1)
def test_unknown_format(self):
msg = "DOES NOT EXIST i... | class ExplainTests(TestCase):
@skipUnlessDBFeature("validates_explain_options")
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"):
Tag.objects.explain(**{"TEST": 1, "TEST2": 1})
def test_unknown_format(self):
msg = "DOES N... |
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; -... |
import json
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch | import json
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch |
class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
def get_context(self, name, value, attrs):
context = super().ge... | class AdminEmailInputWidget(forms.EmailInput):
class AdminURLFieldWidget(forms.URLInput):
template_name = 'admin/widgets/url.html'
def __init__(self, attrs=None, validator_class=URLValidator):
super().__init__(attrs={'class': 'vURLField', **(attrs or {})})
self.validator = validator_class()
... |
class AdminSplitDateTimeWidgetTest(SimpleTestCase):
class AdminURLWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual( | class AdminSplitDateTimeWidgetTest(SimpleTestCase):
class AdminURLWidgetTest(SimpleTestCase):
def test_get_context_validates_url(self):
w = widgets.AdminURLFieldWidget()
for invalid in ['', '/not/a/full/url/', 'javascript:alert("Danger XSS!")']:
with self.subTest(url=invalid):
... |
class AdminURLWidgetTest(SimpleTestCase):
VALUE_RE = re.compile('value="([^"]+)"')
TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>')
w = widgets.AdminURLFieldWidget()
output = w.render('test', 'http://example.com/<sometag>some text</sometag>')
self.assertEqual(
HREF_RE.sear... | class AdminURLWidgetTest(SimpleTestCase):
VALUE_RE = re.compile('value="([^"]+)"')
TEXT_RE = re.compile('<a[^>]+>([^>]+)</a>')
w = widgets.AdminURLFieldWidget()
output = w.render('test', 'http://example.com/<sometag>some-text</sometag>')
self.assertEqual(
HREF_RE.sear... |
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings | import base64
import binascii
import hashlib
import importlib
import warnings
from collections import OrderedDict
from django.conf import settings |
def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
must_update = hasher.algorithm != preferred.algorithm
if not must_update:
must_update = preferred.must_update(encoded)
is_correct = hasher.verify(pass... | def check_password(password, encoded, setter=None, preferred='default'):
preferred = get_hasher(preferred)
hasher = identify_hasher(encoded)
hasher_changed = hasher.algorithm != preferred.algorithm
must_update = hasher_changed or preferred.must_update(encoded)
is_correct = hasher.verify(password, e... |
class BasePasswordHasher(object):
def must_update(self, encoded):
return False
class PBKDF2PasswordHasher(BasePasswordHasher):
""" | class BasePasswordHasher(object):
def must_update(self, encoded):
return False
def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example... |
class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
""" | class PBKDF2PasswordHasher(BasePasswordHasher):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
def harden_runtime(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
extra_iterations = self.iteratio... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password truncation
# Se... | class BCryptSHA256PasswordHasher(BasePasswordHasher):
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, force_bytes(data))
return constant_time_compare(encoded, encoded_2)
def safe_su... |
class BCryptSHA256PasswordHasher(BasePasswordHasher):
(_('checksum'), mask_hash(checksum)),
])
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
""" | class BCryptSHA256PasswordHasher(BasePasswordHasher):
(_('checksum'), mask_hash(checksum)),
])
def harden_runtime(self, password, encoded):
_, data = encoded.split('$', 1)
salt = data[:29] # Length of the salt in bcrypt.
rounds = data.split('$')[2]
# work factor... |
class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class MD5PasswordHasher(BasePasswordHasher):
""" | class SHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class MD5PasswordHasher(BasePasswordHasher):
""" |
class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" | class MD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" | class UnsaltedSHA1PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(hash)),
])
def harden_runtime(self, password, encoded):
pass
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
""" |
class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
class CryptPasswordHasher(BasePasswordHasher):
""" | class UnsaltedMD5PasswordHasher(BasePasswordHasher):
(_('hash'), mask_hash(encoded, show=3)),
])
def harden_runtime(self, password, encoded):
pass
class CryptPasswordHasher(BasePasswordHasher):
""" |
class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
]) | class CryptPasswordHasher(BasePasswordHasher):
(_('salt'), salt),
(_('hash'), mask_hash(data, show=3)),
])
def harden_runtime(self, password, encoded):
pass |
from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six
try:
import crypt | from django.contrib.auth.hashers import (
check_password, get_hasher, identify_hasher, is_password_usable,
make_password,
)
from django.test import SimpleTestCase, mock
from django.test.utils import override_settings
from django.utils import six
from django.utils.encoding import force_bytes
try:
import cry... |
class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('', blank_encoded))
self.assertFalse(check_password(' ', blank_encoded))
def test_unusable(self):
encoded = make_password(None)
self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SU... | class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('', blank_encoded))
self.assertFalse(check_password(' ', blank_encoded))
@skipUnless(bcrypt, "bcrypt not installed")
def test_bcrypt_harden_runtime(self):
hasher = get_hasher('bcrypt')
self.assertEqual('bcry... |
class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_upgrade_new_hasher(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.iterations = old_iterations
def test_pbkdf2_harden_runtime(self):
hasher = get_hasher('default')
self.assertEqual('pbkdf2_sha256', hasher.algorithm)
with mock.patch.object(hasher, 'iterations', 1):
enc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.