buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class PyLibMCCacheTests(BaseMemcachedTests, TestCase):
# libmemcached manages its own connections.
should_disconnect_on_close = False
# By default, pylibmc/libmemcached don't verify keys client-side and so
# this test triggers a server-side bug that causes later tests to fail
# (#19914). The `verif... | class PyLibMCCacheTests(BaseMemcachedTests, TestCase):
# libmemcached manages its own connections.
should_disconnect_on_close = False
@override_settings(CACHES=caches_setting_for_tests(
base=PyLibMCCache_params,
exclude=memcached_excluded_caches, |
"""
from os import path, listdir
import os
import sys
import errno
import marshal | """
from os import path, listdir
import os
import stat
import sys
import errno
import marshal |
class FileSystemBytecodeCache(BytecodeCache):
# On windows the temporary directory is used specific unless
# explicitly forced otherwise. We can just use that.
if os.name == 'n':
return tmpdir
if not hasattr(os, 'getuid'):
raise RuntimeError('Cannot determine sa... | class FileSystemBytecodeCache(BytecodeCache):
# On windows the temporary directory is used specific unless
# explicitly forced otherwise. We can just use that.
if os.name == 'nt':
return tmpdir
if not hasattr(os, 'getuid'):
raise RuntimeError('Cannot determine s... |
class FileSystemBytecodeCache(BytecodeCache):
dirname = '_jinja2-cache-%d' % os.getuid()
actual_dir = os.path.join(tmpdir, dirname)
try:
# 448 == 0700
os.mkdir(actual_dir, 448)
except OSError as e:
if e.errno != errno.EEXIST:
raise
... | class FileSystemBytecodeCache(BytecodeCache):
dirname = '_jinja2-cache-%d' % os.getuid()
actual_dir = os.path.join(tmpdir, dirname)
try:
os.mkdir(actual_dir, stat.S_IRWXU) # 0o700
except OSError as e:
if e.errno != errno.EEXIST:
raise
actu... |
class BaseSettings(MutableMapping):
def getbool(self, name, default=False):
"""
Get a setting value as a boolean.
``1``, ``'1'``, and ``True`` return ``True``, while ``0``, ``'0'``,
``False`` and ``None`` return ``False``.
For example, settings populated through en... | class BaseSettings(MutableMapping):
def getbool(self, name, default=False):
"""
Get a setting value as a boolean.
``1``, ``'1'``, and ``True`` return ``True``, while ``0``, ``'0'``,
``False`` and ``None`` return ``False``.
For example, settings populated through environment... |
class BaseSettings(MutableMapping):
if basename in self:
warnings.warn('_BASE settings are deprecated.',
category=ScrapyDeprecationWarning)
compsett = BaseSettings(self[name + "_BASE"], priority='default')
compsett.update(self[name])
retu... | class BaseSettings(MutableMapping):
if basename in self:
warnings.warn('_BASE settings are deprecated.',
category=ScrapyDeprecationWarning)
# When users defined a _BASE setting, they explicitly don't want to
# use any of Scrapy's defaults. Therefore,... |
class BaseSettingsTest(unittest.TestCase):
def test_getcomposite(self):
s = BaseSettings({'TEST_BASE': {1: 1, 2: 2},
'TEST': BaseSettings({1: 10}),
'HASNOBASE': BaseSettings({1: 1})})
cs = s._getcomposite('TEST')
self.assertEqual(len(cs), ... | class BaseSettingsTest(unittest.TestCase):
def test_getcomposite(self):
s = BaseSettings({'TEST_BASE': {1: 1, 2: 2},
'TEST': BaseSettings({1: 10, 3: 30}, 'default'),
'HASNOBASE': BaseSettings({1: 1}, 'default')})
s['TEST'].set(4, 4, priority='proj... |
from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils.decorators import method_decorator
from django.utils.inspect import (
func_accepts_kwargs, func_accepts_var_args, get_func_full_arg... | from django.db import models
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf
from django.utils._os import safe_join
from django.utils.decorators import method_decorator
from django.utils.inspect import (
func_accepts_kwargs, f... |
class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(directory) / template
if template_file.exists():
templ... | class TemplateDetailView(BaseAdminDocsView):
else:
# This doesn't account for template loaders (#24128).
for index, directory in enumerate(default_engine.dirs):
template_file = Path(safe_join(directory, template))
if template_file.exists():
... |
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertContains(response, 'View documentation')
@override_settings(TEMPLATES=[{
'NAME': 'ONE',
'BACKEND': 'django.template.backends.django.DjangoTemplates', | class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.assertContains(response, 'View documentation')
@unittest.skipUnless(utils.docutils_is_available, 'no docutils installed.')
class AdminDocViewDefaultEngineOnly(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.force_logi... |
setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=1.0",
"jedi>=0.18,<1"
],
test_requires=[ | setup(
python_requires="~=3.6",
install_requires=[
"urwid>=1.1.1",
"pygments>=2.7.4",
"jedi>=0.18,<1"
],
test_requires=[ |
class ExtensionBlock(Block):
new_values = self.values if inplace else self.values.copy()
if isinstance(new, np.ndarray) and len(new) == len(mask):
new = new[mask]
mask = _safe_reshape(mask, new_values.shape) | class ExtensionBlock(Block):
new_values = self.values if inplace else self.values.copy()
if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask):
new = new[mask]
mask = _safe_reshape(mask, new_values.shape) |
class TestUpdate:
# GH 33215
series.update(other)
tm.assert_series_equal(series, expected) | class TestUpdate:
# GH 33215
series.update(other)
tm.assert_series_equal(series, expected)
@pytest.mark.parametrize(
"result, target, expected",
[
(
Series(["a", None], dtype="string"),
Series([None, "b"], dtype="string"),
... |
class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
| class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
classcell = attrs.pop('__classcell__', None)
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
|
class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
| class ItemMeta(ABCMeta):
new_attrs['fields'] = fields
new_attrs['_class'] = _class
if classcell is not None:
new_attrs['__classcell__'] = classcell
return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs)
|
import unittest
from scrapy.item import Item, Field
import six
class ItemTest(unittest.TestCase):
| import sys
import unittest
import six
from scrapy.item import ABCMeta, Item, ItemMeta, Field
from tests import mock
PY36_PLUS = (sys.version_info.major >= 3) and (sys.version_info.minor >= 6)
class ItemTest(unittest.TestCase):
|
class ItemTest(unittest.TestCase):
self.assertNotEqual(item['name'], copied_item['name'])
if __name__ == "__main__":
unittest.main() | class ItemTest(unittest.TestCase):
self.assertNotEqual(item['name'], copied_item['name'])
class ItemMetaTest(unittest.TestCase):
def test_new_method_propagates_classcell(self):
new_mock = mock.Mock(side_effect=ABCMeta.__new__)
base = ItemMeta.__bases__[0]
with mock.patch.object(b... |
import warnings
from binascii import Error as BinasciiError
from email.utils import formatdate
from urllib.parse import (
quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode,
urlparse,
)
from django.core.exceptions import TooManyFieldsSent | import warnings
from binascii import Error as BinasciiError
from email.utils import formatdate
from urllib.parse import (
ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, quote,
quote_plus, scheme_chars, unquote, unquote_plus,
urlencode as original_urlencode, uses_params,
)
from django.c... |
def is_safe_url(url, host=None, allowed_hosts=None, require_https=False):
_is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https))
def _is_safe_url(url, allowed_hosts, require_https=False):
# Chrome considers any URL with more than two slashes to be absolute, but
# urlpars... | def is_safe_url(url, host=None, allowed_hosts=None, require_https=False):
_is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https))
# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
def _urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into... |
class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'\n',
)
for bad_url in bad_urls: | class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'http:999999999',
'ftp:9999999999',
'\n',
)
for bad_url in bad_urls: |
class TestUtilsHttp(unittest.TestCase):
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
)
for good_url in good_urls:
with ignore_warnings(category=RemovedInDjango21Warning): | class TestUtilsHttp(unittest.TestCase):
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
'path/http:2222222222',
)
for good_url in good_urls:
with ignore_warnings(category=RemovedInDjango21Warning): |
class TestYoutubeDL(unittest.TestCase):
'ext': 'mp4',
'width': None,
'height': 1080,
}
def fname(templ): | class TestYoutubeDL(unittest.TestCase):
'ext': 'mp4',
'width': None,
'height': 1080,
'title1': '$PATH',
'title2': '%PATH%',
}
def fname(templ): |
class TestYoutubeDL(unittest.TestCase):
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%%(height)06d.%(ext)s'), '%(... | class TestYoutubeDL(unittest.TestCase):
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4')
self.assertEqual(fname('%%'), '%')
self.asse... |
import re
import shutil
import subprocess
import socket
import sys
import time
import tokenize | import re
import shutil
import subprocess
import socket
import string
import sys
import time
import tokenize |
class YoutubeDL(object):
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
filename = expand_path(outtmpl % template_dict)
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through... | class YoutubeDL(object):
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
# expand_path translates '%%' into '%' and '$$' into '$'
# correspondingly that is not what we want since we need to keep
# '%%' intac... |
def get_response(args, config_dir):
"""Send the request and return a `request.Response`."""
requests_session = get_requests_session()
if not args.session and not args.session_read_only:
kwargs = get_requests_kwargs(args) | def get_response(args, config_dir):
"""Send the request and return a `request.Response`."""
requests_session = get_requests_session()
requests_session.max_redirects = args.max_redirects
if not args.session and not args.session_read_only:
kwargs = get_requests_kwargs(args) |
def main(args=sys.argv[1:], env=Environment(), error=None):
error('Too many redirects (--max-redirects=%s).', args.max_redirects)
except Exception as e:
# TODO: Better distinction between expected and unexpected errors.
# Network errors vs. bugs, etc.
if traceback:
... | def main(args=sys.argv[1:], env=Environment(), error=None):
error('Too many redirects (--max-redirects=%s).', args.max_redirects)
except Exception as e:
# TODO: Better distinction between expected and unexpected errors.
if traceback:
raise
msg = str(e) |
class TestRedirects:
assert HTTP_OK in r
def test_max_redirects(self, httpbin):
r = http('--max-redirects=2', '--follow', httpbin.url + '/redirect/3',
error_exit_ok=True)
assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS | class TestRedirects:
assert HTTP_OK in r
def test_max_redirects(self, httpbin):
r = http('--max-redirects=1', '--follow', httpbin.url + '/redirect/3',
error_exit_ok=True)
assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS |
to the w3lib.url module. Always import those from there instead.
"""
import posixpath
import re
from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag,
urlparse, parse_qsl, urlencode,
unquote)
# scrapy.utils.url was moved to w3lib.... | to the w3lib.url module. Always import those from there instead.
"""
import posixpath
import re
import six
from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag,
urlparse, parse_qsl, urlencode,
quote, unquote)
if six.PY3:
from ... |
def url_has_any_extension(url, extensions):
return posixpath.splitext(parse_url(url).path)[1].lower() in extensions
def canonicalize_url(url, keep_blank_values=True, keep_fragments=False,
encoding=None):
"""Canonicalize the given url by applying the following procedures:
- sort query... | def url_has_any_extension(url, extensions):
return posixpath.splitext(parse_url(url).path)[1].lower() in extensions
def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):
return (
to_native_str(parts.scheme),
to_native_str(parts.netloc.encode('idna')),
# default encoding... |
def parse_url(url, encoding=None):
"""
if isinstance(url, ParseResult):
return url
return urlparse(to_native_str(url, encoding))
def escape_ajax(url): | def parse_url(url, encoding=None):
"""
if isinstance(url, ParseResult):
return url
return urlparse(to_unicode(url, encoding))
if six.PY3:
from urllib.parse import _coerce_args, unquote_to_bytes
def parse_qsl_to_bytes(qs, keep_blank_values=False, strict_parsing=False):
"""Parse a q... |
import unittest
import six
from scrapy.spiders import Spider
from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider,
canonicalize_url, add_http_if_no_scheme,
guess_scheme)
__doctests__ = ['scrapy.utils.url']
| import unittest
import six
from six.moves.urllib.parse import urlparse
from scrapy.spiders import Spider
from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider,
canonicalize_url, add_http_if_no_scheme,
guess_scheme, parse_url)
__doctests__... |
class CanonicalizeUrlTest(unittest.TestCase):
self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"),
"http://www.example.com/do?a=1&q=a+space")
@unittest.skipUnless(six.PY2, "TODO")
def test_normalize_percent_encoding_in_paths(self):
... | class CanonicalizeUrlTest(unittest.TestCase):
self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"),
"http://www.example.com/do?a=1&q=a+space")
def test_canonicalize_url_unicode_path(self):
self.assertEqual(canonicalize_url(u"http:/... |
class CanonicalizeUrlTest(unittest.TestCase):
"http://www.example.com/a%20do%C2%A3.html?a=1")
def test_non_ascii_percent_encoding_in_query_arguments(self):
self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=\xa3500&a=5&z=3"),
... | class CanonicalizeUrlTest(unittest.TestCase):
"http://www.example.com/a%20do%C2%A3.html?a=1")
def test_non_ascii_percent_encoding_in_query_arguments(self):
self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=£500&a=5&z=3"),
... |
class CanonicalizeUrlTest(unittest.TestCase):
"http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"),
"http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html")
@unittest.skipUnless(six.PY2, "TODO")
... | class CanonicalizeUrlTest(unittest.TestCase):
"http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"),
"http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html")
def test_safe_characters_unicode(self):
... |
class CanonicalizeUrlTest(unittest.TestCase):
self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"),
"http://www.example.com/")
def test_quoted_slash_and_question_sign(self):
self.assertEqual(canonicalize_url("http://foo.com/AC%2FDC+rocks%3f/?yeah=1"... | class CanonicalizeUrlTest(unittest.TestCase):
self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"),
"http://www.example.com/")
def test_canonicalize_idns(self):
self.assertEqual(canonicalize_url(u'http://www.bücher.de?q=bücher'),
... |
import numpy as np
import time
import json
import warnings
from collections import deque
from collections import OrderedDict | import numpy as np
import time
import json
import warnings
import io
import sys
from collections import deque
from collections import OrderedDict |
class CSVLogger(Callback):
self.writer = None
self.keys = None
self.append_header = True
self.file_flags = 'b' if six.PY2 and os.name == 'nt' else ''
super(CSVLogger, self).__init__()
def on_train_begin(self, logs=None): | class CSVLogger(Callback):
self.writer = None
self.keys = None
self.append_header = True
if six.PY2:
self.file_flags = 'b'
self._open_args = {}
else:
self.file_flags = ''
self._open_args = {'newline': '\n'}
super(CSVLogger, ... |
class CSVLogger(Callback):
if os.path.exists(self.filename):
with open(self.filename, 'r' + self.file_flags) as f:
self.append_header = not bool(len(f.readline()))
self.csv_file = open(self.filename, 'a' + self.file_flags)
else:
self.csv_fi... | class CSVLogger(Callback):
if os.path.exists(self.filename):
with open(self.filename, 'r' + self.file_flags) as f:
self.append_header = not bool(len(f.readline()))
mode = 'a'
else:
mode = 'w'
self.csv_file = io.open(self.filename,
... |
class CSVLogger(Callback):
if not self.writer:
class CustomDialect(csv.excel):
delimiter = self.sep
self.writer = csv.DictWriter(self.csv_file,
fieldnames=['epoch'] + self.keys, dialect=CustomDialect)
if self.append_he... | class CSVLogger(Callback):
if not self.writer:
class CustomDialect(csv.excel):
delimiter = self.sep
fieldnames = ['epoch'] + self.keys
if six.PY2:
fieldnames = [unicode(x) for x in fieldnames]
self.writer = csv.DictWriter(self.csv_f... |
def test_CSVLogger(tmpdir):
# case 3, reuse of CSVLogger object
model.fit(X_train, y_train, batch_size=batch_size,
validation_data=(X_test, y_test), callbacks=cbks, epochs=1)
import re
with open(filepath) as csvfile:
output = " ".join(csvfile.readlines())
assert len(re.fi... | def test_CSVLogger(tmpdir):
# case 3, reuse of CSVLogger object
model.fit(X_train, y_train, batch_size=batch_size,
validation_data=(X_test, y_test), callbacks=cbks, epochs=2)
import re
with open(filepath) as csvfile:
list_lines = csvfile.readlines()
for line in list_lines... |
class Parser:
if (new_data == data).all():
data = new_data
result = True
except (TypeError, ValueError):
pass
# coerce ints to 64 | class Parser:
if (new_data == data).all():
data = new_data
result = True
except (TypeError, ValueError, OverflowError):
pass
# coerce ints to 64 |
DataFrame\\.index values are different \\(100\\.0 %\\)
with tm.assert_produces_warning(FutureWarning):
result = read_json(expected.to_json(), numpy=True)
tm.assert_frame_equal(result, expected) | DataFrame\\.index values are different \\(100\\.0 %\\)
with tm.assert_produces_warning(FutureWarning):
result = read_json(expected.to_json(), numpy=True)
tm.assert_frame_equal(result, expected)
def test_frame_int_overflow(self):
# GH 30320
encoded_json = json.dumps([... |
class Axes(_AxesBase):
except ValueError:
pass # Failed to convert to float array; must be color specs.
else:
# If c can be either mapped values or a RGB(A) color, prefer
# the former if shapes match, the latter otherwise.
if c.siz... | class Axes(_AxesBase):
except ValueError:
pass # Failed to convert to float array; must be color specs.
else:
# handle the documented special case of a 2D array with 1
# row which as RGB(A) to broadcast.
if c.shape == (1, 4) or c.s... |
class TestScatter:
c=c_case, edgecolors="black", kwargs={}, xsize=xsize,
get_next_color_func=get_next_color)
def _params(c=None, xsize=2, *, edgecolors=None, **kwargs):
return (c, edgecolors, kwargs if kwargs is not None else {}, xsize) | class TestScatter:
c=c_case, edgecolors="black", kwargs={}, xsize=xsize,
get_next_color_func=get_next_color)
@pytest.mark.style('default')
@check_figures_equal(extensions=["png"])
def test_scatter_single_color_c(self, fig_test, fig_ref):
rgb = [[1, 0.5, 0.05]... |
class MultiIndex(Index):
if names is lib.no_default:
names = [getattr(it, "name", None) for it in iterables]
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
| class MultiIndex(Index):
if names is lib.no_default:
names = [getattr(it, "name", None) for it in iterables]
# codes are all ndarrays, so cartesian_product is lossless
codes = cartesian_product(codes)
return MultiIndex(levels, codes, sortorder=sortorder, names=names)
|
import numpy as np
from pandas.core.dtypes.common import is_list_like
import pandas.core.common as com
def cartesian_product(X):
""" | import numpy as np
from pandas.core.dtypes.common import is_list_like
def cartesian_product(X):
""" |
def cartesian_product(X):
# if any factor is empty, the cartesian product is empty
b = np.zeros_like(cumprodX)
return [
np.tile(
np.repeat(np.asarray(com.values_from_object(x)), b[i]), np.product(a[i])
)
for i, x in enumerate(X)
] | def cartesian_product(X):
# if any factor is empty, the cartesian product is empty
b = np.zeros_like(cumprodX)
return [_tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)]
def _tile_compat(arr, num: int):
"""
Index compat for np.tile.
Notes
-----
Does ... |
class TestPivotTable:
tm.assert_frame_equal(result, expected)
def test_pivot_integer_columns(self):
# caused by upstream bug in unstack
| class TestPivotTable:
tm.assert_frame_equal(result, expected)
def test_pivot_table_retains_tz(self):
dti = date_range("2016-01-01", periods=3, tz="Europe/Amsterdam")
df = DataFrame({"A": np.random.randn(3), "B": np.random.randn(3), "C": dti})
result = df.pivot_table(index=["B", "C"... |
class TestCartesianProduct:
tm.assert_index_equal(result1, expected1)
tm.assert_index_equal(result2, expected2)
def test_empty(self):
# product of empty factors
X = [[], [0, 1], []] | class TestCartesianProduct:
tm.assert_index_equal(result1, expected1)
tm.assert_index_equal(result2, expected2)
def test_tzaware_retained(self):
x = date_range("2000-01-01", periods=2, tz="US/Pacific")
y = np.array([3, 4])
result1, result2 = cartesian_product([x, y])
... |
class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
return self._save(name, content)
# These methods are part of the public API, with default implementations.
| class Storage:
content = File(content, name)
name = self.get_available_name(name, max_length=max_length)
name = self._save(name, content)
# Ensure that the name returned from the storage system is still valid.
validate_file_name(name, allow_relative_path=True)
return... |
class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise SuspiciousFileOperation("Detected path traversal ... | class Storage:
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
name = str(name).replace('\\', '/')
dir_name, file_name = os.path.split(name)
if '..' in pathlib.PurePath(dir_name).parts:
raise Suspi... |
class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(filename)
if '..' in pathlib.PurePath(dirnam... | class Storage:
Validate the filename by calling get_valid_name() and return a filename
to be passed to the save() method.
"""
filename = str(filename).replace('\\', '/')
# `filename` may include a path as returned by FileField.upload_to.
dirname, filename = os.path.split(... |
class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Store filenames with forward slashes, even on Windows.
return name.replace('\\', '/')
| class FileSystemStorage(Storage):
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
# Ensure the saved path is always relative to the storage root.
name = os.path.relpath(full_path, self.location)
# Store filenames with forward slashe... |
class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
file_name = '/tmp/../path'
s = FileSystemStorage()
msg = "Detected path traversal attempt in '/tmp/..'"
with self.assertRaisesMessa... | class GenerateFilenameStorageTests(SimpleTestCase):
s.generate_filename(file_name)
def test_storage_dangerous_paths_dir_name(self):
candidates = [
('tmp/../path', 'tmp/..'),
('tmp\\..\\path', 'tmp/..'),
('/tmp/../path', '/tmp/..'),
('\\tmp... |
class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_save_doesnt_close(self):
with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file:
file.write(b'1') | class FileStorageTests(SimpleTestCase):
self.storage.delete('path/to/test.file')
def test_file_save_abs_path(self):
test_name = 'path/to/test.file'
f = ContentFile('file saved with path')
f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f)
self.assertEqual... |
class Axes(_AxesBase):
zdelta = 0.1
def line_props_with_rcdefaults(subkey, explicit, zdelta=0):
d = {k.split('.')[-1]: v for k, v in rcParams.items()
if k.startswith(f'boxplot.{subkey}')}
d['zorder'] = zorder + zdelta
if explicit is not None:
... | class Axes(_AxesBase):
zdelta = 0.1
def line_props_with_rcdefaults(subkey, explicit, zdelta=0,
use_marker=True):
d = {k.split('.')[-1]: v for k, v in rcParams.items()
if k.startswith(f'boxplot.{subkey}')}
d['zorder'] = zor... |
class Axes(_AxesBase):
cbook.normalize_kwargs(
boxprops, mpatches.PathPatch._alias_map))
else:
final_boxprops = line_props_with_rcdefaults('boxprops', boxprops)
final_whiskerprops = line_props_with_rcdefaults(
'whiskerprops', whiskerpro... | class Axes(_AxesBase):
cbook.normalize_kwargs(
boxprops, mpatches.PathPatch._alias_map))
else:
final_boxprops = line_props_with_rcdefaults('boxprops', boxprops,
use_marker=False)
final_whisker... |
def test_boxplot_bad_ci_2():
ax.boxplot([x, x], conf_intervals=[[1, 2], [1]])
@image_comparison(['boxplot_mod_artists_after_plotting.png'],
remove_text=True, savefig_kwarg={'dpi': 40}, style='default')
def test_boxplot_mod_artist_after_plotting(): | def test_boxplot_bad_ci_2():
ax.boxplot([x, x], conf_intervals=[[1, 2], [1]])
def test_boxplot_marker_behavior():
plt.rcParams['lines.marker'] = 's'
plt.rcParams['boxplot.flierprops.marker'] = 'o'
plt.rcParams['boxplot.meanprops.marker'] = '^'
fig, ax = plt.subplots()
test_data = np.arange... |
class Scheduler(object):
if (best_task and batched_params and task.family == best_task.family and
len(batched_tasks) < max_batch_size and task.is_batchable() and all(
task.params.get(name) == value for name, value in unbatched_params.items())):
for na... | class Scheduler(object):
if (best_task and batched_params and task.family == best_task.family and
len(batched_tasks) < max_batch_size and task.is_batchable() and all(
task.params.get(name) == value for name, value in unbatched_params.items()) and
... |
class SchedulerApiTest(unittest.TestCase):
self.assertEqual({'a': ['1', '2', '3']}, response['task_params'])
self.assertEqual('A', response['task_family'])
def test_get_work_with_batch_items_with_resources(self):
self.sch.add_task_batcher(worker=WORKER, task_family='A', batched_args=['a'])
... | class SchedulerApiTest(unittest.TestCase):
self.assertEqual({'a': ['1', '2', '3']}, response['task_params'])
self.assertEqual('A', response['task_family'])
def test_batch_ignore_items_not_ready(self):
self.sch.add_task_batcher(worker=WORKER, task_family='A', batched_args=['a'])
self... |
class SchedulerApiTest(unittest.TestCase):
not_nurtured_statuses = [DONE, UNKNOWN, DISABLED, PENDING, FAILED]
for status in nurtured_statuses:
print(status)
self.assertEqual(set([status.lower()]), set(self.sch.task_list(status, '')))
for status in not_nurtured_statuses:... | class SchedulerApiTest(unittest.TestCase):
not_nurtured_statuses = [DONE, UNKNOWN, DISABLED, PENDING, FAILED]
for status in nurtured_statuses:
self.assertEqual(set([status.lower()]), set(self.sch.task_list(status, '')))
for status in not_nurtured_statuses:
self.assertEq... |
class WebSocketTest(WebSocketBaseTestCase):
response = self.fetch('/echo')
self.assertEqual(response.code, 400)
def test_bad_websocket_version(self):
response = self.fetch('/echo',
headers={'Connection': 'Upgrade', | class WebSocketTest(WebSocketBaseTestCase):
response = self.fetch('/echo')
self.assertEqual(response.code, 400)
def test_missing_websocket_key(self):
response = self.fetch('/echo',
headers={'Connection': 'Upgrade',
'Upgrad... |
class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
self._accept_connection()
except ValueError:
gen_log.debug("Malformed WebSocket request received", | class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
except ValueError:
self.handler.set_status(400)
log_msg = "Missing/Invalid WebSocket headers"
self.handler.finish(log_msg)
gen_... |
import inspect
import sys
PY3 = (sys.version_info[0] == 3)
if hasattr(abc, 'ABC'):
ABC = abc.ABC | import inspect
import sys
PY3 = (sys.version_info[0] == 3)
PY2 = not PY3
if hasattr(abc, 'ABC'):
ABC = abc.ABC |
import traceback
from .variables import CommonVariable, Exploding, BaseVariable
from . import utils, pycompat
ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') | import traceback
from .variables import CommonVariable, Exploding, BaseVariable
from . import utils, pycompat
if pycompat.PY2:
from io import open
ipython_filename_pattern = re.compile('^<ipython-input-([0-9]+)-.*>$') |
def get_source_from_frame(frame):
# apply tokenize.detect_encoding to decode the source into a
# string, then we should do that ourselves.
if isinstance(source[0], bytes):
encoding = 'ascii'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
... | def get_source_from_frame(frame):
# apply tokenize.detect_encoding to decode the source into a
# string, then we should do that ourselves.
if isinstance(source[0], bytes):
encoding = 'utf-8'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
... |
class FileWriter(object):
self.overwrite = overwrite
def write(self, s):
with open(self.path, 'w' if self.overwrite else 'a') as output_file:
output_file.write(s)
self.overwrite = False
| class FileWriter(object):
self.overwrite = overwrite
def write(self, s):
with open(self.path, 'w' if self.overwrite else 'a',
encoding='utf-8') as output_file:
output_file.write(s)
self.overwrite = False
|
def assert_output(output, expected_entries, prefix=None):
any_mismatch = False
result = ''
template = '\n{line!s:%s} {expected_entry} {arrow}' % max(map(len, lines))
for expected_entry, line in zip_longest(expected_entries, lines, fillvalue=""):
mismatch = not (expected_entry and expected_en... | def assert_output(output, expected_entries, prefix=None):
any_mismatch = False
result = ''
template = u'\n{line!s:%s} {expected_entry} {arrow}' % max(map(len, lines))
for expected_entry, line in zip_longest(expected_entries, lines, fillvalue=""):
mismatch = not (expected_entry and expected_e... |
def assert_sample_output(module):
with sys_tools.OutputCapturer(stdout=False,
stderr=True) as output_capturer:
module.main()
time = '21:10:42.298924'
time_pattern = re.sub(r'\d', r'\\d', time)
| def assert_sample_output(module):
with sys_tools.OutputCapturer(stdout=False,
stderr=True) as output_capturer:
module.main()
time = '21:10:42.298924'
time_pattern = re.sub(r'\d', r'\\d', time)
|
default: :rc:`scatter.edgecolors`
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
linewidths = rcParams['lines.linewidth']
offsets = np.ma.column_stack([x, y])
| default: :rc:`scatter.edgecolors`
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
if linewidths is None:
linewidths = rcParams['lines.linewidth']
elif np.iterable(linewidths):
linewidths = [
... |
class TestScatter:
ax_test.scatter(np.ones(3), range(3), c=rgb)
ax_test.scatter(np.ones(4)*2, range(4), c=rgba)
def _params(c=None, xsize=2, *, edgecolors=None, **kwargs):
return (c, edgecolors, kwargs if kwargs is not None else {}, xsize) | class TestScatter:
ax_test.scatter(np.ones(3), range(3), c=rgb)
ax_test.scatter(np.ones(4)*2, range(4), c=rgba)
def test_scatter_linewidths(self):
x = np.arange(5)
fig, ax = plt.subplots()
for i in range(3):
pc = ax.scatter(x, np.full(5, i), c=f'C{i}', marker='x... |
class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
os.makedirs(self._dir, 0o700, exist_ok=True)
def _key_to_file(self, key, version=None):
""" | class FileBasedCache(BaseCache):
self._delete(fname)
def _createdir(self):
# Set the umask because os.makedirs() doesn't apply the "mode" argument
# to intermediate-level directories.
old_umask = os.umask(0o077)
try:
os.makedirs(self._dir, 0o700, exist_ok=Tru... |
import os
import pickle
import re
import shutil
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock
from django.conf import settings
from django.core import management, signals | import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock, skipIf
from django.conf import settings
from django.core import management, signals |
class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
def test_get_does_not_ignore_non_filenotfound_exceptions(self):
with mock.patch('builtins.open', side_effect=OSError):
with self.asser... | class FileBasedCacheTests(BaseCacheTests, TestCase):
# Returns the default instead of erroring.
self.assertEqual(cache.get('foo', 'baz'), 'baz')
@skipIf(
sys.platform == 'win32',
'Windows only partially supports umasks and chmod.',
)
def test_cache_dir_permissions(self):
... |
def pivot_table(
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
if table.index.nlevels > 1:
# Related GH #17123
# If index_names are integers, determine whether the integers refer
# to the level position or name. | def pivot_table(
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
# GH17038, this check should only happen if index is defined (not None)
if table.index.nlevels > 1 and index:
# Related GH #17123
# If index_names are integers, determine whether the ... |
class TestPivotTable:
totals = table.loc[("All", ""), value_col]
assert totals == self.data[value_col].mean()
# no rows
rtable = self.data.pivot_table(
columns=["AA", "BB"], margins=True, aggfunc=np.mean
)
assert isinstance(rtable, Series)
ta... | class TestPivotTable:
totals = table.loc[("All", ""), value_col]
assert totals == self.data[value_col].mean()
table = self.data.pivot_table(index=["AA", "BB"], margins=True, aggfunc="mean")
for item in ["DD", "EE", "FF"]:
totals = table.loc[("All", ""), item] |
class TestPivotTable:
tm.assert_frame_equal(expected, result)
def test_pivot_integer_columns(self):
# caused by upstream bug in unstack
| class TestPivotTable:
tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("cols", [(1, 2), ("a", "b"), (1, "b"), ("a", 1)])
def test_pivot_table_multiindex_only(self, cols):
# GH 17038
df2 = DataFrame({cols[0]: [1, 2, 3], cols[1]: [1, 2, 3], "v": [4, 5, 6]})
resul... |
def delete(self, req, id):
raise HTTPForbidden(explanation=msg, request=req,
content_type="text/plain")
status = 'deleted'
try:
# The image's location field may be None in the case
# of a saving or queued image, therefore don't ask a b... | def delete(self, req, id):
raise HTTPForbidden(explanation=msg, request=req,
content_type="text/plain")
if image['location'] and CONF.delayed_delete:
status = 'pending_delete'
else:
status = 'deleted'
try:
# Delete... |
def request(self, method, url, body=None, headers=None):
def getresponse(self):
mapper = routes.Mapper()
api = context.UnauthenticatedContextMiddleware(rserver.API(mapper))
webob_res = self.req.get_response(api)
return utils.FakeHTTPResponse(status=webob_res.status_int, | def request(self, method, url, body=None, headers=None):
def getresponse(self):
mapper = routes.Mapper()
server = rserver.API(mapper)
# NOTE(markwash): we need to pass through context auth information if
# we have it.
if 'X-Auth-Token' in self.req.headers:
api = ... |
def test_delete_non_exists_image(self):
res = req.get_response(self.api)
self.assertEquals(res.status_int, webob.exc.HTTPNotFound.code)
def test_delete_queued_image(self):
"""Delete an image in a queued state
| def test_delete_non_exists_image(self):
res = req.get_response(self.api)
self.assertEquals(res.status_int, webob.exc.HTTPNotFound.code)
def test_delete_not_allowed(self):
# Verify we can get the image data
req = webob.Request.blank("/images/%s" % UUID2)
req.method = 'GET'
... |
def process_request(self, req):
'tenant': tenant,
'roles': roles,
'is_admin': self.is_admin,
}
req.context = context.RequestContext(**kwargs) | def process_request(self, req):
'tenant': tenant,
'roles': roles,
'is_admin': self.is_admin,
'auth_tok': auth_tok,
}
req.context = context.RequestContext(**kwargs) |
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_s3_url
def get_engine(engine): | from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url
def get_engine(engine): |
class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path):
# path is s3:// so we need to open the s3file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or_buffer(path, mode="wb")
... | class FastParquetImpl(BaseImpl):
if partition_cols is not None:
kwargs["file_scheme"] = "hive"
if is_s3_url(path) or is_gcs_url(path):
# if path is s3:// or gs:// we need to open the file in 'wb' mode.
# TODO: Support 'ab'
path, _, _, _ = get_filepath_or... |
from io import StringIO
import numpy as np
import pytest | from io import StringIO
import os
import numpy as np
import pytest |
def test_to_csv_gcs(monkeypatch):
assert_frame_equal(df1, df2)
@td.skip_if_no("gcsfs")
def test_gcs_get_filepath_or_buffer(monkeypatch):
df1 = DataFrame( | def test_to_csv_gcs(monkeypatch):
assert_frame_equal(df1, df2)
@td.skip_if_no("fastparquet")
@td.skip_if_no("gcsfs")
def test_to_parquet_gcs_new_file(monkeypatch, tmpdir):
"""Regression test for writing to a not-yet-existent GCS Parquet file."""
df1 = DataFrame(
{
"int": [1, 3],
... |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S)
re_chars = re.compile(r'<.*?>|(.)', re.U | re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'... | def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S)
re_chars = re.compile(r'<[^>]+?>|(.)', re.S)
re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|... |
class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three <br>four ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... | class FunctionTests(SimpleTestCase):
def test_truncate2(self):
self.assertEqual(
truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4),
'<p>one <a href="#">two - three ...</a></p>',
)
def test_truncate3(self):
self.assertEqual(
... |
class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_words(self):
truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
self.assert... | class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...')
def test_truncate_chars_html(self):
perf_test_values = [
(('</a' + '\t' * 50000) + '//>', None),
('&' ... |
class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... | class TestUtilsText(SimpleTestCase):
truncator = text.Truncator('<i>Buenos días! ¿Cómo está?</i>')
self.assertEqual('<i>Buenos días! ¿Cómo...</i>', truncator.words(3, '...', html=True))
truncator = text.Truncator('<p>I <3 python, what about you... |
class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('%20;'), '%20;')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(
unescapeHTML('é'), 'é')
def test_daterange(self):
_20century = Da... | class TestUtil(unittest.TestCase):
self.assertEqual(unescapeHTML('%20;'), '%20;')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('/'), '/')
self.assertEqual(unescapeHTML('é'), 'é')
self.assertEqual(unescapeHTML('�'), '�... |
def _htmlentity_transform(entity):
numstr = '0%s' % numstr
else:
base = 10
return compat_chr(int(numstr, base))
# Unknown entity in name, return its literal representation
return ('&%s;' % entity) | def _htmlentity_transform(entity):
numstr = '0%s' % numstr
else:
base = 10
# See https://github.com/rg3/youtube-dl/issues/7518
try:
return compat_chr(int(numstr, base))
except ValueError:
pass
# Unknown entity in name, return its liter... |
class PKey(object):
:raises: ``IOError`` -- if there was an error writing the file.
"""
with open(filename, "w") as f:
os.chmod(filename, o600)
self._write_private_key(f, key, format, password=password)
| class PKey(object):
:raises: ``IOError`` -- if there was an error writing the file.
"""
# Ensure that we create new key files directly with a user-only mode,
# instead of opening, writing, then chmodding, which leaves us open to
# CVE-2022-24302.
# NOTE: O_TRUNC is a noo... |
Some unit tests for public/private key objects.
import unittest
import os
from binascii import hexlify
from hashlib import md5
| Some unit tests for public/private key objects.
import unittest
import os
import stat
from binascii import hexlify
from hashlib import md5
|
from paramiko import (
SSHException,
)
from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers
from mock import patch
import pytest
from .util import _support, is_low_entro... | from paramiko import (
SSHException,
)
from paramiko.py3compat import StringIO, byte_chr, b, bytes, PY2
from paramiko.common import o600
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers
from mock import patch, Mock
import pytest
f... |
class KeyTest(unittest.TestCase):
key1.load_certificate,
_support("test_rsa.key-cert.pub"),
) | class KeyTest(unittest.TestCase):
key1.load_certificate,
_support("test_rsa.key-cert.pub"),
)
@patch("paramiko.pkey.os")
def _test_keyfile_race(self, os_, exists):
# Re: CVE-2022-24302
password = "television"
newpassword = "radio"
source = _suppor... |
class JSON(object):
json_renderer_factory = JSON() # bw compat
JSONP_VALID_CALLBACK = re.compile(r"^[a-zA-Z_$][0-9a-zA-Z_$]+$")
class JSONP(JSON):
""" `JSONP <http://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper | class JSON(object):
json_renderer_factory = JSON() # bw compat
JSONP_VALID_CALLBACK = re.compile(r"^[$a-z_][$0-9a-z_\.\[\]]+[^.]$", re.I)
class JSONP(JSON):
""" `JSONP <http://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper |
class JSONP(JSON):
raise HTTPBadRequest('Invalid JSONP callback function name.')
ct = 'application/javascript'
body = '%s(%s);' % (callback, val)
response = request.response
if response.content_type == response.default_cont... | class JSONP(JSON):
raise HTTPBadRequest('Invalid JSONP callback function name.')
ct = 'application/javascript'
body = '/**/{0}({1});'.format(callback, val)
response = request.response
if response.content_type == response.de... |
class TestJSONP(unittest.TestCase):
request = testing.DummyRequest()
request.GET['callback'] = 'callback'
result = renderer({'a':'1'}, {'request':request})
self.assertEqual(result, 'callback({"a": "1"});')
self.assertEqual(request.response.content_type,
'... | class TestJSONP(unittest.TestCase):
request = testing.DummyRequest()
request.GET['callback'] = 'callback'
result = renderer({'a':'1'}, {'request':request})
self.assertEqual(result, '/**/callback({"a": "1"});')
self.assertEqual(request.response.content_type,
... |
class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
| class Field(dict):
class ItemMeta(ABCMeta):
def __new__(mcs, class_name, bases, attrs):
classcell = attrs.pop('__classcell__', None)
new_bases = tuple(base._class for base in bases if hasattr(base, '_class'))
_class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.