buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "xx",
"eauth": "xx",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"ssh_remote_port_forwards": ... | class NetapiSSHClientTest(SSHCase):
"client": "ssh",
"tgt": "127.0.0.1",
"renderer": "cheetah",
"fun": "test.ping",
"roster_file": "/tmp/salt-tests-tmpdir/config/roaster",
"rosters": "/",
"ssh_remote_port_forwards": "hhhhh|id>{} #, lol"... |
from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex, | from pandas.core.dtypes.common import (
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
ABCExtensionArray,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex, |
class IntervalArray(IntervalMixin, ExtensionArray):
# Avoid materializing self.values
return self.left.size
def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs):
"""
Take elements from the IntervalArray. | class IntervalArray(IntervalMixin, ExtensionArray):
# Avoid materializing self.values
return self.left.size
def shift(self, periods: int = 1, fill_value: object = None) -> ABCExtensionArray:
if not len(self) or periods == 0:
return self.copy()
if isna(fill_value):
... |
class TestMethods:
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
class TestSetitem:
def test_set_na(self, left_right_dtypes): | class TestMethods:
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
def test_shift(self):
# https://github.com/pandas-dev/pandas/issues/31495
a = IntervalArray.from_breaks([1, 2, 3])
result = a.shift()
# int -> float
... |
class BaseMethodsTests(BaseExtensionTests):
expected = empty
self.assert_extension_array_equal(result, expected)
def test_shift_fill_value(self, data):
arr = data[:4]
fill_value = data[0] | class BaseMethodsTests(BaseExtensionTests):
expected = empty
self.assert_extension_array_equal(result, expected)
def test_shift_zero_copies(self, data):
result = data.shift(0)
assert result is not data
result = data[:0].shift(2)
assert result is not data
def te... |
def open_spam(self, url):
"spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
"//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
# Just commented them out.
# Can't really tell why keep failing in windows and sparc. | def open_spam(self, url):
"spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
"//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
def test_local_file_open(self):
class DummyURLopener(urllib.URLopener):
def open_local_file(self, url):
return url
for url in ('l... |
def open(self, fullurl, data=None):
name = 'open_' + urltype
self.type = urltype
name = name.replace('-', '_')
if not hasattr(self, name):
if proxy:
return self.open_unknown_proxy(proxy, fullurl, data)
else: | def open(self, fullurl, data=None):
name = 'open_' + urltype
self.type = urltype
name = name.replace('-', '_')
# bpo-35907: disallow the file reading with the type not allowed
if not hasattr(self, name) or name == 'open_local_file':
if proxy:
return s... |
try:
import pickle
except ImportError:
import cPickle as pickle
import marshal
import os
import socket | import base64
import hashlib
import hmac
try:
import cPickle as pickle
except ImportError:
import pickle
import marshal
import os
import socket |
import tempfile
import threading
class PythonFileRunner(object):
"""A class for running python project files"""
| import tempfile
import threading
def _compat_compare_digest(a, b):
"""Implementation of hmac.compare_digest for python < 2.7.7.
This function uses an approach designed to prevent timing analysis by
avoiding content-based short circuiting behaviour, making it appropriate
for cryptography.
"""
... |
class _SocketReceiver(_MessageReceiver):
def __init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data_port = 3037
while self.data_port < 4000:
try:
self.server_socket.bind(('', self.data_port))
break
... | class _SocketReceiver(_MessageReceiver):
def __init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data_port = 3037
self.key = os.urandom(32)
while self.data_port < 4000:
try:
self.server_socket.bind(('localhost', sel... |
def __rope_start_everything():
import sys
import socket
try:
import pickle
except ImportError:
import cPickle as pickle
import marshal
import inspect
import types
import threading
import rope.base.utils.pycompat as pycompat
class _MessageSender(object):
| def __rope_start_everything():
import sys
import socket
try:
import cPickle as pickle
except ImportError:
import pickle
import marshal
import inspect
import types
import threading
import rope.base.utils.pycompat as pycompat
import base64
import hashlib
imp... |
def __rope_start_everything():
class _SocketSender(_MessageSender):
def __init__(self, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', port))
self.my_file = s.makefile('wb')
def send_data(self, data):
if not self... | def __rope_start_everything():
class _SocketSender(_MessageSender):
def __init__(self, port, key):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', port))
self.my_file = s.makefile('wb')
self.key = base64.b64decode(key)
... |
def __rope_start_everything():
def __init__(self, send_info, project_root):
self.project_root = project_root
if send_info.isdigit():
self.sender = _SocketSender(int(send_info))
else:
self.sender = _FileSender(send_info)
| def __rope_start_everything():
def __init__(self, send_info, project_root):
self.project_root = project_root
if send_info[0].isdigit():
port, key = send_info.split(':', 1)
self.sender = _SocketSender(int(port), key)
else:
self.... |
from rope.base.exceptions import ModuleNotFoundError
from rope.base.resources import File, Folder, _ResourceMatcher
try:
import pickle
except ImportError:
import cPickle as pickle
class _Project(object): | from rope.base.exceptions import ModuleNotFoundError
from rope.base.resources import File, Folder, _ResourceMatcher
try:
import cPickle as pickle
except ImportError:
import pickle
class _Project(object): |
except ImportError:
import ropetest.projecttest
import ropetest.codeanalyzetest
import ropetest.type_hinting_test
import ropetest.pycoretest
import ropetest.pyscopestest | except ImportError:
import ropetest.projecttest
import ropetest.codeanalyzetest
import ropetest.doatest
import ropetest.type_hinting_test
import ropetest.pycoretest
import ropetest.pyscopestest |
def suite():
result = unittest.TestSuite()
result.addTests(ropetest.projecttest.suite())
result.addTests(ropetest.codeanalyzetest.suite())
result.addTests(ropetest.type_hinting_test.suite())
result.addTests(ropetest.pycoretest.suite())
result.addTests(ropetest.pyscopestest.suite()) | def suite():
result = unittest.TestSuite()
result.addTests(ropetest.projecttest.suite())
result.addTests(ropetest.codeanalyzetest.suite())
result.addTests(ropetest.doatest.suite())
result.addTests(ropetest.type_hinting_test.suite())
result.addTests(ropetest.pycoretest.suite())
result.addTest... |
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding = _preprocess_padding(padding)
if tf_data_format == 'NHWC':
spatial_start_dim = 1
strides = (1, 1) + strides + (1,)
else:
spatial_start_dim = 2
strides = (1, 1, 1) + strides
x = tf.expand_dims(... | def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding = _preprocess_padding(padding)
if tf_data_format == 'NHWC':
spatial_start_dim = 1
strides = (1,) + strides * 2 + (1,)
else:
spatial_start_dim = 2
strides = (1, 1) + strides * 2
x = tf.expand_di... |
def test_separable_conv_1d():
num_step = 9
for padding in _convolution_paddings:
for multiplier in [1, 2]:
for dilation_rate in [1, 2]:
if padding == 'same':
continue
if dilation_rate != 1:
continue
lay... | def test_separable_conv_1d():
num_step = 9
for padding in _convolution_paddings:
for strides in [1, 2]:
for multiplier in [1, 2]:
for dilation_rate in [1, 2]:
if padding == 'same' and strides != 1:
continue
if d... |
def strip_tags(value):
value = str(value)
while '<' in value and '>' in value:
new_value = _strip_once(value)
if len(new_value) >= len(value):
# _strip_once was not able to detect more tags
break
value = new_value
return value | def strip_tags(value):
value = str(value)
while '<' in value and '>' in value:
new_value = _strip_once(value)
if value.count('<') == new_value.count('<'):
# _strip_once wasn't able to detect more tags.
break
value = new_value
return value |
class TestUtilsHtml(SimpleTestCase):
('&gotcha&#;<>', '&gotcha&#;<>'),
('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'),
('<script>alert()</script>&h', 'alert()h'),
)
for value, output in items:
with self.subTest(value=value, output=output): | class TestUtilsHtml(SimpleTestCase):
('&gotcha&#;<>', '&gotcha&#;<>'),
('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'),
('<script>alert()</script>&h', 'alert()h'),
('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'),
('X<<<<br>br>br>br>X', 'XX'),... |
def gendata4():
data = [gendata1(), gendata2(), gendata4()]
class TestAudioop(unittest.TestCase):
| def gendata4():
data = [gendata1(), gendata2(), gendata4()]
INVALID_DATA = [
('abc', 0),
('abc', 2),
('abc', 4),
]
class TestAudioop(unittest.TestCase):
|
def test_negativelen(self):
self.assertRaises(audioop.error,
audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392)
def test_main():
run_unittest(TestAudioop)
| def test_negativelen(self):
self.assertRaises(audioop.error,
audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392)
def test_issue7673(self):
state = None
for data, size in INVALID_DATA:
size2 = size
self.assertRaises(audioop.error, audioop.getsa... |
def get_meta_refresh(response):
def response_status_message(status):
"""Return status code plus status text descriptive message
>>> response_status_message(200)
'200 OK'
>>> response_status_message(404)
'404 Not Found'
"""
return '%s %s' % (status, to_native_str(http.RESPONSES.get(int(sta... | def get_meta_refresh(response):
def response_status_message(status):
"""Return status code plus status text descriptive message
"""
return '%s %s' % (status, to_native_str(http.RESPONSES.get(int(status), "Unknown Status")))
def response_httprepr(response): |
from six.moves.urllib.parse import urlparse
from scrapy.http import Response, TextResponse, HtmlResponse
from scrapy.utils.python import to_bytes
from scrapy.utils.response import (response_httprepr, open_in_browser,
get_meta_refresh, get_base_url)
__doctests__ = ['scrapy.utils.respo... | from six.moves.urllib.parse import urlparse
from scrapy.http import Response, TextResponse, HtmlResponse
from scrapy.utils.python import to_bytes
from scrapy.utils.response import (response_httprepr, open_in_browser,
get_meta_refresh, get_base_url, response_status_message)
__doctests... |
class ResponseUtilsTest(unittest.TestCase):
resp2 = HtmlResponse("http://www.example.com", body=b"""
<html><body>blahablsdfsal&</body></html>""")
self.assertEqual(get_base_url(resp2), "http://www.example.com") | class ResponseUtilsTest(unittest.TestCase):
resp2 = HtmlResponse("http://www.example.com", body=b"""
<html><body>blahablsdfsal&</body></html>""")
self.assertEqual(get_base_url(resp2), "http://www.example.com")
def test_response_status_message(self):
self.assertEqual(response_sta... |
class Block(PandasObject):
# length checking
check_setitem_lengths(indexer, value, values)
if is_empty_indexer(indexer, arr_value):
# GH#8669 empty indexers
pass | class Block(PandasObject):
# length checking
check_setitem_lengths(indexer, value, values)
exact_match = (
len(arr_value.shape)
and arr_value.shape[0] == values.shape[0]
and arr_value.size == values.size
)
if is_empty_indexer(indexer, arr_valu... |
class Block(PandasObject):
# be e.g. a list; see GH#6043
values[indexer] = value
# if we are an exact match (ex-broadcasting),
# then use the resultant dtype
elif (
len(arr_value.shape)
and arr_value.shape[0] == values.shape[0]
and ar... | class Block(PandasObject):
# be e.g. a list; see GH#6043
values[indexer] = value
elif (
exact_match
and is_categorical_dtype(arr_value.dtype)
and not is_categorical_dtype(values)
):
# GH25495 - If the current dtype is not categori... |
class TestDataFrameIndexingCategorical:
df.value, range(0, 105, 10), right=False, labels=labels
)
def test_loc_indexing_preserves_index_category_dtype(self):
# GH 15166
df = DataFrame( | class TestDataFrameIndexingCategorical:
df.value, range(0, 105, 10), right=False, labels=labels
)
def test_setitem_single_row_categorical(self):
# GH 25495
df = DataFrame({"Alpha": ["a"], "Numeric": [0]})
categories = pd.Categorical(df["Alpha"], categories=["a", ... |
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.utils import split_tzname_delta
class DatabaseOperations(BaseDatabaseOperations):
cast_char_field_without_max_length = "varchar"
explain_prefix = "EXPLAIN"
cast_data_types = {
"AutoField": "integer",
"BigAutoField": "bigint", | from django.db.backends.utils import split_tzname_delta
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):
return set( | __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.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; -... |
def login():
login_user(form.user, remember=remember_me, authn_via=["password"])
after_this_request(_commit)
if not _security._want_json(request):
return redirect(get_post_login_redirect())
if _security._want_json(request):
if current_user.is_authenticated:
... | def login():
login_user(form.user, remember=remember_me, authn_via=["password"])
after_this_request(_commit)
if _security._want_json(request):
return base_render_json(form, include_auth_token=True)
return redirect(get_post_login_redirect())
if _security._want_json(reque... |
def change_password():
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(), form.new_password.data)
if not _security._want_json(request):
do_flash(*get_message("PASSWORD_CHANGE"))
return redirect(
... | def change_password():
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(), form.new_password.data)
if _security._want_json(request):
form.user = current_user
return base_render_json(form, include_auth_toke... |
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
tests_require = [
"Flask-Mongoengine>=0.9.5",
"peewee>=3.11.2",
"Flask-SQLAlchemy>=2.3",
"argon2_cffi>=19.1.0", | version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
tests_require = [
"Flask-Mongoengine~=0.9.5",
"peewee>=3.11.2",
"Flask-SQLAlchemy>=2.3",
"argon2_cffi>=19.1.0", |
"cryptography>=2.3.1",
"isort>=4.2.2",
"mock>=1.3.0",
"mongoengine>=0.15.3",
"mongomock>=3.14.0",
"msgcheck>=2.9",
"pony>=0.7.11",
"phonenumberslite>=8.11.1", | "cryptography>=2.3.1",
"isort>=4.2.2",
"mock>=1.3.0",
"mongoengine~=0.19.1",
"mongomock~=3.19.0",
"msgcheck>=2.9",
"pony>=0.7.11",
"phonenumberslite>=8.11.1", |
def test_session_query(in_app_context):
assert response.status_code == 200
end_nqueries = get_num_queries(app.security.datastore)
assert current_nqueries is None or end_nqueries == (current_nqueries + 2) | def test_session_query(in_app_context):
assert response.status_code == 200
end_nqueries = get_num_queries(app.security.datastore)
assert current_nqueries is None or end_nqueries == (current_nqueries + 2)
@pytest.mark.changeable()
def test_no_get_auth_token(app, client):
# Test that GETs don't return a... |
class TestUtil(unittest.TestCase):
on = js_to_json('{ 0: /* " \n */ ",]" , }')
self.assertEqual(json.loads(on), {'0': ',]'})
on = js_to_json(r'["<p>x<\/p>"]')
self.assertEqual(json.loads(on), ['<p>x</p>'])
| class TestUtil(unittest.TestCase):
on = js_to_json('{ 0: /* " \n */ ",]" , }')
self.assertEqual(json.loads(on), {'0': ',]'})
on = js_to_json('{ 0: // comment\n1 }')
self.assertEqual(json.loads(on), {'0': 1})
on = js_to_json(r'["<p>x<\/p>"]')
self.assertEqual(json.loads(... |
def js_to_json(code):
v = m.group(0)
if v in ('true', 'false', 'null'):
return v
elif v.startswith('/*') or v == ',':
return ""
if v[0] in ("'", '"'): | def js_to_json(code):
v = m.group(0)
if v in ('true', 'false', 'null'):
return v
elif v.startswith('/*') or v.startswith('//') or v == ',':
return ""
if v[0] in ("'", '"'): |
def js_to_json(code):
return re.sub(r'''(?sx)
"(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:) | def js_to_json(code):
return re.sub(r'''(?sx)
"(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
'(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
/\*.*?\*/|//[^\n]*|,(?=\s*[\]}])|
[a-zA-Z_][.a-zA-Z_0-9]*|
\b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
[0-9]+(?=\s*:) |
from thefuck.rules.php_s import get_new_command, match
from thefuck.types import Command
def test_match():
assert match(Command('php -s localhost:8000', ''))
@pytest.mark.parametrize('command', [ | from thefuck.rules.php_s import get_new_command, match
from thefuck.types import Command
@pytest.mark.parametrize('command', [
Command('php -s localhost:8000', ''),
Command('php -t pub -s 0.0.0.0:8080', '')
])
def test_match(command):
assert match(command)
@pytest.mark.parametrize('command', [ |
def test_not_match(command):
assert not match(command)
def test_get_new_command():
new_command = get_new_command(Command('php -s localhost:8000', ''))
assert new_command == 'php -S localhost:8000' | def test_not_match(command):
assert not match(command)
@pytest.mark.parametrize('command, new_command', [
(Command('php -s localhost:8000', ''), 'php -S localhost:8000'),
(Command('php -t pub -s 0.0.0.0:8080', ''), 'php -t pub -S 0.0.0.0:8080')
])
def test_get_new_command(command, new_command):
assert... |
from thefuck.utils import replace_argument, for_app
@for_app('php')
def match(command):
return "php -s" in command.script
def get_new_command(command):
return replace_argument(command.script, "-s", "-S")
requires_output = False | from thefuck.utils import replace_argument, for_app
@for_app('php')
def match(command):
return " -s " in command.script
def get_new_command(command):
return replace_argument(command.script, "-s", "-S") |
class TestFish(object):
assert not shell.how_to_configure().can_configure_automatically
def test_info(self, shell, Popen):
Popen.return_value.stdout.read.side_effect = [b'3.5.9']
assert shell.info() == 'Fish Shell 3.5.9' | class TestFish(object):
assert not shell.how_to_configure().can_configure_automatically
def test_info(self, shell, Popen):
Popen.return_value.stdout.read.side_effect = [b'fish, version 3.5.9\n']
assert shell.info() == 'Fish Shell 3.5.9'
assert Popen.call_args[0][0] == ['fish', '--ve... |
class Fish(Generic):
def info(self):
"""Returns the name and version of the current shell"""
proc = Popen(['fish', '-c', 'echo $FISH_VERSION'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').strip()
return u'Fish Shell {}'.format(versi... | class Fish(Generic):
def info(self):
"""Returns the name and version of the current shell"""
proc = Popen(['fish', '--version'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').split()[-1]
return u'Fish Shell {}'.format(version)
de... |
INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... | INTERNAL_RESULT_KEYS = ('add_host', 'add_group')
LOCALHOST = ('127.0.0.1', 'localhost', '::1')
MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script')
MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw')
RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo... |
from ansible.module_utils.common._collections_compat import MutableMapping, Muta
from ansible.plugins.loader import connection_loader
from ansible.utils.display import Display
display = Display()
| from ansible.module_utils.common._collections_compat import MutableMapping, Muta
from ansible.plugins.loader import connection_loader
from ansible.utils.display import Display
display = Display()
|
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 text_to_word_sequence(text,
if lower:
text = text.lower()
if sys.version_info < (3,) and isinstance(text, unicode):
translate_map = dict((ord(c), unicode(split)) for c in filters)
else:
translate_map = maketrans(filters, split * len(filters))
text = text.translate(translate... | def text_to_word_sequence(text,
if lower:
text = text.lower()
if sys.version_info < (3,):
if isinstance(text, unicode):
translate_map = dict((ord(c), unicode(split)) for c in filters)
text = text.translate(translate_map)
elif len(split) == 1:
translat... |
def test_text_to_word_sequence():
assert text_to_word_sequence(text) == ['hello', 'world']
def test_text_to_word_sequence_unicode():
text = u'ali! veli? kırk dokuz elli'
assert text_to_word_sequence(text) == [u'ali', u'veli', u'kırk', u'dokuz', u'elli']
def test_tokenizer_unicode():
texts = [u'ali v... | def test_text_to_word_sequence():
assert text_to_word_sequence(text) == ['hello', 'world']
def test_text_to_word_sequence_multichar_split():
text = 'hello!stop?world!'
assert text_to_word_sequence(text, split='stop') == ['hello', 'world']
def test_text_to_word_sequence_unicode():
text = u'ali! veli?... |
class Axis(martist.Artist):
self._minor_tick_kw.update(kwtrans)
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# special-case label color to also apply to the offset text
if 'labelcolor' in kwtrans:
self.offsetText.s... | class Axis(martist.Artist):
self._minor_tick_kw.update(kwtrans)
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# labelOn and labelcolor also apply to the offset text.
if 'label1On' in kwtrans or 'label2On' in kwtrans:
... |
def test_offset_label_color():
assert ax.yaxis.get_offset_text().get_color() == 'red'
def test_large_offset():
fig, ax = plt.subplots()
ax.plot((1 + np.array([0, 1.e-12])) * 1.e27) | def test_offset_label_color():
assert ax.yaxis.get_offset_text().get_color() == 'red'
def test_offset_text_visible():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot([1.01e9, 1.02e9, 1.03e9])
ax.yaxis.set_tick_params(label1On=False, label2On=True)
assert ax.yaxis.get_offset_text().get... |
from vyper.builtin_interfaces import ERC20, ERC721
from vyper.cli.utils import extract_file_interface_imports
from vyper.compiler import compile_code, compile_codes
from vyper.exceptions import InterfaceViolation, StructureException
def test_basic_extract_interface(): | from vyper.builtin_interfaces import ERC20, ERC721
from vyper.cli.utils import extract_file_interface_imports
from vyper.compiler import compile_code, compile_codes
from vyper.exceptions import ArgumentException, InterfaceViolation, StructureException
def test_basic_extract_interface(): |
def test():
assert erc20.balanceOf(sender) == 1000
def test_units_interface(w3, get_contract):
code = """
import balanceof as BalanceOf | def test():
assert erc20.balanceOf(sender) == 1000
# test data returned from external interface gets clamped
@pytest.mark.parametrize("typ", ("int128", "uint8"))
def test_external_interface_int_clampers(get_contract, assert_tx_failed, typ):
external_contract = f"""
@external
def ok() -> {typ}:
return 1
@... |
def _dynarray_make_setter(dst, src):
# for ABI-encoded dynamic data, we must loop to unpack, since
# the layout does not match our memory layout
should_loop = (
src.encoding in (Encoding.ABI, Encoding.JSON_ABI)
and src.typ.subtype.abi_type.is_dynamic()
)
... | def _dynarray_make_setter(dst, src):
# for ABI-encoded dynamic data, we must loop to unpack, since
# the layout does not match our memory layout
should_loop = src.encoding == Encoding.ABI and src.typ.subtype.abi_type.is_dynamic()
# if the subtype is dynamic, there might be a lot of
... |
def _get_element_ptr_tuplelike(parent, key):
ofst = 0 # offset from parent start
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
| def _get_element_ptr_tuplelike(parent, key):
ofst = 0 # offset from parent start
if parent.encoding == Encoding.ABI:
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
|
def _get_element_ptr_array(parent, key, array_bounds_check):
# NOTE: there are optimization rules for this when ix or bound is literal
ix = IRnode.from_list([clamp_op, ix, bound], typ=ix.typ)
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
... | def _get_element_ptr_array(parent, key, array_bounds_check):
# NOTE: there are optimization rules for this when ix or bound is literal
ix = IRnode.from_list([clamp_op, ix, bound], typ=ix.typ)
if parent.encoding == Encoding.ABI:
if parent.location == STORAGE:
raise CompilerPanic(... |
def _freshname(name):
# returns True if t is ABI encoded and is a type that needs any kind of
# validation
def needs_clamp(t, encoding):
if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
return False
if isinstance(t, (ByteArrayLike, DArrayType)):
if encoding == Encoding.JSON_ABI:
... | def _freshname(name):
# returns True if t is ABI encoded and is a type that needs any kind of
# validation
def needs_clamp(t, encoding):
if encoding == Encoding.VYPER:
return False
if encoding != Encoding.ABI:
raise CompilerPanic("unreachable") # pragma: notest
if isinstance(t, (ByteArrayLi... |
check_assign,
check_external_call,
dummy_node_for_type,
get_element_ptr,
)
from vyper.codegen.ir_node import Encoding, IRnode
from vyper.codegen.types import InterfaceType, TupleType, get_type_for_exact_size
from vyper.exceptions import StateAccessViolation, TypeCheckFailure
| check_assign,
check_external_call,
dummy_node_for_type,
make_setter,
needs_clamp,
)
from vyper.codegen.ir_node import Encoding, IRnode
from vyper.codegen.types import InterfaceType, TupleType, get_type_for_exact_size
from vyper.codegen.types.convert import new_type_to_old_type
from vyper.exceptions ... |
def _pack_arguments(contract_sig, args, context):
return buf, mstore_method_id + [encode_args], args_ofst, args_len
def _returndata_encoding(contract_sig):
if contract_sig.is_from_json:
return Encoding.JSON_ABI
return Encoding.ABI
def _unpack_returndata(buf, contract_sig, skip_contract_check, co... | def _pack_arguments(contract_sig, args, context):
return buf, mstore_method_id + [encode_args], args_ofst, args_len
def _unpack_returndata(buf, contract_sig, skip_contract_check, context, expr):
# expr.func._metadata["type"].return_type is more accurate
# than contract_sig.return_type in the case of JSON ... |
def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
# TODO move the -1 optimization to IR optimizer
if not skip_contract_check:
ret += [["assert", ["gt", "returndatasize",... | def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
if not skip_contract_check:
ret += [["assert", ["ge", "returndatasize", min_return_size]]]
encoding = Encoding.ABI
... |
def _external_call_helper(
buf, arg_packer, args_ofst, args_len = _pack_arguments(contract_sig, args_ir, context)
ret_unpacker, ret_ofst, ret_len = _unpack_returndata(
buf, contract_sig, skip_contract_check, context
)
sub += arg_packer | def _external_call_helper(
buf, arg_packer, args_ofst, args_len = _pack_arguments(contract_sig, args_ir, context)
ret_unpacker, ret_ofst, ret_len = _unpack_returndata(
buf, contract_sig, skip_contract_check, context, expr
)
sub += arg_packer |
def _external_call_helper(
if contract_sig.return_type is not None:
sub += ret_unpacker
ret = IRnode.from_list(
sub,
typ=contract_sig.return_type,
location=MEMORY,
# set the encoding to ABI here, downstream code will decode and add clampers.
encoding=_returndata_... | def _external_call_helper(
if contract_sig.return_type is not None:
sub += ret_unpacker
return IRnode.from_list(sub, typ=contract_sig.return_type, location=MEMORY)
def _get_special_kwargs(stmt_expr, context): |
import vyper.utils as util
from vyper.address_space import CALLDATA, DATA, MEMORY
from vyper.ast.signatures.function_signature import FunctionSignature, VariableRecord
from vyper.codegen.context import Context
from vyper.codegen.core import get_element_ptr, getpos, make_setter
from vyper.codegen.expr import Expr
from v... | import vyper.utils as util
from vyper.address_space import CALLDATA, DATA, MEMORY
from vyper.ast.signatures.function_signature import FunctionSignature, VariableRecord
from vyper.codegen.abi_encoder import abi_encoding_matches_vyper
from vyper.codegen.context import Context
from vyper.codegen.core import get_element_pt... |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
arg_ir = get_element_ptr(base_args_ofst, i)
if _should_decode(arg.typ):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
dst = IRno... | def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
arg_ir = get_element_ptr(base_args_ofst, i)
if needs_clamp(arg.typ, Encoding.ABI):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
... |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
# leave it in place
context.vars[arg.name] = VariableRecord(
name=arg.name, | def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
assert abi_encoding_matches_vyper(arg.typ)
# leave it in place
context.vars[arg.name] = VariableRec... |
class Encoding(Enum):
VYPER = auto()
# abi encoded, default for args/return values from external funcs
ABI = auto()
# abi encoded, same as ABI but no clamps for bytestrings
JSON_ABI = auto()
# future: packed
| class Encoding(Enum):
VYPER = auto()
# abi encoded, default for args/return values from external funcs
ABI = auto()
# future: packed
|
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType(typ.value_type)
if isinstance(typ, new.Struc... | def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType([new_type_to_old_type(t) for t in typ.value_type... |
class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): | class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def __invert__(self):
return type(self)(~self._data, self._mask)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
arr = operator.inv(com.values_from_object(self))
return self.__array_wrap__(arr)
def __nonzero__(self):
raise ValueError( | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
new_data = self._data.apply(operator.invert)
result = self._constructor(new_data).__finalize__(self)
return result
def __nonzero__(self):
raise ValueError... |
def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = result.to_dense()
result = check_bool_array_indexer(index, result)
return result | def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = np.asarray(result)
result = check_bool_array_indexer(index, result)
return result |
def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
@pytest.mark.parametrize("fill_value", [0, np.nan])
@pytest.mark.parametrize("op", [operator.pos, operator.neg]) | def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
result = ~pd.Series(sparray)
expected = pd.Series(expected)
tm.assert_series_equal(result, expected)
result = ~pd.DataFrame({"A": sparray})
expected = pd.DataFram... |
def test_ufunc_reduce_raises(values):
np.add.reduce(a)
class TestLogicalOps(BaseOpsUtil):
def test_numpy_scalars_ok(self, all_logical_operators):
a = pd.array([True, False, None], dtype="boolean") | def test_ufunc_reduce_raises(values):
np.add.reduce(a)
class TestUnaryOps:
def test_invert(self):
a = pd.array([True, False, None], dtype="boolean")
expected = pd.array([False, True, None], dtype="boolean")
tm.assert_extension_array_equal(~a, expected)
expected = pd.Series... |
from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil # noqa
from .printing import BasePrintingTests # noqa
from... | from .interface import BaseInterfaceTests # noqa
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
from .ops import ( # noqa
BaseArithmeticOpsTests,
BaseComparisonOpsTests,
BaseOpsUtil,
BaseUnaryOpsTests,
)
from .printi... |
class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__") | class BaseComparisonOpsTests(BaseOpsUtil):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__")
class BaseUnaryOpsTests(BaseOpsUtil):
def test_invert(self, data):
s = pd.Series(data, name="name")
result = ~s
... |
class TestPrinting(base.BasePrintingTests):
pass
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass | class TestPrinting(base.BasePrintingTests):
pass
class TestUnaryOps(base.BaseUnaryOpsTests):
pass
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass |
class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
@pytest.mark.parametrize(
"df",
[ | class TestDataFrameUnaryOperators:
tm.assert_frame_equal(-(df < 0), ~(df < 0))
def test_invert_mixed(self):
shape = (10, 5)
df = pd.concat(
[
pd.DataFrame(np.zeros(shape, dtype="bool")),
pd.DataFrame(np.zeros(shape, dtype=int)),
],
... |
from thefuck.rules.ls_lah import match, get_new_command
def test_match():
assert match(Mock(script='ls file.py'), None)
assert match(Mock(script='ls /opt'), None)
assert not match(Mock(script='ls -lah /opt'), None)
def test_get_new_command(): | from thefuck.rules.ls_lah import match, get_new_command
def test_match():
assert match(Mock(script='ls'), None)
assert match(Mock(script='ls file.py'), None)
assert match(Mock(script='ls /opt'), None)
assert not match(Mock(script='ls -lah /opt'), None)
assert not match(Mock(script='pacman -S binut... |
def match(command, settings):
return 'ls' in command.script and not ('ls -' in command.script)
def get_new_command(command, settings): | def match(command, settings):
return (command.script == 'ls'
or command.script.startswith('ls ')
and not ('ls -' in command.script))
def get_new_command(command, settings): |
class Errors(object):
"details: https://spacy.io/api/lemmatizer#init")
E174 = ("Architecture '{name}' not found in registry. Available "
"names: {names}")
@add_codes | class Errors(object):
"details: https://spacy.io/api/lemmatizer#init")
E174 = ("Architecture '{name}' not found in registry. Available "
"names: {names}")
E175 = ("Can't remove rule for unknown match pattern ID: {key}")
@add_codes |
def test_matcher_sets_return_correct_tokens(en_vocab):
matches = matcher(doc)
texts = [Span(doc, s, e, label=L).text for L, s, e in matches]
assert texts == ["zero", "one", "two"] | def test_matcher_sets_return_correct_tokens(en_vocab):
matches = matcher(doc)
texts = [Span(doc, s, e, label=L).text for L, s, e in matches]
assert texts == ["zero", "one", "two"]
def test_matcher_remove(en_vocab):
matcher = Matcher(en_vocab)
pattern = [{"ORTH": "test"}, {"OP": "?"}]
assert le... |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
new_index = self.index[loc]
if is_scalar(loc):
new_values = self._data.fast_xs(loc)
# may need to box a datelike-scalar
#
# if we encounter an array-like and we only have 1 dim
... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
new_index = self.index[loc]
if is_scalar(loc):
# In this case loc should be an integer
if self.ndim == 1:
# if we encounter an array-like and we only have 1 dim
# that me... |
class SingleBlockManager(BlockManager):
fast path for getting a cross-section
return a view of the data
"""
return self._block.values[loc]
def concat(self, to_concat, new_axis) -> "SingleBlockManager":
""" | class SingleBlockManager(BlockManager):
fast path for getting a cross-section
return a view of the data
"""
raise NotImplementedError("Use series._values[loc] instead")
def concat(self, to_concat, new_axis) -> "SingleBlockManager":
""" |
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):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
""" | class BCryptSHA256PasswordHasher(BasePasswordHasher):
algorithm, empty, algostr, rounds, data = encoded.split('$', 4)
return int(rounds) != self.rounds
def harden_runtime(self, password, encoded):
_, data = encoded.split('$', 1)
salt = data[:29] # Length of the salt in bcrypt.
... |
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):
finally:
hasher.rounds = old_rounds
def test_unusable(self):
encoded = make_password(None)
self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH) | class TestUtilsHashPass(SimpleTestCase):
finally:
hasher.rounds = old_rounds
@skipUnless(bcrypt, "bcrypt not installed")
def test_bcrypt_harden_runtime(self):
hasher = get_hasher('bcrypt')
self.assertEqual('bcrypt', hasher.algorithm)
with mock.patch.object(hasher, '... |
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.