buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
ORDER_DIR = {
'ASC': ('ASC', 'DESC'),
'DESC': ('DESC', 'ASC'),
}
# SQL join types.
INNER = 'INNER JOIN' | ORDER_DIR = {
'ASC': ('ASC', 'DESC'),
'DESC': ('DESC', 'ASC'),
}
ORDER_PATTERN = _lazy_re_compile(r'[-+]?[.\w]+$')
# SQL join types.
INNER = 'INNER JOIN' |
from django.db.models.lookups import Lookup
from django.db.models.query_utils import (
Q, check_rel_lookup_compatibility, refs_expression,
)
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.lookups import Lookup
from django.db.models.query_utils import (
Q, check_rel_lookup_compatibility, refs_expression,
)
from django.db.models.sql.constants import (
INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE,
)
from django.db.models.sql.datastructures import (
BaseTable, Empty, Joi... |
class Query(BaseExpression):
errors = []
for item in ordering:
if isinstance(item, str):
if '.' in item:
warnings.warn(
'Passing column raw column aliases to order_by() is '
'deprecated. Wrap %r in a RawSQL e... | class Query(BaseExpression):
errors = []
for item in ordering:
if isinstance(item, str):
if '.' in item and ORDER_PATTERN.match(item):
warnings.warn(
'Passing column raw column aliases to order_by() is '
'dep... |
class QuerySetExceptionTests(SimpleTestCase):
with self.assertRaisesMessage(FieldError, msg):
Article.objects.order_by('*')
def test_invalid_queryset_model(self):
msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".'
with self.assertRaisesMessage(ValueError,... | class QuerySetExceptionTests(SimpleTestCase):
with self.assertRaisesMessage(FieldError, msg):
Article.objects.order_by('*')
def test_order_by_escape_prevention(self):
msg = (
"Cannot resolve keyword 'queries.name);' into field. Choices are: "
"created, id, name"
... |
from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_float64,
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, | from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, |
Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if method == "pearson":
correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods)
elif method == "spearman":
correl... | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
... |
Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
baseCov = np.empty((mat.shape[1], mat.shape[1]))
... | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty(... |
class TestDataFrameCov:
)
tm.assert_frame_equal(result, expected)
class TestDataFrameCorr:
# DataFrame.corr(), as opposed to DataFrame.corrwith | class TestDataFrameCov:
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])]
)
def test_cov_nullable_integer(self, other_column):
# https://github.com/pandas-dev/pandas/issues/33803
data ... |
class TestDataFrameCorr:
df3.cov()
df3.corr()
class TestDataFrameCorrWith:
def test_corrwith(self, datetime_frame): | class TestDataFrameCorr:
df3.cov()
df3.corr()
@td.skip_if_no_scipy
@pytest.mark.parametrize(
"nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]
)
@pytest.mark.parametrize(
"other_column",
[pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.... |
from __future__ import absolute_import
import datetime
import logging
import os | from __future__ import absolute_import
import re
import datetime
import logging
import os |
class ConnectionError(Exception):
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import.""" | class ConnectionError(Exception):
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import.""" |
def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the | def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def putrequest(self, method, url, *args, **kwargs):
"""Send a request to the server"""
match = _CONTAINS_CONTROL_CHAR_RE.search(method)
if match:
raise ValueError(
"Method cannot ... |
def test_dns_error(self):
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
def test_percent_encode_invalid_target_chars(self):
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/echo_params?q=\r&k=\n \n") | def test_dns_error(self):
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
@pytest.mark.parametrize("char", [" ", "\r", "\n", "\x00"])
def test_invalid_method_not_allowed(self, char):
with pytest.raises(ValueError):
with HTTPConnectionPo... |
class _AxesBase(martist.Artist):
if right is None:
right = old_right
if self.get_xscale() == 'log':
if left <= 0:
cbook._warn_external(
'Attempted to set non-positive left xlim on a ' | class _AxesBase(martist.Artist):
if right is None:
right = old_right
if self.get_xscale() == 'log' and (left <= 0 or right <= 0):
# Axes init calls set_xlim(0, 1) before get_xlim() can be called,
# so only grab the limits if we really need them.
o... |
def test_log_scales():
ax.set_xscale('log', basex=9.0)
@image_comparison(['stackplot_test_image', 'stackplot_test_image'])
def test_stackplot():
fig = plt.figure() | def test_log_scales():
ax.set_xscale('log', basex=9.0)
def test_log_scales_invalid():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xscale('log')
with pytest.warns(UserWarning, match='Attempted to set non-positive'):
ax.set_xlim(-1, 10)
@image_comparison(['stackplot_test_image'... |
class TimedeltaIndex(
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
value = np.array(value, dtype=_TD_DTYPE, copy=False)
else:
value = Timedelta(value).asm8.view(_TD_DTYPE)
... | class TimedeltaIndex(
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
if not type(self._data)._is_recognized_dtype(value):
raise TypeError(
"searchsorted requires c... |
class TestTimedeltaArray:
arr[0] = obj
assert arr[0] == pd.Timedelta(seconds=1)
class TestReductions:
@pytest.mark.parametrize("name", ["sum", "std", "min", "max", "median"]) | class TestTimedeltaArray:
arr[0] = obj
assert arr[0] == pd.Timedelta(seconds=1)
@pytest.mark.parametrize(
"other",
[
1,
np.int64(1),
1.0,
np.datetime64("NaT"),
pd.Timestamp.now(),
"invalid",
np.arang... |
class MultiPartParser:
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
stripped_chunk += b"".join(over_chunk.split())
... | class MultiPartParser:
remaining = len(stripped_chunk) % 4
while remaining != 0:
over_chunk = field_stream.read(4 - remaining)
if not over_chunk:
... |
class FileUploadTests(TestCase):
def test_big_base64_newlines_upload(self):
self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
def test_unicode_file_name(self):
with sys_tempfile.TemporaryDirectory() as temp_dir:
# This file contains Chinese symbols and an accen... | class FileUploadTests(TestCase):
def test_big_base64_newlines_upload(self):
self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
def test_base64_invalid_upload(self):
payload = client.FakePayload('\r\n'.join([
'--' + client.BOUNDARY,
'Content-Dispositi... |
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
stderr=subprocess.STDOUT,
)
if checkout is not None:
subprocess.check_output( # nosec
[repo_type, 'checkout', checkout],
cwd=repo_dir,
... | def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
stderr=subprocess.STDOUT,
)
if checkout is not None:
checkout_params = [checkout]
# Avoid Mercurial "--config" and "--debugger" injection vulnerability
if repo_ty... |
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
output = clone_error.output.decode('utf-8')
if 'not found' in output.lower():
raise RepositoryNotFound(
'The repository {} could not be found, '
'have you made a typo?'.f... | def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
output = clone_error.output.decode('utf-8')
if 'not found' in output.lower():
raise RepositoryNotFound(
f'The repository {repo_url} could not be found, '
'have you made a... |
def test_clone_should_invoke_vcs_command(
mock_subprocess.assert_any_call(
[repo_type, 'clone', repo_url], cwd=str(clone_dir), stderr=subprocess.STDOUT
)
mock_subprocess.assert_any_call(
[repo_type, 'checkout', branch], cwd=expected_repo_dir, stderr=subprocess.STDOUT
)
| def test_clone_should_invoke_vcs_command(
mock_subprocess.assert_any_call(
[repo_type, 'clone', repo_url], cwd=str(clone_dir), stderr=subprocess.STDOUT
)
branch_info = [branch]
# We sanitize branch information for Mercurial
if repo_type == "hg":
branch_info.insert(0, "--")
mock... |
def test_clone_handles_repo_typo(mocker, clone_dir, error_message):
vcs.clone(repository_url, clone_to_dir=str(clone_dir), no_input=True)
assert str(err.value) == (
'The repository {} could not be found, have you made a typo?'
).format(repository_url)
@pytest.mark.parametrize( | def test_clone_handles_repo_typo(mocker, clone_dir, error_message):
vcs.clone(repository_url, clone_to_dir=str(clone_dir), no_input=True)
assert str(err.value) == (
f'The repository {repository_url} could not be found, have you made a typo?'
)
@pytest.mark.parametrize( |
def test_clone_handles_branch_typo(mocker, clone_dir, error_message):
assert str(err.value) == (
'The unknown_branch branch of repository '
'{} could not found, have you made a typo?'
).format(repository_url)
def test_clone_unknown_subprocess_error(mocker, clone_dir): | def test_clone_handles_branch_typo(mocker, clone_dir, error_message):
assert str(err.value) == (
'The unknown_branch branch of repository '
f'{repository_url} could not found, have you made a typo?'
)
def test_clone_unknown_subprocess_error(mocker, clone_dir): |
class AuthenticationForm(forms.Form):
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
# An authentication backend may reject inactive users. Check
# if the... | class AuthenticationForm(forms.Form):
if username is not None and password:
self.user_cache = authenticate(self.request, username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login']... |
class UserCreationFormTest(TestDataMixin, TestCase):
)
class AuthenticationFormTest(TestDataMixin, TestCase):
def test_invalid_username(self): | class UserCreationFormTest(TestDataMixin, TestCase):
)
# To verify that the login form rejects inactive users, use an authentication
# backend that allows them.
@override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend'])
class AuthenticationFormTest(TestDataMixin, Te... |
class AuthenticationFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
def test_login_failed(self):
signal_calls = []
| class AuthenticationFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
# Use an authentication backend that rejects inactive users.
@override_settings(AUTHENTICATION_BACKENDS=['django.cont... |
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
return arr.view(dtype)
# allow frequency conversions | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... |
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
return arr.view(dtype)
if dtype not in [_INT64_DTYPE, _TD_DTYPE]: | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... |
import pytest
import pandas.util._test_decorators as td
import pandas.core.dtypes.common as com
from pandas.core.dtypes.dtypes import (
CategoricalDtype, | import pytest
import pandas.util._test_decorators as td
from pandas.core.dtypes.cast import astype_nansafe
import pandas.core.dtypes.common as com
from pandas.core.dtypes.dtypes import (
CategoricalDtype, |
from pandas.core.dtypes.dtypes import (
IntervalDtype,
PeriodDtype,
)
import pandas as pd
from pandas.conftest import ( | from pandas.core.dtypes.dtypes import (
IntervalDtype,
PeriodDtype,
)
from pandas.core.dtypes.missing import isna
import pandas as pd
from pandas.conftest import ( |
def test__get_dtype_fails(input_param, expected_error_message):
)
def test__is_dtype_type(input_param, result):
assert com._is_dtype_type(input_param, lambda tipo: tipo == result) | def test__get_dtype_fails(input_param, expected_error_message):
)
def test__is_dtype_type(input_param, result):
assert com._is_dtype_type(input_param, lambda tipo: tipo == result)
@pytest.mark.parametrize("val", [np.datetime64("NaT"), np.timedelta64("NaT")])
@pytest.mark.parametrize("typ", [np.int64])
def test_as... |
def ret10_slice() -> Bytes[10]:
assert c.ret10_slice() == b"A"
def test_slice_convert(get_contract):
# test slice of converting between bytes32 and Bytes
code = """ | def ret10_slice() -> Bytes[10]:
assert c.ret10_slice() == b"A"
def test_slice_equality(get_contract):
# test for equality with dirty bytes
code = """
@external
def assert_eq() -> bool:
dirty_bytes: String[4] = "abcd"
dirty_bytes = slice(dirty_bytes, 0, 3)
clean_bytes: String[4] = "abc"
ret... |
def test(a: uint256, b: String[50] = "foo") -> Bytes[100]:
assert c.test(12345, "bar")[-3:] == b"bar"
def test_string_equality(get_contract_with_gas_estimation):
code = """
_compA: String[100]
_compB: String[100]
@external
def equal_true() -> bool:
compA: String[100] = "The quick brown fox jumps over the... | def test(a: uint256, b: String[50] = "foo") -> Bytes[100]:
assert c.test(12345, "bar")[-3:] == b"bar"
string_equality_tests = [
(
100,
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy hog",
),
# check <= 32 codepath
(32, "abc", "abc\0"... |
def compare_var_storage_not_equal_false() -> bool:
assert c.storage_not_equal_true() is True
assert c.storage_not_equal_false() is False
a = "The quick brown fox jumps over the lazy dog"
b = "The quick brown fox jumps over the lazy hog"
assert c.string_compare_equal(a, a) is True
assert c.strin... | def compare_var_storage_not_equal_false() -> bool:
assert c.storage_not_equal_true() is True
assert c.storage_not_equal_false() is False
assert c.string_compare_equal(a, a) is True
assert c.string_compare_equal(a, b) is False
assert c.string_compare_not_equal(b, a) is True |
def copy_bytes(dst, src, length, length_bound):
with src.cache_when_complex("src") as (b1, src), length.cache_when_complex(
"copy_bytes_count"
) as (b2, length,), dst.cache_when_complex("dst") as (b3, dst):
# fast code for common case where num bytes is small
# TODO expand this for mor... | def copy_bytes(dst, src, length, length_bound):
with src.cache_when_complex("src") as (b1, src), length.cache_when_complex(
"copy_bytes_count"
) as (b2, length), dst.cache_when_complex("dst") as (b3, dst):
# fast code for common case where num bytes is small
# TODO expand this for more... |
from vyper.address_space import DATA, IMMUTABLES, MEMORY, STORAGE
from vyper.codegen import external_call, self_call
from vyper.codegen.core import (
LOAD,
bytes_data_ptr,
clamp_basetype,
ensure_in_memory,
get_dyn_array_count, | from vyper.address_space import DATA, IMMUTABLES, MEMORY, STORAGE
from vyper.codegen import external_call, self_call
from vyper.codegen.core import (
clamp_basetype,
ensure_in_memory,
get_dyn_array_count, |
def parse_Compare(self):
left = Expr(self.expr.left, self.context).ir_node
right = Expr(self.expr.right, self.context).ir_node
length_mismatch = left.typ.maxlen != right.typ.maxlen
left_over_32 = left.typ.maxlen > 32
right_over_32 = right.typ.maxlen > 32
... | def parse_Compare(self):
left = Expr(self.expr.left, self.context).ir_node
right = Expr(self.expr.right, self.context).ir_node
left_keccak = keccak256_helper(self.expr, left, self.context)
right_keccak = keccak256_helper(self.expr, right, self.context)
if op... |
from math import ceil
from vyper.codegen.core import ensure_in_memory
from vyper.codegen.ir_node import IRnode
from vyper.codegen.types import BaseType, ByteArrayLike, is_base_type
from vyper.exceptions import CompilerPanic | from math import ceil
from vyper.codegen.core import bytes_data_ptr, ensure_in_memory, get_bytearray_length
from vyper.codegen.ir_node import IRnode
from vyper.codegen.types import BaseType, ByteArrayLike, is_base_type
from vyper.exceptions import CompilerPanic |
def _gas_bound(num_words):
return SHA3_BASE + num_words * SHA3_PER_WORD
def keccak256_helper(expr, ir_arg, context):
sub = ir_arg # TODO get rid of useless variable
_check_byteslike(sub.typ, expr)
# Can hash literals
# TODO this is dead code.
if isinstance(sub, bytes):
return IRnode.... | def _gas_bound(num_words):
return SHA3_BASE + num_words * SHA3_PER_WORD
def keccak256_helper(expr, to_hash, context):
_check_byteslike(to_hash.typ, expr)
# Can hash literals
# TODO this is dead code.
if isinstance(to_hash, bytes):
return IRnode.from_list(bytes_to_int(keccak256(to_hash)), ... |
__metaclass__ = type
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.utils.collection_loader import AnsibleCollectionLoader
def _ensure_default_collection(collection_list=None): | __metaclass__ = type
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.utils.collection_loader import AnsibleCollectionLoader
from ansible.template import is_template, Environment
from ansible.utils.display import Display
display = Display()
def _ens... |
def _ensure_default_collection(collection_list=None):
class CollectionSearch:
# this needs to be populated before we can resolve tasks/roles/etc
_collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection)
def _load_collections(self, attr, ds):
#... | def _ensure_default_collection(collection_list=None):
class CollectionSearch:
# this needs to be populated before we can resolve tasks/roles/etc
_collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection,
always_post_validat... |
class CollectionSearch:
if not ds: # don't return an empty collection list, just return None
return None
return ds | class CollectionSearch:
if not ds: # don't return an empty collection list, just return None
return None
# This duplicates static attr checking logic from post_validate()
# because if the user attempts to template a collection name, it will
# error before it ever gets to th... |
class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, thetamax = thetamax, thetamin | class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
self._unstale_viewLim()
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, theta... |
def test_polar_invertedylim():
def test_polar_invertedylim_rorigin():
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_ylim(2, 0)
ax.set_rorigin(3)
| def test_polar_invertedylim():
def test_polar_invertedylim_rorigin():
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.yaxis.set_inverted(True)
# Set the rlims to inverted (2, 0) without calling set_rlim, to check that
# viewlims are correctly unstaled before draw()ing.
... |
def _iter_command_classes(module_name):
# TODO: add `name` attribute to commands and and merge this function with
# scrapy.utils.spider.iter_spider_classes
for module in walk_modules(module_name):
for obj in vars(module).itervalues():
if inspect.isclass(obj) and \
issubcla... | def _iter_command_classes(module_name):
# TODO: add `name` attribute to commands and and merge this function with
# scrapy.utils.spider.iter_spider_classes
for module in walk_modules(module_name):
for obj in vars(module).values():
if inspect.isclass(obj) and \
issubcl... |
class TestProcessProtocol(protocol.ProcessProtocol):
def __init__(self):
self.deferred = defer.Deferred()
self.out = ''
self.err = ''
self.exitcode = None
def outReceived(self, data): | class TestProcessProtocol(protocol.ProcessProtocol):
def __init__(self):
self.deferred = defer.Deferred()
self.out = b''
self.err = b''
self.exitcode = None
def outReceived(self, data): |
class CmdlineTest(unittest.TestCase):
self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings'
def _execute(self, *new_args, **kwargs):
args = (sys.executable, '-m', 'scrapy.cmdline') + new_args
proc = Popen(args, stdout=PIPE, stderr=PIPE, env=self.env, **kwargs)
comm = pr... | class CmdlineTest(unittest.TestCase):
self.env['SCRAPY_SETTINGS_MODULE'] = 'tests.test_cmdline.settings'
def _execute(self, *new_args, **kwargs):
encoding = getattr(sys.stdout, 'encoding') or 'utf-8'
args = (sys.executable, '-m', 'scrapy.cmdline') + new_args
proc = Popen(args, stdou... |
from twisted.trial import unittest
from twisted.internet import defer
| import sys
from twisted.trial import unittest
from twisted.internet import defer
|
class VersionTest(ProcessTest, unittest.TestCase):
@defer.inlineCallbacks
def test_output(self):
_, out, _ = yield self.execute([])
self.assertEqual(out.strip(), "Scrapy %s" % scrapy.__version__) | class VersionTest(ProcessTest, unittest.TestCase):
@defer.inlineCallbacks
def test_output(self):
encoding = getattr(sys.stdout, 'encoding') or 'utf-8'
_, out, _ = yield self.execute([])
self.assertEqual(out.strip().decode(encoding), "Scrapy %s" % scrapy.__version__) |
from django.db.models.sql.where import (
)
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import cached_property
from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
def get_field_names_from_opts(opts):
return set(chain.from_iterable( | from django.db.models.sql.where import (
)
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import cached_property
from django.utils.regex_helper import _lazy_re_compile
from django.utils.tree import Node
__all__ = ['Query', 'RawQuery']
# Quotation marks ('"`[]), whitespace c... |
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(sel... | 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):
('Stuart Russell', 1),
('Peter Norvig', 2),
], lambda a: (a.name, a.contact_count), ordered=False) | class AggregateTestCase(TestCase):
('Stuart Russell', 1),
('Peter Norvig', 2),
], lambda a: (a.name, a.contact_count), ordered=False)
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "aggregation_author"; --"""
msg = (
"Column al... |
class NonAggregateAnnotationTestCase(TestCase):
{'name': 'Wesley J. Chun', 'max_pages': 0},
])
class AliasTests(TestCase):
@classmethod | class NonAggregateAnnotationTestCase(TestCase):
{'name': 'Wesley J. Chun', 'max_pages': 0},
])
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation... |
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):
'bar %s'
)
class SelectRelatedTests(TestCase):
def test_tickets_3045_3288(self): | class Queries5Tests(TestCase):
'bar %s'
)
def test_extra_select_alias_sql_injection(self):
crafted_alias = """injected_name" from "queries_note"; --"""
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolons, or SQL co... |
def format_str(src_contents: str, line_length: int) -> FileContent:
return dst_contents
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
drv = driver.Driver(grammar, pytree.convert)
if src_txt[-1]... | def format_str(src_contents: str, line_length: int) -> FileContent:
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
pygram.python_grammar_no_exec_statement,
pygram.python_grammar,
]
def lib2to3_parse(src_txt: ... |
def whitespace(leaf: Leaf) -> str: # noqa C901
):
return NO
elif prev.type in OPENING_BRACKETS:
return NO
| def whitespace(leaf: Leaf) -> str: # noqa C901
):
return NO
elif (
prevp.type == token.RIGHTSHIFT
and prevp.parent
and prevp.parent.type == syms.shift_expr
and prevp.prev_sibling
and prevp.prev_sibling.type == token.NAME
... |
def assert_equivalent(src: str, dst: str) -> None:
try:
src_ast = ast.parse(src)
except Exception as exc:
raise AssertionError(f"cannot parse source: {exc}") from None
try:
dst_ast = ast.parse(dst) | def assert_equivalent(src: str, dst: str) -> None:
try:
src_ast = ast.parse(src)
except Exception as exc:
major, minor = sys.version_info[:2]
raise AssertionError(
f"cannot use --safe with this file; failed to parse source file "
f"with Python {major}.{minor}'s bu... |
python_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
pattern_grammar = driver.load_packaged_grammar("blib2to3", _PATTERN_GRAMMAR_FILE)
pattern_symbols = Symbols(pattern_grammar) | python_symbols = Symbols(python_grammar)
python_grammar_no_print_statement = python_grammar.copy()
del python_grammar_no_print_statement.keywords["print"]
python_grammar_no_exec_statement = python_grammar.copy()
del python_grammar_no_exec_statement.keywords["exec"]
python_grammar_no_print_statement_no_exec_statement ... |
def func_no_args():
for i in range(10):
print(i)
continue
return None
async def coroutine(arg):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) | def func_no_args():
for i in range(10):
print(i)
continue
exec("new-style exec", {}, {})
return None
async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', time... |
def func_no_args():
print(i)
continue
return None
async def coroutine(arg):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) | def func_no_args():
print(i)
continue
exec("new-style exec", {}, {})
return None
async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', ti... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_report(self) -> None:
report = black.Report()
out_lines = [] | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_python2(self) -> None:
source, expected = read_data('python2')
actual = fs(source)
se... |
class PlayBook(object):
basedir = self.inventory.basedir()
filename = "%s.retry" % os.path.basename(self.filename)
filename = filename.replace(".yml","")
if not os.path.exists('/var/tmp/ansible'):
try:
os.makedirs('/var/tmp/ansible')
except:
... | class PlayBook(object):
basedir = self.inventory.basedir()
filename = "%s.retry" % os.path.basename(self.filename)
filename = filename.replace(".yml","")
filename = os.path.join(os.path.expandvars('$HOME/'), filename)
try:
fd = open(filename, 'w') |
def sendEmail(sydent, templateName, mailTo, substitutions):
allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8'))
allSubstitutions[k+"_forurl"] = urllib.quote(v)
mailString = open(mailTemplateFile).read() % allSubstitutions
rawFrom = email.utils.parseaddr(mailFrom)[1]
... | def sendEmail(sydent, templateName, mailTo, substitutions):
allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8'))
allSubstitutions[k+"_forurl"] = urllib.quote(v)
mailString = open(mailTemplateFile).read().decode('utf8') % allSubstitutions
parsedFrom = email.utils.parsead... |
def sendEmail(sydent, templateName, mailTo, substitutions):
smtp = smtplib.SMTP(mailServer, mailPort, myHostname)
if mailUsername != '':
smtp.login(mailUsername, mailPassword)
smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8'))
smtp.quit()
... | def sendEmail(sydent, templateName, mailTo, substitutions):
smtp = smtplib.SMTP(mailServer, mailPort, myHostname)
if mailUsername != '':
smtp.login(mailUsername, mailPassword)
# We're using the parsing above to do basic validation, but instead of
# fa... |
def upload_scan(self, filename):
if filename.endswith('.json') or filename.endswith('.jsonld'):
headers['Content-Type'] = 'application/ld+json'
with open(filename,"r") as f:
response = requests.post(url, headers=headers, data=f, verify=False)
elif filename.endswit... | def upload_scan(self, filename):
if filename.endswith('.json') or filename.endswith('.jsonld'):
headers['Content-Type'] = 'application/ld+json'
with open(filename,"r") as f:
response = requests.post(url, headers=headers, data=f, verify=not self.config['insecure'])
... |
def download_project_scans(self, project_name,version_name, output_folder=None):
if not os.path.exists(project_name):
os.mkdir(project_name)
pathname = os.path.join(project_name, filename)
responce = requests.get(url, headers=self.get_heade... | def download_project_scans(self, project_name,version_name, output_folder=None):
if not os.path.exists(project_name):
os.mkdir(project_name)
pathname = os.path.join(project_name, filename)
responce = requests.get(url, headers=self.get_heade... |
VERSION = (0, 0, 52)
__version__ = '.'.join(map(str, VERSION)) | VERSION = (0, 0, 53)
__version__ = '.'.join(map(str, VERSION)) |
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 ... |
Tests for L{twisted.web.twcgi}.
"""
import sys
import os
import json
from io import BytesIO
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import cl... | Tests for L{twisted.web.twcgi}.
"""
import sys, os
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import client, twcgi, server, resource
from twisted... |
print
print "cgi output"
'''
HEADER_OUTPUT_CGI = '''\
import json
import os
print("")
print("")
vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")}
print(json.dumps(vals))
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
| print
print "cgi output"
'''
class PythonScript(twcgi.FilteredScript):
filter = sys.executable
|
class CGITests(unittest.TestCase):
return factory.deferred
def test_noProxyPassthrough(self):
"""
The CGI script is never called with the Proxy header passed through.
"""
cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI)
portnum = self.startServer(cgiFilename)
... | class CGITests(unittest.TestCase):
return factory.deferred
def test_duplicateHeaderCGI(self):
"""
If a CGI script emits two instances of the same header, both are sent in |
class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length', 'proxy'):
envname = "HTTP_" + envname
env[en... | class CGIScript(resource.Resource):
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace('-', '_').upper()
if title not in ('content-type', 'content-length'):
envname = "HTTP_" + envname
env[envname] = ... |
def test_categorical_no_compress():
def test_sort():
# http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby # noqa: E501
# This should result in a properly sorted Series so that the plot
# has a sorted x axis
# self.cat.groupby(['value_group'])['value_group'].co... | def test_categorical_no_compress():
def test_sort():
# http://stackoverflow.com/questions/23814368/sorting-pandas-
# categorical-labels-after-groupby
# This should result in a properly sorted Series so that the plot
# has a sorted x axis
# self.cat.groupby(['value_group'])['value_group'].co... |
from datetime import datetime
import pytest
from pandas import DatetimeIndex
import pandas.util.testing as tm
from pandas.tseries.holiday import ( | from datetime import datetime
import pytest
from pandas import DatetimeIndex, offsets, to_datetime
import pandas.util.testing as tm
from pandas.tseries.holiday import ( |
from pandas.tseries.holiday import (
Holiday,
Timestamp,
USFederalHolidayCalendar,
USThanksgivingDay,
get_calendar,
) | from pandas.tseries.holiday import (
Holiday,
Timestamp,
USFederalHolidayCalendar,
USLaborDay,
USThanksgivingDay,
get_calendar,
) |
def test_calendar_observance_dates():
def test_rule_from_name():
us_fed_cal = get_calendar("USFederalHolidayCalendar")
assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay | def test_calendar_observance_dates():
def test_rule_from_name():
us_fed_cal = get_calendar("USFederalHolidayCalendar")
assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay
def test_calendar_2031():
# See gh-27790
#
# Labor Day 2031 is on September 1. Saturday before is August 30.
... |
class AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass):
rules = [] # type: List[Holiday]
start_date = Timestamp(datetime(1970, 1, 1))
end_date = Timestamp(datetime(2030, 12, 31))
_cache = None
def __init__(self, name=None, rules=None): | class AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass):
rules = [] # type: List[Holiday]
start_date = Timestamp(datetime(1970, 1, 1))
end_date = Timestamp(datetime(2200, 12, 31))
_cache = None
def __init__(self, name=None, rules=None): |
class Grouping:
self._group_index = CategoricalIndex(
Categorical.from_codes(
codes=codes, categories=categories, ordered=self.grouper.ordered
)
)
# we are done | class Grouping:
self._group_index = CategoricalIndex(
Categorical.from_codes(
codes=codes, categories=categories, ordered=self.grouper.ordered
),
name=self.name,
)
# we are done |
def test_preserve_categories():
# ordered=True
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)})
index = CategoricalIndex(categories, categories, ordered=True)
tm.assert_index_equal(
df.groupby("A", sort=True, observed=False).first().index, index
) | def test_preserve_categories():
# ordered=True
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)})
index = CategoricalIndex(categories, categories, ordered=True, name="A")
tm.assert_index_equal(
df.groupby("A", sort=True, observed=False).first().index, index
... |
def test_preserve_categories():
# ordered=False
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)})
sort_index = CategoricalIndex(categories, categories, ordered=False)
nosort_index = CategoricalIndex(list("bac"), list("bac"), ordered=False)
tm.assert_index_equal(
... | def test_preserve_categories():
# ordered=False
df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)})
sort_index = CategoricalIndex(categories, categories, ordered=False, name="A")
nosort_index = CategoricalIndex(list("bac"), list("bac"), ordered=False, name="A")
tm.a... |
def test_groupby_categorical_axis_1(code):
result = df.groupby(cat, axis=1).mean()
expected = df.T.groupby(cat, axis=0).mean().T
assert_frame_equal(result, expected) | def test_groupby_categorical_axis_1(code):
result = df.groupby(cat, axis=1).mean()
expected = df.T.groupby(cat, axis=0).mean().T
assert_frame_equal(result, expected)
def test_groupby_cat_preserves_structure(observed):
# GH 28787
df = DataFrame([("Bob", 1), ("Greg", 2)], columns=["Name", "Item"])
... |
class StackedRNNCells(Layer):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_size
input_shape = (input_shape[0], input_shape[1], output_dim)
self.built = True
def get_config(self): | class StackedRNNCells(Layer):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_size
input_shape = (input_shape[0], output_dim)
self.built = True
def get_config(self): |
def test_minimal_rnn_cell_layer():
super(MinimalRNNCell, self).__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
initializer='uniform',
n... | def test_minimal_rnn_cell_layer():
super(MinimalRNNCell, self).__init__(**kwargs)
def build(self, input_shape):
# no time axis in the input shape passed to RNN cells
assert len(input_shape) == 2
self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
... |
from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import Variable, VariableDoesNotExist
from .library import Library
register = Library() | from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import VARIABLE_ATTRIBUTE_SEPARATOR
from .library import Library
register = Library() |
def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve
>>> _property_resolver(1)('abc')
'b' | def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, chain __getitem__() and getattr().
>>> _property_resolver(1)('abc')
'b' |
def _property_resolver(arg):
try:
float(arg)
except ValueError:
return Variable(arg).resolve
else:
return itemgetter(arg)
| def _property_resolver(arg):
try:
float(arg)
except ValueError:
if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_':
raise AttributeError('Access to private variables is forbidden.')
parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR)
def resolve(value):
... |
def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (TypeError, VariableDoesNotExist):
return ''
| def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (AttributeError, TypeError):
return ''
|
def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (TypeError, VariableDoesNotExist):
return ''
| def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (AttributeError, TypeError):
return ''
|
from django.template.defaultfilters import dictsort
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_sort(self):
sorted_dicts = dictsort(
[{'age': 23, 'name': 'Barbara-Ann'}, | from django.template.defaultfilters import _property_resolver, dictsort
from django.test import SimpleTestCase
class User:
password = 'abc'
_private = 'private'
@property
def test_property(self):
return 'cde'
def test_method(self):
"""This is just a test method."""
class Funct... |
class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses template.Variable under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ | class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses dict.get()/getattr() under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
self.assertEqual(dict... |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
... |
Tests for L{twisted.web.twcgi}.
"""
import sys, os
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import client, twcgi, server, resource
from twisted... | Tests for L{twisted.web.twcgi}.
"""
import sys
import os
import json
from io import BytesIO
from twisted.trial import unittest
from twisted.internet import reactor, interfaces, error
from twisted.python import util, failure, log
from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR
from twisted.web import cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.