buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
import datetime
import unittest
from unittest import mock
from urllib.parse import quote_plus | import datetime
import sys
import unittest
from unittest import mock
from urllib.parse import quote_plus |
from urllib.parse import quote_plus
from django.test import SimpleTestCase
from django.utils.encoding import (
DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes,
force_text, get_system_encoding, iri_to_uri, smart_bytes, smart_text,
uri_to_iri,
)
from django.utils.functional import Simp... | from urllib.parse import quote_plus
from django.test import SimpleTestCase
from django.utils.encoding import (
DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes,
force_text, get_system_encoding, iri_to_uri, repercent_broken_unicode,
smart_bytes, smart_text, uri_to_iri,
)
from django.ut... |
class TestEncodingUtils(SimpleTestCase):
with mock.patch('locale.getdefaultlocale', side_effect=Exception):
self.assertEqual(get_system_encoding(), 'ascii')
class TestRFC3987IEncodingUtils(unittest.TestCase):
| class TestEncodingUtils(SimpleTestCase):
with mock.patch('locale.getdefaultlocale', side_effect=Exception):
self.assertEqual(get_system_encoding(), 'ascii')
def test_repercent_broken_unicode_recursion_error(self):
# Prepare a string long enough to force a recursion error if the tested
... |
class GroupBy(_GroupBy):
# >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :]
# but this hits https://github.com/pandas-dev/pandas/issues/10710
# which doesn't reorder the list-like `q` on the inner level.
order = np.roll(list(range(result.index.nlevels)), -1)
... | class GroupBy(_GroupBy):
# >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :]
# but this hits https://github.com/pandas-dev/pandas/issues/10710
# which doesn't reorder the list-like `q` on the inner level.
order = list(range(1, result.index.nlevels)) + [0]
... |
def test_quantile_array_multiple_levels():
tm.assert_frame_equal(result, expected)
def test_quantile_raises():
df = pd.DataFrame(
[["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"] | def test_quantile_array_multiple_levels():
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("frame_size", [(2, 3), (100, 10)])
@pytest.mark.parametrize("groupby", [[0], [0, 1]])
@pytest.mark.parametrize("q", [[0.5, 0.6]])
def test_groupby_quantile_with_arraylike_q_and_int_columns(frame_size, group... |
class Index(IndexOpsMixin, PandasObject):
is_null_slicer = start is None and stop is None
is_index_slice = is_int(start) and is_int(stop)
is_positional = is_index_slice and not self.is_integer()
if kind == "getitem":
""" | class Index(IndexOpsMixin, PandasObject):
is_null_slicer = start is None and stop is None
is_index_slice = is_int(start) and is_int(stop)
is_positional = is_index_slice and not (
self.is_integer() or self.is_categorical()
)
if kind == "getitem":
""" |
class CategoricalIndex(Index, accessor.PandasDelegate):
take_nd = take
def map(self, mapper):
"""
Map values using input correspondence (a dict, Series, or function). | class CategoricalIndex(Index, accessor.PandasDelegate):
take_nd = take
@Appender(_index_shared_docs["_maybe_cast_slice_bound"])
def _maybe_cast_slice_bound(self, label, side, kind):
if kind == "loc":
return label
return super()._maybe_cast_slice_bound(label, side, kind)
d... |
class TestCategoricalIndex:
df.reindex(["a"], limit=2)
def test_loc_slice(self):
# slicing
# not implemented ATM
# GH9748
msg = (
"cannot do slice indexing on {klass} with these "
r"indexers \[1\] of {kind}".format(
klass=str(Cate... | class TestCategoricalIndex:
df.reindex(["a"], limit=2)
def test_loc_slice(self):
# GH9748
with pytest.raises(KeyError, match="1"):
self.df.loc[1:5]
result = self.df.loc["b":"c"]
expected = self.df.iloc[[2, 3, 4]]
tm.assert_frame_equal(result, expecte... |
class TestCategoricalIndex:
# GH-17569
cat_idx = CategoricalIndex(idx_values, ordered=ordered_fixture)
df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx)
# scalar selection
result = df.loc[idx_values[0]] | class TestCategoricalIndex:
# GH-17569
cat_idx = CategoricalIndex(idx_values, ordered=ordered_fixture)
df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx)
sl = slice(idx_values[0], idx_values[1])
# scalar selection
result = df.loc[idx_values[0]] |
class TestCategoricalIndex:
expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
tm.assert_frame_equal(result, expected)
# scalar assignment
result = df.copy()
result.loc[idx_values[0]] = "qux" | class TestCategoricalIndex:
expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
tm.assert_frame_equal(result, expected)
# slice selection
result = df.loc[sl]
expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
tm.assert_frame_equal(r... |
class TestCategoricalIndex:
result.loc[idx_values[:2], "A"] = ["qux", "qux2"]
expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
tm.assert_frame_equal(result, expected) | class TestCategoricalIndex:
result.loc[idx_values[:2], "A"] = ["qux", "qux2"]
expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
tm.assert_frame_equal(result, expected)
# slice assignment
result = df.copy()
result.loc[sl, "A"] = ["qux", "qux2"]
ex... |
class DataFrame(NDFrame):
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
)[1] | class DataFrame(NDFrame):
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
self.loc._ensure_listlike_indexer(key, axis=1)
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
... |
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
is_integer,
is_iterator,
is_list_like, | from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
is_hashable,
is_integer,
is_iterator,
is_list_like, |
class _LocationIndexer(_NDFrameIndexerBase):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.axis is not None:
return self._convert_tuple(key, is_setter=True)
| class _LocationIndexer(_NDFrameIndexerBase):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.name == "loc":
self._ensure_listlike_indexer(key)
if self.axis is not None:
return self._convert_tuple(key, is_setter=True)
|
class _LocationIndexer(_NDFrameIndexerBase):
raise
raise IndexingError(key) from e
def __setitem__(self, key, value):
if isinstance(key, tuple):
key = tuple(com.apply_if_callable(x, self.obj) for x in key) | class _LocationIndexer(_NDFrameIndexerBase):
raise
raise IndexingError(key) from e
def _ensure_listlike_indexer(self, key, axis=None):
"""
Ensure that a list-like of column labels are all present by adding them if
they do not already exist.
Parameters
... |
class TestDataFrameIndexing:
expected = Series(tuples, index=float_frame.index, name="tuples")
tm.assert_series_equal(result, expected)
def test_setitem_multi_index(self):
# GH7655, test that assigning to a sub-frame of a frame
# with multi-index columns aligns both rows and columns | class TestDataFrameIndexing:
expected = Series(tuples, index=float_frame.index, name="tuples")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"columns,box,expected",
[
(
["A", "B", "C", "D"],
7,
pd.DataF... |
class TestDataFrameIndexing:
float_frame["col6"] = series
tm.assert_series_equal(series, float_frame["col6"], check_names=False)
msg = (
r"\"None of \[Float64Index\(\[.*dtype='float64'\)\] are in the "
r"\[columns\]\""
)
with pytest.raises(KeyError, match... | class TestDataFrameIndexing:
float_frame["col6"] = series
tm.assert_series_equal(series, float_frame["col6"], check_names=False)
# set ndarray
arr = np.random.randn(len(float_frame))
float_frame["col9"] = arr |
Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No"""
assert is_scalar(result) and result == "Z"
def test_loc_coercion(self):
# 12411 | Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No"""
assert is_scalar(result) and result == "Z"
@pytest.mark.parametrize(
"index,box,expected",
[
(
([0, 2], ["A", "B", "C", "D"]),
7,
pd.DataFrame(
... |
class Bidirectional(Wrapper):
return self.forward_layer.updates + self.backward_layer.updates
return []
@property
def losses(self):
if hasattr(self.forward_layer, 'losses'):
return self.forward_layer.losses + self.backward_layer.losses
return []
@property
... | class Bidirectional(Wrapper):
return self.forward_layer.updates + self.backward_layer.updates
return []
def get_updates_for(self, inputs=None):
forward_updates = self.forward_layer.get_updates_for(inputs)
backward_updates = self.backward_layer.get_updates_for(inputs)
ret... |
def test_Bidirectional_trainable():
assert len(layer.trainable_weights) == 6
if __name__ == '__main__':
pytest.main([__file__]) | def test_Bidirectional_trainable():
assert len(layer.trainable_weights) == 6
@keras_test
def test_Bidirectional_updates():
x = Input(shape=(3, 2))
layer = wrappers.Bidirectional(layers.SimpleRNN(3))
assert len(layer.updates) == 0
assert len(layer.get_updates_for(None)) == 0
assert len(layer.ge... |
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
from django.utils.functional import cached_property
from django.utils.tree impo... | from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
from django.utils.functional import cached_property
from django.utils.regex_hel... |
class Query(BaseExpression):
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def add_annotation(self, annotation, alias, is_summary=False, select=True):
"""Add a single annotation expression to the Query."""
annotation = annotation.resolve_expression(
... | class Query(BaseExpression):
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def check_alias(self, alias):
if FORBIDDEN_ALIAS_PATTERN.search(alias):
raise ValueError(
"Column aliases cannot contain whitespace characters, quotation mar... |
class Query(BaseExpression):
else:
param_iter = iter([])
for name, entry in select.items():
entry = str(entry)
entry_params = []
pos = entry.find("%s") | class Query(BaseExpression):
else:
param_iter = iter([])
for name, entry in select.items():
self.check_alias(name)
entry = str(entry)
entry_params = []
pos = entry.find("%s") |
class AggregateTestCase(TestCase):
)
self.assertEqual(len(qs), 6)
def test_exists_extra_where_with_aggregate(self):
qs = Book.objects.annotate(
count=Count("id"), | class AggregateTestCase(TestCase):
)
self.assertEqual(len(qs), 6)
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "aggregation_author"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolo... |
class NonAggregateAnnotationTestCase(TestCase):
],
)
class AliasTests(TestCase):
@classmethod | class NonAggregateAnnotationTestCase(TestCase):
],
)
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolons, or SQL ... |
class AliasTests(TestCase):
with self.subTest(operation=operation):
with self.assertRaisesMessage(FieldError, msg):
getattr(qs, operation)("rating_alias") | class AliasTests(TestCase):
with self.subTest(operation=operation):
with self.assertRaisesMessage(FieldError, msg):
getattr(qs, operation)("rating_alias")
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
... |
class ValuesExpressionsTests(TestCase):
[{"salary": 10}, {"salary": 20}, {"salary": 30}],
)
def test_values_expression_group_by(self):
# values() applies annotate() first, so values selected are grouped by
# id, not firstname. | class ValuesExpressionsTests(TestCase):
[{"salary": 10}, {"salary": 20}, {"salary": 30}],
)
def test_values_expression_alias_sql_injection(self):
crafted_alias = """injected_name" from "expressions_company"; --"""
msg = (
"Column aliases cannot contain whitespace cha... |
class Queries5Tests(TestCase):
Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s"
)
def test_queryset_reuse(self):
# Using querysets doesn't mutate aliases.
authors = Author.objects.filter(Q(name="a1") | Q(name="nonexistent")) | class Queries5Tests(TestCase):
Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s"
)
def test_extra_select_alias_sql_injection(self):
crafted_alias = """injected_name" from "queries_note"; --"""
msg = (
"Column aliases cannot contain whitespace character... |
def _has_sneaky_javascript(self, style):
return True
if 'expression(' in style:
return True
if '</noscript' in style:
# e.g. '<noscript><style><a title="</noscript><img src=x onerror=alert(1)>">'
return True | def _has_sneaky_javascript(self, style):
return True
if 'expression(' in style:
return True
if '@import' in style:
return True
if '</noscript' in style:
# e.g. '<noscript><style><a title="</noscript><img src=x onerror=alert(1)>">'
retur... |
def test_sneaky_js_in_math_style(self):
b'<math><style>/* deleted */</style></math>',
lxml.html.tostring(clean_html(s)))
def test_formaction_attribute_in_button_input(self):
# The formaction attribute overrides the form's action and should be
# treated as a malicious link at... | def test_sneaky_js_in_math_style(self):
b'<math><style>/* deleted */</style></math>',
lxml.html.tostring(clean_html(s)))
def test_sneaky_import_in_style(self):
# Prevent "@@importimport" -> "@import" replacement.
style_codes = [
"@@importimport(extstyle.css)",
... |
def str_repeat(arr, repeats):
else:
def rep(x, r):
try:
return bytes.__mul__(x, r)
except TypeError: | def str_repeat(arr, repeats):
else:
def rep(x, r):
if x is libmissing.NA:
return x
try:
return bytes.__mul__(x, r)
except TypeError: |
class TestStringMethods:
assert isinstance(rs, Series)
tm.assert_series_equal(rs, xp)
def test_match(self):
# New match behavior introduced in 0.13
values = Series(["fooBAD__barBAD", np.nan, "foo"]) | class TestStringMethods:
assert isinstance(rs, Series)
tm.assert_series_equal(rs, xp)
def test_repeat_with_null(self):
# GH: 31632
values = Series(["a", None], dtype="string")
result = values.str.repeat([3, 4])
exp = Series(["aaa", None], dtype="string")
tm.a... |
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.requests import Request | from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.requests import Request |
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()}
) | async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": jsonable_encoder(exc.errors())},
) |
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.testclient import TestClient
app = FastAPI() | from decimal import Decimal
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel, condecimal
from starlette.testclient import TestClient
app = FastAPI() |
app = FastAPI()
class Item(BaseModel):
name: str
age: int
@app.post("/items/") | app = FastAPI()
class Item(BaseModel):
name: str
age: condecimal(gt=Decimal(0.0))
@app.post("/items/") |
openapi_schema = {
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"age": {"title": "Age", "type": "integer"},
},
},
"ValidationError": { | openapi_schema = {
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"age": {"title": "Age", "exclusiveMinimum": 0.0, "type": "number"},
},
},
"ValidationError": { |
openapi_schema = {
},
}
multiple_errors = {
"detail": [
{ | openapi_schema = {
},
}
single_error = {
"detail": [
{
"ctx": {"limit_value": 0.0},
"loc": ["body", "item", 0, "age"],
"msg": "ensure this value is greater than 0",
"type": "value_error.number.not_gt",
}
]
}
multiple_errors = {
"detail": ... |
multiple_errors = {
},
{
"loc": ["body", "item", 0, "age"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
},
{
"loc": ["body", "item", 1, "name"], | multiple_errors = {
},
{
"loc": ["body", "item", 0, "age"],
"msg": "value is not a valid decimal",
"type": "type_error.decimal",
},
{
"loc": ["body", "item", 1, "name"], |
multiple_errors = {
},
{
"loc": ["body", "item", 1, "age"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
},
]
} | multiple_errors = {
},
{
"loc": ["body", "item", 1, "age"],
"msg": "value is not a valid decimal",
"type": "type_error.decimal",
},
]
} |
def test_put_correct_body():
assert response.json() == {"item": [{"name": "Foo", "age": 5}]}
def test_put_incorrect_body():
response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}])
assert response.status_code == 422
assert response.json() == multiple_errors | def test_put_correct_body():
assert response.json() == {"item": [{"name": "Foo", "age": 5}]}
def test_jsonable_encoder_requiring_error():
response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}])
assert response.status_code == 422
assert response.json() == single_error
def test_put_inco... |
from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name = 'auth/widgets/read_only_password_hash.html'
read_only = True | from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
def _unicode_ci_compare(s1, s2):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return unicodeda... |
class PasswordResetForm(forms.Form):
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % UserModel.get_email_field_name(): email,
'is_active': True,
... | class PasswordResetForm(forms.Form):
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
email_field_name = UserModel.get_email_field_name()
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % email_field_na... |
class PasswordResetForm(forms.Form):
user.
"""
email = self.cleaned_data["email"]
for user in self.get_users(email):
if not domain_override:
current_site = get_current_site(request) | class PasswordResetForm(forms.Form):
user.
"""
email = self.cleaned_data["email"]
email_field_name = UserModel.get_email_field_name()
for user in self.get_users(email):
if not domain_override:
current_site = get_current_site(request) |
class PasswordResetForm(forms.Form):
domain = current_site.domain
else:
site_name = domain = domain_override
context = {
'email': email,
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64... | class PasswordResetForm(forms.Form):
domain = current_site.domain
else:
site_name = domain = domain_override
user_email = getattr(user, email_field_name)
context = {
'email': user_email,
'domain': domain,
... |
class PasswordResetForm(forms.Form):
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
email, html_email_template_name=html_email_template_name,
)
| class PasswordResetForm(forms.Form):
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
user_email, html_email_template_name=html_email_template_name,
)
|
class PasswordResetFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
def test_nonexistent_email(self):
"""
Test nonexistent email address. This should not fail because it would | class PasswordResetFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
def test_user_email_unicode_collision(self):
User.objects.create_user('mike123', 'mike@example.org', 'test123')
User.ob... |
def test_bad_server_hostname(self):
with self.assertRaises(ValueError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
server_hostname=".example.org")
class MemoryBIOTests(unittest.TestCase): | def test_bad_server_hostname(self):
with self.assertRaises(ValueError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
server_hostname=".example.org")
with self.assertRaises(TypeError):
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
... |
class Series(base.IndexOpsMixin, generic.NDFrame):
else:
return self.iloc[key]
if isinstance(key, list):
# handle the dup indexing case GH#4246
return self.loc[key]
return self.reindex(key)
def _get_values_tuple(self, key):
# mpl hackaro... | class Series(base.IndexOpsMixin, generic.NDFrame):
else:
return self.iloc[key]
# handle the dup indexing case GH#4246
return self.loc[key]
def _get_values_tuple(self, key):
# mpl hackaround |
def test_getitem_boolean_empty():
# GH5877
# indexing with empty series
s = Series(["A", "B"])
expected = Series(np.nan, index=["C"], dtype=object)
result = s[Series(["C"], dtype=object)]
tm.assert_series_equal(result, expected)
s = Series(["A", "B"])
expected = Series(dtype=object, in... | def test_getitem_boolean_empty():
# GH5877
# indexing with empty series
s = Series(["A", "B"])
expected = Series(dtype=object, index=Index([], dtype="int64"))
result = s[Series([], dtype=object)] |
class TestSeriesGetitemSlices:
class TestSeriesGetitemListLike:
def test_getitem_intlist_intindex_periodvalues(self):
ser = Series(period_range("2000-01-01", periods=10, freq="D"))
| class TestSeriesGetitemSlices:
class TestSeriesGetitemListLike:
@pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series])
def test_getitem_no_matches(self, box):
# GH#33462 we expect the same behavior for list/ndarray/Index/Series
ser = Series(["A", "B"])
key = Series(["C... |
from collections import namedtuple
from typing import Dict, List
from netaddr import IPSet
from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST
from synapse.python_dependencies import DependencyException, check_requirements
from synapse.util.module_loader import load_module
| from collections import namedtuple
from typing import Dict, List
from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST, generate_ip_set
from synapse.python_dependencies import DependencyException, check_requirements
from synapse.util.module_loader import load_module
|
def read_config(self, config, **kwargs):
"to work"
)
self.url_preview_ip_range_blacklist = IPSet(
config["url_preview_ip_range_blacklist"]
)
# we always blacklist '0.0.0.0' and '::', which are supposed to be
# unroutab... | def read_config(self, config, **kwargs):
"to work"
)
# we always blacklist '0.0.0.0' and '::', which are supposed to be
# unroutable addresses.
self.url_preview_ip_range_blacklist = generate_ip_set(
config["url_preview_ip_range_bla... |
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os.path
import re | # See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import logging
import os.path
import re |
import attr
import yaml
from netaddr import IPSet
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
from synapse.util.stringutils import parse_and_validate_server_name |
import attr
import yaml
from netaddr import AddrFormatError, IPNetwork, IPSet
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
from synapse.util.stringutils import parse_and_validate_server_name |
# in the list.
DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
DEFAULT_IP_RANGE_BLACKLIST = [
# Localhost
"127.0.0.0/8", | # in the list.
DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
def _6to4(network: IPNetwork) -> IPNetwork:
"""Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056."""
# 6to4 networks consist of:
# * 2002 as the first 16 bits
# * The first IPv4 address in the network hex-encoded as the next 32 bit... |
"192.0.0.0/24",
# Link-local networks.
"169.254.0.0/16",
# Testing networks.
"198.18.0.0/15",
"192.0.2.0/24", | "192.0.0.0/24",
# Link-local networks.
"169.254.0.0/16",
# Formerly used for 6to4 relay.
"192.88.99.0/24",
# Testing networks.
"198.18.0.0/15",
"192.0.2.0/24", |
"fe80::/10",
# Unique local addresses.
"fc00::/7",
]
DEFAULT_ROOM_VERSION = "6" | "fe80::/10",
# Unique local addresses.
"fc00::/7",
# Testing networks.
"2001:db8::/32",
# Multicast.
"ff00::/8",
# Site-local addresses
"fec0::/10",
]
DEFAULT_ROOM_VERSION = "6" |
def read_config(self, config, **kwargs):
)
# Attempt to create an IPSet from the given ranges
try:
self.ip_range_blacklist = IPSet(ip_range_blacklist)
except Exception as e:
raise ConfigError("Invalid range(s) provided in ip_range_blacklist.") from e
# Al... | def read_config(self, config, **kwargs):
)
# Attempt to create an IPSet from the given ranges
# Always blacklist 0.0.0.0, ::
self.ip_range_blacklist = generate_ip_set(
ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",)
)
self.ip_rang... |
def read_config(self, config, **kwargs):
federation_ip_range_blacklist = config.get(
"federation_ip_range_blacklist", ip_range_blacklist
)
try:
self.federation_ip_range_blacklist = IPSet(federation_ip_range_blacklist)
except Exception as e:
raise Confi... | def read_config(self, config, **kwargs):
federation_ip_range_blacklist = config.get(
"federation_ip_range_blacklist", ip_range_blacklist
)
# Always blacklist 0.0.0.0, ::
self.federation_ip_range_blacklist = generate_ip_set(
federation_ip_range_blacklist,
... |
import yaml
from synapse.config.server import ServerConfig, is_threepid_reserved
from tests import unittest
|
import yaml
from synapse.config._base import ConfigError
from synapse.config.server import ServerConfig, generate_ip_set, is_threepid_reserved
from tests import unittest
|
def test_listeners_set_correctly_open_private_ports_true(self):
)
self.assertEqual(conf["listeners"], expected_listeners) | def test_listeners_set_correctly_open_private_ports_true(self):
)
self.assertEqual(conf["listeners"], expected_listeners)
class GenerateIpSetTestCase(unittest.TestCase):
def test_empty(self):
ip_set = generate_ip_set(())
self.assertFalse(ip_set)
ip_set = generate_ip_set((... |
class tqdm(object):
return self.total if self.iterable is None else \
(self.iterable.shape[0] if hasattr(self.iterable, "shape")
else len(self.iterable) if hasattr(self.iterable, "__len__")
else self.total)
def __enter__(self):
return self | class tqdm(object):
return self.total if self.iterable is None else \
(self.iterable.shape[0] if hasattr(self.iterable, "shape")
else len(self.iterable) if hasattr(self.iterable, "__len__")
else getattr(self, "total", None))
def __enter__(self):
return self |
from __future__ import division
from tqdm import tqdm
from tests_tqdm import with_setup, pretest, posttest, StringIO, closing
from tests_tqdm import DiscreteTimer, cpu_timify
from time import sleep
from threading import Event
from tqdm import TMonitor
class FakeSleep(object): | from __future__ import division
from tqdm import tqdm, TMonitor
from tests_tqdm import with_setup, pretest, posttest, SkipTest, \
StringIO, closing
from tests_tqdm import DiscreteTimer, cpu_timify
from time import sleep
from threading import Event
class FakeSleep(object): |
def make_create_fake_sleep_event(sleep):
return create_fake_sleep_event
@with_setup(pretest, posttest)
def test_monitor_thread():
"""Test dummy monitoring thread""" | def make_create_fake_sleep_event(sleep):
return create_fake_sleep_event
def incr(x):
return x + 1
@with_setup(pretest, posttest)
def test_monitor_thread():
"""Test dummy monitoring thread""" |
def test_monitoring_multi():
# Check that class var monitor is deleted if no instance left
tqdm.monitor_interval = 10
assert tqdm.monitor is None | def test_monitoring_multi():
# Check that class var monitor is deleted if no instance left
tqdm.monitor_interval = 10
assert tqdm.monitor is None
@with_setup(pretest, posttest)
def test_imap():
"""Test multiprocessing.Pool"""
try:
from multiprocessing import Pool
except ImportError:
... |
class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna:
pointer = self._codes[good].min()
else:
return np.nan | class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna and good.any():
pointer = self._codes[good].min()
else:
return np.nan |
class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna:
pointer = self._codes[good].max()
else:
return np.nan | class Categorical(ExtensionArray, PandasObject):
good = self._codes != -1
if not good.all():
if skipna and good.any():
pointer = self._codes[good].max()
else:
return np.nan |
class TestCategoricalAnalytics:
assert _min == 2
assert _max == 1
@pytest.mark.parametrize("method", ["min", "max"])
def test_deprecate_numeric_only_min_max(self, method):
# GH 25303 | class TestCategoricalAnalytics:
assert _min == 2
assert _max == 1
@pytest.mark.parametrize("function", ["min", "max"])
@pytest.mark.parametrize("skipna", [True, False])
def test_min_max_only_nan(self, function, skipna):
# https://github.com/pandas-dev/pandas/issues/33450
... |
def test_match(stderr):
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push --quiet', stderr=stderr))\
== "git push --set-upstream origin master --quiet" | def test_match(stderr):
def test_get_new_command(stderr):
assert get_new_command(Command('git push', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_command(Command('git push -u origin', stderr=stderr))\
== "git push --set-upstream origin master"
assert get_new_com... |
def match(command):
@git_support
def get_new_command(command):
push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2]
return replace_argument(command.script, 'push', push_upstream) | def match(command):
@git_support
def get_new_command(command):
# If --set-upstream or -u are passed, remove it and its argument. This is
# because the remaining arguments are concatenated onto the command suggested
# by git, which includes --set-upstream and its argument
upstream_option_index = -1
... |
def parse_uri(self, uri):
"like so: "
"swift+http://user:pass@authurl.com/v1/container/obj"
)
logger.error(_("Invalid store uri %(uri)s: %(reason)s") % locals())
raise exception.BadStoreUri()
pieces = urlparse.urlparse(uri) | def parse_uri(self, uri):
"like so: "
"swift+http://user:pass@authurl.com/v1/container/obj"
)
logger.error(_("Invalid store URI: %(reason)s") % locals())
raise exception.BadStoreUri()
pieces = urlparse.urlparse(uri) |
def parse_uri(self, uri):
# the account and user. Combine them into a single username of
# account:user
if len(cred_parts) == 1:
reason = (_("Badly formed credentials '%(creds)s' in Swift "
"URI") % locals())
logger.error(re... | def parse_uri(self, uri):
# the account and user. Combine them into a single username of
# account:user
if len(cred_parts) == 1:
reason = (_("Badly formed credentials in Swift URI."))
logger.error(reason)
raise exception.BadStoreUri()
... |
def parse_uri(self, uri):
path_parts.insert(0, netloc)
self.authurl = '/'.join(path_parts)
except IndexError:
reason = _("Badly formed Swift URI: %s") % uri
logger.error(reason)
raise exception.BadStoreUri()
| def parse_uri(self, uri):
path_parts.insert(0, netloc)
self.authurl = '/'.join(path_parts)
except IndexError:
reason = _("Badly formed Swift URI.")
logger.error(reason)
raise exception.BadStoreUri()
|
def get(self, location):
except swift_client.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri()
raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % locals())
... | def get(self, location):
except swift_client.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri()
msg = _("Swift could not find image at URI.")
raise exception.NotFound(msg)
else:
raise
|
def add(self, image_id, image_file, image_size):
except swift_client.ClientException, e:
if e.http_status == httplib.CONFLICT:
raise exception.Duplicate(_("Swift already has an image at "
"location %s") % location.get_uri())
msg =... | def add(self, image_id, image_file, image_size):
except swift_client.ClientException, e:
if e.http_status == httplib.CONFLICT:
raise exception.Duplicate(_("Swift already has an image at "
"this location."))
msg = (_("Failed to add... |
def delete(self, location):
except swift_client.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri()
raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % locals())
... | def delete(self, location):
except swift_client.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_store_uri()
msg = _("Swift could not find image at URI.")
raise exception.NotFound(msg)
else:
rais... |
def register_cli_int(*args, **kw):
register_str('public_port', default=5000)
register_str('onready')
register_str('auth_admin_prefix', default='')
#ssl options
register_bool('enable', group='ssl', default=False) | def register_cli_int(*args, **kw):
register_str('public_port', default=5000)
register_str('onready')
register_str('auth_admin_prefix', default='')
register_int('max_param_size', default=64)
# we allow tokens to be a bit larger to accomidate PKI
register_int('max_token_size', default=8192)
#ssl options
register_bool('e... |
class ValidationError(Error):
title = 'Bad Request'
class Unauthorized(Error):
"""The request you have made requires authentication."""
code = 401 | class ValidationError(Error):
title = 'Bad Request'
class ValidationSizeError(Error):
"""Request attribute %(attribute)s must be less than or equal to %(size)i.
The server could not comply with the request because the attribute
size is invalid (too large).
The client is assumed to be in error.
... |
from keystone import catalog
from keystone.common import cms
from keystone.common import logging
from keystone.common import wsgi
from keystone import exception
from keystone import identity | from keystone import catalog
from keystone.common import cms
from keystone.common import logging
from keystone.common import utils
from keystone.common import wsgi
from keystone import exception
from keystone import identity |
LOG = logging.getLogger(__name__)
class AdminRouter(wsgi.ComposingRouter): |
LOG = logging.getLogger(__name__)
MAX_PARAM_SIZE = config.CONF.max_param_size
MAX_TOKEN_SIZE = config.CONF.max_token_size
class AdminRouter(wsgi.ComposingRouter): |
def authenticate(self, context, auth=None):
if 'passwordCredentials' in auth:
user_id = auth['passwordCredentials'].get('userId', None)
username = auth['passwordCredentials'].get('username', '')
password = auth['passwordCredentials'].get('password', '')
tenant_na... | def authenticate(self, context, auth=None):
if 'passwordCredentials' in auth:
user_id = auth['passwordCredentials'].get('userId', None)
if user_id and len(user_id) > MAX_PARAM_SIZE:
raise exception.ValidationSizeError(attribute='userId',
... |
def authenticate(self, context, auth=None):
# more compat
tenant_id = auth.get('tenantId', None)
if tenant_name:
try:
tenant_ref = self.identity_api.get_tenant_by_name( | def authenticate(self, context, auth=None):
# more compat
tenant_id = auth.get('tenantId', None)
if tenant_id and len(tenant_id) > MAX_PARAM_SIZE:
raise exception.ValidationSizeError(attribute='tenantId',
size=MAX_P... |
def authenticate(self, context, auth=None):
catalog_ref = {}
elif 'token' in auth:
old_token = auth['token'].get('id', None)
tenant_name = auth.get('tenantName')
try:
old_token_ref = self.token_api.get_token(context=context, | def authenticate(self, context, auth=None):
catalog_ref = {}
elif 'token' in auth:
old_token = auth['token'].get('id', None)
if len(old_token) > MAX_TOKEN_SIZE:
raise exception.ValidationSizeError(attribute='token',
... |
import default_fixtures
from keystone import config
from keystone import service
from keystone import test
from keystone.identity.backends import kvs as kvs_identity | import default_fixtures
from keystone import config
from keystone import exception
from keystone import service
from keystone import test
from keystone.identity.backends import kvs as kvs_identity |
CONF = config.CONF
class TokenExpirationTest(test.TestCase):
def setUp(self):
super(TokenExpirationTest, self).setUp() | CONF = config.CONF
def _build_user_auth(token=None, user_id=None, username=None,
password=None, tenant_id=None, tenant_name=None):
"""Build auth dictionary.
It will create an auth dictionary based on all the arguments
that it receives.
"""
auth_json = {}
if token is not N... |
def _maintain_token_expiration(self):
def test_maintain_uuid_token_expiration(self):
self.opt_in_group('signing', token_format='UUID')
self._maintain_token_expiration() | def _maintain_token_expiration(self):
def test_maintain_uuid_token_expiration(self):
self.opt_in_group('signing', token_format='UUID')
self._maintain_token_expiration()
class AuthTest(test.TestCase):
def setUp(self):
super(AuthTest, self).setUp()
CONF.identity.driver = 'keysto... |
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc
from pandas.core.dtypes.cast import maybe_cast_result
from pandas.core.dtypes.common import (
ensure_float,
is_datetime64_dtype,
is_integer_dtype,
is_numeric_dtype,
is_object_dtype, | from pandas.util._decorators import Appender, Substitution, cache_readonly, doc
from pandas.core.dtypes.cast import maybe_cast_result
from pandas.core.dtypes.common import (
ensure_float,
is_bool_dtype,
is_datetime64_dtype,
is_extension_array_dtype,
is_integer_dtype,
is_numeric_dtype,
is_obj... |
class GroupBy(_GroupBy[FrameOrSeries]):
)
inference = None
if is_integer_dtype(vals):
inference = np.int64
elif is_datetime64_dtype(vals):
inference = "datetime64[ns]"
vals = np.asarray(vals).astype(np.float)
| class GroupBy(_GroupBy[FrameOrSeries]):
)
inference = None
if is_integer_dtype(vals.dtype):
if is_extension_array_dtype(vals.dtype):
vals = vals.to_numpy(dtype=float, na_value=np.nan)
inference = np.int64
elif is_bo... |
def test_quantile_missing_group_values_correct_results():
tm.assert_frame_equal(result, expected)
# pipe
# --------------------------------
| def test_quantile_missing_group_values_correct_results():
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"values",
[
pd.array([1, 0, None] * 2, dtype="Int64"),
pd.array([True, False, None] * 2, dtype="boolean"),
],
)
@pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0... |
class TestImage:
with pytest.warns(DeprecationWarning):
assert test_module.PILLOW_VERSION > "7.0.0"
def test_overrun(self):
"""For overrun completeness, test as:
valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c
"""
for file in [
... | class TestImage:
with pytest.warns(DeprecationWarning):
assert test_module.PILLOW_VERSION > "7.0.0"
@pytest.mark.parametrize("path", [
"fli_overrun.bin",
"sgi_overrun.bin",
"sgi_overrun_expandrow.bin",
"sgi_overrun_expandrow2.bin",
"pc... |
class PcxImageFile(ImageFile.ImageFile):
version = s[1]
bits = s[3]
planes = s[65]
stride = i16(s, 66)
logger.debug(
"PCX version %s, bits %s, planes %s, stride %s",
version,
bits,
planes,
stride,
)
self... | class PcxImageFile(ImageFile.ImageFile):
version = s[1]
bits = s[3]
planes = s[65]
ignored_stride = i16(s, 66)
logger.debug(
"PCX version %s, bits %s, planes %s, stride %s",
version,
bits,
planes,
ignored_stride,
... |
class PcxImageFile(ImageFile.ImageFile):
self.mode = mode
self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
bbox = (0, 0) + self.size
logger.debug("size: %sx%s", *self.size)
| class PcxImageFile(ImageFile.ImageFile):
self.mode = mode
self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
# don't trust the passed in stride. Calculate for ourselves.
# CVE-2020-35655
stride = (self._size[0] * bits + 7) // 8
stride += stride % 2
bbox = (0, 0) ... |
class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('é'), 'é')
self.assertEqual(unescapeHTML('�'), '�')
# HTML5 entities
self.assertEqual(unescapeHTML('.''), '.\'')
| class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('é'), 'é')
self.assertEqual(unescapeHTML('�'), '�')
self.assertEqual(unescapeHTML('&a"'), '&a"')
# HTML5 entities
self.assertE... |
def unescapeHTML(s):
assert type(s) == compat_str
return re.sub(
r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
def get_subprocess_encoding(): | def unescapeHTML(s):
assert type(s) == compat_str
return re.sub(
r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
def get_subprocess_encoding(): |
import pytest
import warnings
from mock import Mock, patch
from thefuck.utils import default_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache, \ |
import pytest
import warnings
from mock import Mock, call, patch
from thefuck.utils import default_settings, \
memoize, get_closest, get_all_executables, replace_argument, \
get_all_matched_commands, is_app, for_app, cache, \ |
def test_get_all_executables():
assert 'fuck' not in all_callables
@pytest.mark.parametrize('args, result', [
(('apt-get instol vim', 'instol', 'install'), 'apt-get install vim'),
(('git brnch', 'brnch', 'branch'), 'git branch')]) | def test_get_all_executables():
assert 'fuck' not in all_callables
@pytest.fixture
def os_environ_pathsep(monkeypatch, path, pathsep):
env = {'PATH': path}
monkeypatch.setattr('os.environ', env)
monkeypatch.setattr('os.pathsep', pathsep)
return env
@pytest.mark.usefixtures('no_memoize', 'os_envi... |
def get_all_executables():
tf_entry_points = ['thefuck', 'fuck']
bins = [exe.name.decode('utf8') if six.PY2 else exe.name
for path in os.environ.get('PATH', '').split(':')
for exe in _safe(lambda: list(Path(path).iterdir()), [])
if not _safe(exe.is_dir, True)
and... | def get_all_executables():
tf_entry_points = ['thefuck', 'fuck']
bins = [exe.name.decode('utf8') if six.PY2 else exe.name
for path in os.environ.get('PATH', '').split(os.pathsep)
for exe in _safe(lambda: list(Path(path).iterdir()), [])
if not _safe(exe.is_dir, True)
... |
def get_new_command(command):
def side_effect(old_cmd, command):
with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive:
for file in archive.getnames():
try:
os.remove(file)
except OSError: | def get_new_command(command):
def side_effect(old_cmd, command):
with tarfile.TarFile(_tar_file(old_cmd.script_parts)[0]) as archive:
for file in archive.getnames():
if not os.path.abspath(file).startswith(os.getcwd()):
# it's unsafe to overwrite files outside of the current dire... |
def get_new_command(command):
def side_effect(old_cmd, command):
with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive:
for file in archive.namelist():
try:
os.remove(file)
except OSError: | def get_new_command(command):
def side_effect(old_cmd, command):
with zipfile.ZipFile(_zip_file(old_cmd), 'r') as archive:
for file in archive.namelist():
if not os.path.abspath(file).startswith(os.getcwd()):
# it's unsafe to overwrite files outside of the current directory
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.