buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def authenticate(self, context, auth=None):
if 'passwordCredentials' in auth:
user_id = auth['passwordCredentials'].get('userId', None)
username = auth['passwordCredentials'].get('username', '')
password = auth['passwordCredentials'].get('password', '')
tenant_na... | def authenticate(self, context, auth=None):
if 'passwordCredentials' in auth:
user_id = auth['passwordCredentials'].get('userId', None)
if user_id and len(user_id) > MAX_PARAM_SIZE:
raise exception.ValidationSizeError(attribute='userId',
... |
def authenticate(self, context, auth=None):
# more compat
tenant_id = auth.get('tenantId', None)
if tenant_name:
try:
tenant_ref = self.identity_api.get_tenant_by_name( | def authenticate(self, context, auth=None):
# more compat
tenant_id = auth.get('tenantId', None)
if tenant_id and len(tenant_id) > MAX_PARAM_SIZE:
raise exception.ValidationSizeError(attribute='tenantId',
size=MAX_P... |
def authenticate(self, context, auth=None):
catalog_ref = {}
elif 'token' in auth:
old_token = auth['token'].get('id', None)
tenant_name = auth.get('tenantName')
try:
old_token_ref = self.token_api.get_token(context=context, | def authenticate(self, context, auth=None):
catalog_ref = {}
elif 'token' in auth:
old_token = auth['token'].get('id', None)
if len(old_token) > MAX_TOKEN_SIZE:
raise exception.ValidationSizeError(attribute='token',
... |
import default_fixtures
from keystone import config
from keystone import service
from keystone import test
from keystone.identity.backends import kvs as kvs_identity | import default_fixtures
from keystone import config
from keystone import exception
from keystone import service
from keystone import test
from keystone.identity.backends import kvs as kvs_identity |
CONF = config.CONF
class TokenExpirationTest(test.TestCase):
def setUp(self):
super(TokenExpirationTest, self).setUp() | CONF = config.CONF
def _build_user_auth(token=None, user_id=None, username=None,
password=None, tenant_id=None, tenant_name=None):
"""Build auth dictionary.
It will create an auth dictionary based on all the arguments
that it receives.
"""
auth_json = {}
if token is not N... |
def _maintain_token_expiration(self):
def test_maintain_uuid_token_expiration(self):
self.opt_in_group('signing', token_format='UUID')
self._maintain_token_expiration() | def _maintain_token_expiration(self):
def test_maintain_uuid_token_expiration(self):
self.opt_in_group('signing', token_format='UUID')
self._maintain_token_expiration()
class AuthTest(test.TestCase):
def setUp(self):
super(AuthTest, self).setUp()
CONF.identity.driver = 'keysto... |
from asgiref.local import Local
from django.conf import settings
from django.core import signals
from django.core.cache.backends.base import (
BaseCache, CacheKeyWarning, InvalidCacheBackendError,
)
from django.utils.module_loading import import_string
__all__ = [
'cache', 'caches', 'DEFAULT_CACHE_ALIAS', 'Inv... | from asgiref.local import Local
from django.conf import settings
from django.core import signals
from django.core.cache.backends.base import (
BaseCache, CacheKeyWarning, InvalidCacheBackendError, InvalidCacheKey,
)
from django.utils.module_loading import import_string
__all__ = [
'cache', 'caches', 'DEFAULT_C... |
class CacheKeyWarning(RuntimeWarning):
pass
# Stub class to ensure not passing in a `timeout` argument results in
# the default timeout
DEFAULT_TIMEOUT = object() | class CacheKeyWarning(RuntimeWarning):
pass
class InvalidCacheKey(ValueError):
pass
# Stub class to ensure not passing in a `timeout` argument results in
# the default timeout
DEFAULT_TIMEOUT = object() |
class BaseCache:
backend. This encourages (but does not force) writing backend-portable
cache code.
"""
if len(key) > MEMCACHE_MAX_KEY_LENGTH:
warnings.warn(
'Cache key will cause errors if used with memcached: %r '
'(longer than %s)' % (key, M... | class BaseCache:
backend. This encourages (but does not force) writing backend-portable
cache code.
"""
for warning in memcache_key_warnings(key):
warnings.warn(warning, CacheKeyWarning)
def incr_version(self, key, delta=1, version=None):
""" |
class BaseCache:
def close(self, **kwargs):
"""Close the cache connection"""
pass | class BaseCache:
def close(self, **kwargs):
"""Close the cache connection"""
pass
def memcache_key_warnings(key):
if len(key) > MEMCACHE_MAX_KEY_LENGTH:
yield (
'Cache key will cause errors if used with memcached: %r '
'(longer than %s)' % (key, MEMCACHE_MAX_KEY... |
import pickle
import re
import time
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.utils.functional import cached_property
| import pickle
import re
import time
from django.core.cache.backends.base import (
DEFAULT_TIMEOUT, BaseCache, InvalidCacheKey, memcache_key_warnings,
)
from django.utils.functional import cached_property
|
class BaseMemcachedCache(BaseCache):
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
return self._cache.add(key, value, self.get_backend_timeout(timeout))
def get(self, key, default=None, version=None):
key = self.make_key(key... | class BaseMemcachedCache(BaseCache):
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
return self._cache.add(key, value, self.get_backend_timeout(timeout))
def get(self, key, default=None, version=None):
... |
class BaseMemcachedCache(BaseCache):
def incr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.decr(key, -delta) | class BaseMemcachedCache(BaseCache):
def incr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.decr(key, -delta) |
class BaseMemcachedCache(BaseCache):
def decr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.incr(key, -delta) | class BaseMemcachedCache(BaseCache):
def decr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.incr(key, -delta) |
class BaseMemcachedCache(BaseCache):
original_keys = {}
for key, value in data.items():
safe_key = self.make_key(key, version=version)
safe_data[safe_key] = value
original_keys[safe_key] = key
failed_keys = self._cache.set_multi(safe_data, self.get_backend_tim... | class BaseMemcachedCache(BaseCache):
original_keys = {}
for key, value in data.items():
safe_key = self.make_key(key, version=version)
self.validate_key(safe_key)
safe_data[safe_key] = value
original_keys[safe_key] = key
failed_keys = self._cache.s... |
class BaseMemcachedCache(BaseCache):
def clear(self):
self._cache.flush_all()
class MemcachedCache(BaseMemcachedCache):
"An implementation of a cache binding using python-memcached" | class BaseMemcachedCache(BaseCache):
def clear(self):
self._cache.flush_all()
def validate_key(self, key):
for warning in memcache_key_warnings(key):
raise InvalidCacheKey(warning)
class MemcachedCache(BaseMemcachedCache):
"An implementation of a cache binding using python-mem... |
from unittest import mock
from django.conf import settings
from django.core import management, signals
from django.core.cache import (
DEFAULT_CACHE_ALIAS, CacheKeyWarning, cache, caches,
)
from django.core.cache.backends.base import InvalidCacheBackendError
from django.core.cache.utils import make_template_fragmen... | from unittest import mock
from django.conf import settings
from django.core import management, signals
from django.core.cache import (
DEFAULT_CACHE_ALIAS, CacheKeyWarning, InvalidCacheKey, cache, caches,
)
from django.core.cache.backends.base import InvalidCacheBackendError
from django.core.cache.utils import make... |
class BaseCacheTests:
def _perform_invalid_key_test(self, key, expected_warning):
"""
All the builtin backends (except memcached, see below) should warn on
keys that would be refused by memcached. This encourages portable
caching code without making it too difficult to use productio... | class BaseCacheTests:
def _perform_invalid_key_test(self, key, expected_warning):
"""
All the builtin backends should warn (except memcached that should
error) on keys that would be refused by memcached. This encourages
portable caching code without making it too difficult to use pr... |
class BaseMemcachedTests(BaseCacheTests):
with self.settings(CACHES={'default': params}):
self.assertEqual(cache._servers, ['server1.tld', 'server2:11211'])
def test_invalid_key_characters(self):
"""
On memcached, we don't introduce a duplicate key validation
... | class BaseMemcachedTests(BaseCacheTests):
with self.settings(CACHES={'default': params}):
self.assertEqual(cache._servers, ['server1.tld', 'server2:11211'])
def _perform_invalid_key_test(self, key, expected_warning):
"""
Whilst other backends merely warn, memcach... |
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, |
ssl = None
import sys
import tempfile
from nturl2path import url2pathname, pathname2url
from base64 import b64encode | ssl = None
import sys
import tempfile
import warnings
from nturl2path import url2pathname, pathname2url
from base64 import b64encode |
def open_spam(self, url):
"spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
"//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
# Just commented them out.
# Can't really tell why keep failing in windows and sparc.
# Everywhere else they work ok, but on those machines, sometimes | def open_spam(self, url):
"spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
"//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
def test_local_file_open(self):
# bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme
class DummyURLopener(urllib.request.URLopener):
... |
def open(self, fullurl, data=None):
name = 'open_' + urltype
self.type = urltype
name = name.replace('-', '_')
if not hasattr(self, name):
if proxy:
return self.open_unknown_proxy(proxy, fullurl, data)
else: | def open(self, fullurl, data=None):
name = 'open_' + urltype
self.type = urltype
name = name.replace('-', '_')
if not hasattr(self, name) or name == 'open_local_file':
if proxy:
return self.open_unknown_proxy(proxy, fullurl, data)
else: |
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum, Flag
from functools import partial, wraps
import keyword
import logging
from multiprocessing import Manager | from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum, Flag
from functools import partial, wraps
import io
import keyword
import logging
from multiprocessing import Manager |
def format_file_in_place(
"""
if src.suffix == ".pyi":
mode |= FileMode.PYI
with tokenize.open(src) as src_buffer:
src_contents = src_buffer.read()
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast, mode=mode | def format_file_in_place(
"""
if src.suffix == ".pyi":
mode |= FileMode.PYI
with open(src, "rb") as buf:
newline, encoding, src_contents = prepare_input(buf.read())
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast, mode=mode |
def format_file_in_place(
return False
if write_back == write_back.YES:
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)" | def format_file_in_place(
return False
if write_back == write_back.YES:
with open(src, "w", encoding=encoding, newline=newline) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)" |
def format_file_in_place(
if lock:
lock.acquire()
try:
sys.stdout.write(diff_contents)
finally:
if lock:
lock.release() | def format_file_in_place(
if lock:
lock.acquire()
try:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(diff_contents)
f.d... |
def format_stdin_to_stdout(
`line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
:func:`format_file_contents`.
"""
src = sys.stdin.read()
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode) | def format_stdin_to_stdout(
`line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
:func:`format_file_contents`.
"""
newline, encoding, src = prepare_input(sys.stdin.buffer.read())
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast, mode=... |
def format_stdin_to_stdout(
finally:
if write_back == WriteBack.YES:
sys.stdout.write(dst)
elif write_back == WriteBack.DIFF:
src_name = "<stdin> (original)"
dst_name = "<stdin> (formatted)"
sys.stdout.write(diff(src, dst, src_name, dst_name))
def... | def format_stdin_to_stdout(
finally:
if write_back == WriteBack.YES:
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f.write(dst)
f.detach()
... |
def format_str(
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement, | def format_str(
return dst_contents
def prepare_input(src: bytes) -> Tuple[str, str, str]:
"""Analyze `src` and return a tuple of (newline, encoding, decoded_contents)
Where `newline` is either CRLF or LF, and `decoded_contents` is decoded with
universal newlines (i.e. only LF).
"""
srcbuf = ... |
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
src_txt += nl
for grammar in GRAMMARS:
drv = driver.Dri... | def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
src_txt += "\n"
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert)
try: |
import asyncio
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import partial
from io import StringIO
import os
from pathlib import Path
import sys | import asyncio
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import partial
from io import BytesIO, TextIOWrapper
import os
from pathlib import Path
import sys |
class BlackTestCase(unittest.TestCase):
source, expected = read_data("../black")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin, sys.stdout = StringIO(source), StringIO()
sys.stdin.name = "<stdin>"
black.format_stdin_to_stdout(
... | class BlackTestCase(unittest.TestCase):
source, expected = read_data("../black")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8")
sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8")
... |
class BlackTestCase(unittest.TestCase):
expected, _ = read_data("expression.diff")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin, sys.stdout = StringIO(source), StringIO()
sys.stdin.name = "<stdin>"
black.format_stdin_to_stdout(
... | class BlackTestCase(unittest.TestCase):
expected, _ = read_data("expression.diff")
hold_stdin, hold_stdout = sys.stdin, sys.stdout
try:
sys.stdin = TextIOWrapper(BytesIO(source.encode("utf8")), encoding="utf8")
sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8")
... |
class BlackTestCase(unittest.TestCase):
tmp_file = Path(black.dump_to_file(source))
hold_stdout = sys.stdout
try:
sys.stdout = StringIO()
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
actual = sys.stdout.read() | class BlackTestCase(unittest.TestCase):
tmp_file = Path(black.dump_to_file(source))
hold_stdout = sys.stdout
try:
sys.stdout = TextIOWrapper(BytesIO(), encoding="utf8")
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF))
sys.stdout.seek(0)
... |
class BlackTestCase(unittest.TestCase):
result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"])
self.assertEqual(result.exit_code, 2)
if __name__ == "__main__":
unittest.main() | class BlackTestCase(unittest.TestCase):
result = CliRunner().invoke(black.main, ["-", option, "**()(!!*)"])
self.assertEqual(result.exit_code, 2)
def test_preserves_line_endings(self) -> None:
with TemporaryDirectory() as workspace:
test_file = Path(workspace) / "test.py... |
class EmptyLineTracker:
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before -= self.previous_after
self.previous_after = after
self.previous_line = current_line
return before, after | class EmptyLineTracker:
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before = (
# Black should not insert empty lines at the beginning
# of the file
0
if self.previous_line is None
else ... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
def test_tab_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n ... | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_beginning_backslash(self) -> None:
source, expected = read_data("beginning_backslash")
actu... |
async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match]
text = self.clean_input(text)
# Make sure it's not a URL
if URL_RE.search(text):
return False, None
watchlist_patterns = self._get_filterlist_items('filter_token', allowed=False)
for p... | async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match]
text = self.clean_input(text)
watchlist_patterns = self._get_filterlist_items('filter_token', allowed=False)
for pattern in watchlist_patterns:
match = re.search(pattern, text, flags=re.IGNORECASE) |
class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
] | class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN RSA PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
] |
class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256) | class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN RSA PUBLIC KEY-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):... |
from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models.aggregates import Aggregate
from django.utils.functional import cached_property
| from django.contrib.gis.db.models.fields import (
ExtentField, GeometryCollectionField, GeometryField, LineStringField,
)
from django.db.models import Value
from django.db.models.aggregates import Aggregate
from django.utils.functional import cached_property
|
class GeoAggregate(Aggregate):
)
def as_oracle(self, compiler, connection, **extra_context):
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))'
return self.as_s... | class GeoAggregate(Aggregate):
)
def as_oracle(self, compiler, connection, **extra_context):
if not self.is_extent:
tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)
clone = self.copy()
clone.set_source_expressions([
*sel... |
class OracleToleranceMixin:
tolerance = 0.05
def as_oracle(self, compiler, connection, **extra_context):
tol = self.extra.get('tolerance', self.tolerance)
return self.as_sql(
compiler, connection,
template="%%(function)s(%%(expressions)s, %s)" % tol,
**extra_... | class OracleToleranceMixin:
tolerance = 0.05
def as_oracle(self, compiler, connection, **extra_context):
tolerance = Value(self._handle_param(
self.extra.get('tolerance', self.tolerance),
'tolerance',
NUMERIC_TYPES,
))
clone = self.copy()
clon... |
class DistanceFunctionsTests(FuncTestMixin, TestCase):
).filter(d=D(m=1))
self.assertTrue(qs.exists())
@skipIfDBFeature("supports_distance_geodetic")
@skipUnlessDBFeature("has_Distance_function")
def test_distance_function_raw_result_d_lookup(self): | class DistanceFunctionsTests(FuncTestMixin, TestCase):
).filter(d=D(m=1))
self.assertTrue(qs.exists())
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_distance_function_tolerance_escaping(self):
qs = Interstate.... |
import tempfile
from io import StringIO
from django.contrib.gis import gdal | import tempfile
import unittest
from io import StringIO
from django.contrib.gis import gdal |
from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import NotSupportedError, connection
from django.test import TestCase, skipUnlessDBFeature
from ..utils import ( | from django.contrib.gis.geos import (
MultiPoint, MultiPolygon, Point, Polygon, fromstr,
)
from django.core.management import call_command
from django.db import DatabaseError, NotSupportedError, connection
from django.test import TestCase, skipUnlessDBFeature
from ..utils import ( |
class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
def test_within_subquery(self):
"""
Using a queryset inside a geo lookup is working (using a subquery) | class GeoQuerySetTest(TestCase):
qs = City.objects.filter(name='NotACity')
self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
@unittest.skipUnless(
connection.vendor == 'oracle',
'Oracle supports tolerance paremeter.',
)
def test_unionagg_tolerance(self):
... |
class Scheduler(object):
for batch_task in self._state.get_batch_running_tasks(task.batch_id):
batch_task.expl = expl
if not (task.status in (RUNNING, BATCH_RUNNING) and status == PENDING) or new_deps:
# don't allow re-scheduling of task while it is running, it m... | class Scheduler(object):
for batch_task in self._state.get_batch_running_tasks(task.batch_id):
batch_task.expl = expl
if not (task.status in (RUNNING, BATCH_RUNNING) and (status not in (DONE, FAILED, RUNNING) or task.worker_running != worker_id)) or new_deps:
# d... |
class SchedulerApiTest(unittest.TestCase):
self.assertEqual(self.sch.get_work(worker='Y')['task_id'], 'C')
self.assertEqual(self.sch.get_work(worker='X')['task_id'], 'B')
def test_retry(self):
# Try to build A but fails, will retry after 100s
self.setTime(0) | class SchedulerApiTest(unittest.TestCase):
self.assertEqual(self.sch.get_work(worker='Y')['task_id'], 'C')
self.assertEqual(self.sch.get_work(worker='X')['task_id'], 'B')
def test_status_wont_override(self):
# Worker X is running A
# Worker Y wants to override the status to UNKNOWN ... |
from absl.testing import parameterized
import numpy as np
from tensorflow.python.dlpack import dlpack
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.platform import test
from tensorflow.python.ops imp... | from absl.testing import parameterized
import numpy as np
from tensorflow.python.dlpack import dlpack
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.pla... |
def UnsupportedComplex64():
self.assertRaisesRegex(Exception, ".* is not supported by dlpack",
UnsupportedComplex64)
if __name__ == "__main__":
ops.enable_eager_execution() | def UnsupportedComplex64():
self.assertRaisesRegex(Exception, ".* is not supported by dlpack",
UnsupportedComplex64)
def testMustPassTensorArgumentToDLPack(self):
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"The argument to `to_dlpack` must be a TF ten... |
import logging
import salt.utils.files
import salt.utils.path
import salt.payload
from salt.ext import six | import logging
import salt.utils.files
import salt.utils.path
import salt.utils.verify
import salt.payload
from salt.ext import six |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not salt.utils.verify.clean_path(opts['token_dir'], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
log = logging.getLogger(__name__)
| import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
import salt.ext.six
log = logging.getLogger(__name__)
|
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ''
for part in path.split(os.path.sep)[1:]:
if base != '':
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
... | def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(
yaml_contents,
default_flow_style=False,
)
if not os.... |
def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_: | def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['file_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.p... | def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
root = __opts__['file_roots'][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_p... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created' | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created'
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config('master')
self.conf_dir... |
class BadTestModuleNamesTestCase(TestCase):
'integration.logging.test_jid_logging',
'integration.logging.handlers.test_logstash_mod',
'integration.master.test_event_return',
'integration.minion.test_blackout',
'integration.minion.test_executor',
'i... | class BadTestModuleNamesTestCase(TestCase):
'integration.logging.test_jid_logging',
'integration.logging.handlers.test_logstash_mod',
'integration.master.test_event_return',
'integration.master.test_clear_funcs',
'integration.minion.test_blackout',
... |
import stat
import shutil
import tempfile
import socket
# Import third party libs
if sys.platform.startswith('win'): | import stat
import shutil
import tempfile
import socket
import ctypes
# Import third party libs
if sys.platform.startswith('win'): |
from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
)
# Import 3rd-party libs | from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
clean_path
)
# Import 3rd-party libs |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
'''
salt.utils.clean_path works as expected
'''
def setUp(self):
self.tmpdir = tempfile... |
ReferenceError: conole is not defined
@pytest.mark.parametrize('test', tests)
def test_match(monkeypatch, test):
monkeypatch.setenv('EDITOR', 'dummy_editor')
assert match(Command(stderr=test[4]), None)
@pytest.mark.parametrize('test', tests)
def test_not_match(monkeypatch, test):
if 'EDITOR' in os.envir... | ReferenceError: conole is not defined
@pytest.mark.parametrize('test', tests)
def test_match(mocker, monkeypatch, test):
mocker.patch('os.path.isfile', return_value=True)
monkeypatch.setenv('EDITOR', 'dummy_editor')
assert match(Command(stderr=test[4]), None)
@pytest.mark.parametrize('test', tests)
def ... |
def _search(stderr):
def match(command, settings):
return 'EDITOR' in os.environ and _search(command.stderr)
def get_new_command(command, settings): | def _search(stderr):
def match(command, settings):
if 'EDITOR' not in os.environ:
return False
m = _search(command.stderr)
return m and os.path.isfile(m.group('file'))
def get_new_command(command, settings): |
class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
return multi_join_idx, lidx, ridx
jl = list(overlap)[0]
| class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
if return_indexers:
return multi_join_idx, lidx, ridx
else:
return multi_join_idx
jl = list(overlap)[0]
|
def test_join_multi_wrong_order():
midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])
midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])
join_idx, lidx, ridx = midx1.join(midx2, return_indexers=False)
exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)
tm.... | def test_join_multi_wrong_order():
midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])
midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])
join_idx, lidx, ridx = midx1.join(midx2, return_indexers=True)
exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)
tm.a... |
class MetricsHandler(tornado.web.RequestHandler):
self._scheduler = scheduler
def get(self):
metrics = self._scheduler._state._metrics_collector.generate_latest()
if metrics:
metrics.configure_http_handler(self)
self.write(metrics)
| class MetricsHandler(tornado.web.RequestHandler):
self._scheduler = scheduler
def get(self):
metrics_collector = self._scheduler._state._metrics_collector
metrics = metrics_collector.generate_latest()
if metrics:
metrics_collector.configure_http_handler(self)
... |
class MetricsHandlerTest(unittest.TestCase):
with mock.patch.object(self.handler, 'write') as patched_write:
self.handler.get()
patched_write.assert_called_once_with(mock_metrics)
mock_metrics.configure_http_handler.assert_called_once_with(self.handler)
def test_get_no_m... | class MetricsHandlerTest(unittest.TestCase):
with mock.patch.object(self.handler, 'write') as patched_write:
self.handler.get()
patched_write.assert_called_once_with(mock_metrics)
self.mock_scheduler._state._metrics_collector.configure_http_handler.assert_called_once_with(
... |
def test_urlsplit_normalization(self):
urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')
for scheme in ["http", "https", "ftp"]:
for c in denorm_chars:
url = "{}://netloc{}false.netloc/path".format(scheme, c)
with self.subTest(url=url, char='{:04X}'.fo... | def test_urlsplit_normalization(self):
urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')
for scheme in ["http", "https", "ftp"]:
for netloc in ["netloc{}false.netloc", "n{}user@netloc"]:
for c in denorm_chars:
url = "{}://{}/path".format(scheme, ne... |
def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.rpartition('@')[2] # ignore anything to the left of '@'
n = n.replace(':', '') # ignore characters already included
n... | def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.replace('@', '') # ignore characters already included
n = n.replace(':', '') # but not the surrounding text
n = n.r... |
def test_partial(self):
)
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode,
b"\xff", "strict", True)
def test_nonbmp(self):
self.assertEqual("\U00010203".encode(self.encoding), | def test_partial(self):
)
def test_errors(self):
tests = [
(b'\xff', '\ufffd'),
(b'A\x00Z', 'A\ufffd'),
(b'A\x00B\x00C\x00D\x00Z', 'ABCD\ufffd'),
(b'\x00\xd8', '\ufffd'),
(b'\x00\xd8A', '\ufffd'),
(b'\x00\xd8A\x00', '\ufffdA'),... |
def test_partial(self):
)
def test_errors(self):
self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode,
b"\xff", "strict", True)
def test_nonbmp(self):
self.assertEqual("\U00010203".encode(self.encoding), | def test_partial(self):
)
def test_errors(self):
tests = [
(b'\xff', '\ufffd'),
(b'\x00A\xff', 'A\ufffd'),
(b'\x00A\x00B\x00C\x00DZ', 'ABCD\ufffd'),
(b'\xd8\x00', '\ufffd'),
(b'\xd8\x00\xdc', '\ufffd'),
(b'\xd8\x00\x00A', '\uff... |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
res._is_copy = self._is_copy
return res
def _iget_item_cache(self, item):
"""Return the cached item, item represents a positional indexer."""
ax = self._info_axis
if ax.is_unique:
lower = se... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
res._is_copy = self._is_copy
return res
def _iget_item_cache(self, item: int):
"""Return the cached item, item represents a positional indexer."""
ax = self._info_axis
if ax.is_unique:
lower... |
class _iLocIndexer(_LocationIndexer):
if not is_integer(k):
return False
ax = self.obj.axes[i]
if not ax.is_unique:
return False
return True
def _validate_integer(self, key: int, axis: int) -> None: | class _iLocIndexer(_LocationIndexer):
if not is_integer(k):
return False
return True
def _validate_integer(self, key: int, axis: int) -> None: |
class TestiLoc(Base):
class TestiLoc2:
# TODO: better name, just separating out things that dont rely on base class
def test_iloc_exceeds_bounds(self):
# GH6296 | class TestiLoc(Base):
class TestiLoc2:
# TODO: better name, just separating out things that dont rely on base class
def test_is_scalar_access(self):
# GH#32085 index with duplicates doesnt matter for _is_scalar_access
index = pd.Index([1, 2, 1])
ser = pd.Series(range(3), index=index)
... |
def SHA244(self,data:str):
hash = str(sha.digest())
return self.__Salt(hash,salt=self.salt)
def MD5(self,data:str):
sha = hashlib.md5(bytes(data.encode()))
hash = str(sha.digest())
return self.__Salt(hash,salt=self.salt)
def SHA384(self,data:str):
sha = hashlib.... | def SHA244(self,data:str):
hash = str(sha.digest())
return self.__Salt(hash,salt=self.salt)
def SHA384(self,data:str):
sha = hashlib.sha384(bytes(data.encode()))
hash = str(sha.digest()) |
class _Rolling_and_Expanding(_Rolling):
raise ValueError("engine must be either 'numba' or 'cython'")
# TODO: Why do we always pass center=False?
# name=func for WindowGroupByMixin._apply
return self._apply(
apply_func,
center=False,
floor=0,
... | class _Rolling_and_Expanding(_Rolling):
raise ValueError("engine must be either 'numba' or 'cython'")
# TODO: Why do we always pass center=False?
# name=func & raw=raw for WindowGroupByMixin._apply
return self._apply(
apply_func,
center=False,
flo... |
class TestGrouperGrouping:
result = r.apply(lambda x: x.sum(), raw=raw)
expected = g.apply(lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw))
tm.assert_frame_equal(result, expected) | class TestGrouperGrouping:
result = r.apply(lambda x: x.sum(), raw=raw)
expected = g.apply(lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw))
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("expected_value,raw_value", [[1.0, True], [0.0, False]])
def test_groupb... |
class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
raise ValueError(
"Cannot specify `categories` or `ordered` together with `dtype`."
)
elif is_categorical(values):
# If no "dtype" was passed, use the one from "values", but honor
... | class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
raise ValueError(
"Cannot specify `categories` or `ordered` together with `dtype`."
)
elif not isinstance(dtype, CategoricalDtype):
raise ValueError(f"Cannot not construct Catego... |
class TestCategoricalDtype(Base):
with pytest.raises(ValueError, match=msg):
CategoricalDtype._from_values_or_dtype(values, categories, ordered, dtype)
def test_is_dtype(self, dtype):
assert CategoricalDtype.is_dtype(dtype)
assert CategoricalDtype.is_dtype("category") | class TestCategoricalDtype(Base):
with pytest.raises(ValueError, match=msg):
CategoricalDtype._from_values_or_dtype(values, categories, ordered, dtype)
def test_from_values_or_dtype_invalid_dtype(self):
msg = "Cannot not construct CategoricalDtype from <class 'object'>"
with pyt... |
class Base:
assert not indices.equals(np.array(indices))
# Cannot pass in non-int64 dtype to RangeIndex
if not isinstance(indices, RangeIndex):
same_values = Index(indices, dtype=object)
assert indices.equals(same_values)
assert same_values.equals(indices) | class Base:
assert not indices.equals(np.array(indices))
# Cannot pass in non-int64 dtype to RangeIndex
if not isinstance(indices, (RangeIndex, CategoricalIndex)):
# TODO: CategoricalIndex can be re-allowed following GH#32167
same_values = Index(indices, dtype=object)
... |
class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.reindex_like(data)
if freq is None:
mask = isna(com.values_from_object(data)... | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
if freq is None:
... |
class TestTimeSeries:
rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled)
)
def test_pct_change_shift_over_nas(self):
s = Series([1.0, 1.5, np.nan, 2.5, 3.0])
| class TestTimeSeries:
rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled)
)
def test_pct_change_with_duplicate_axis(self):
# GH 28664
common_idx = date_range("2019-11-14", periods=5, freq="D")
result = Series(range(5), common_idx).pct_change(freq="B")
... |
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... |
options:
name:
description:
- Zone name.
required: true
path:
description: | options:
name:
description:
- Zone name.
- A zone name must be unique name.
- A zone name must begin with an alpha-numeric character.
- The name can contain alpha-numeric characters, underbars I(_), hyphens I(-), and periods I(.).
- The name cannot be longer than 64 characters.
t... |
EXAMPLES = '''
import os
import platform
import tempfile
import time
| EXAMPLES = '''
import os
import platform
import re
import tempfile
import time
|
class Zone(object):
if int(self.os_minor) < 10:
self.module.fail_json(msg='This module requires Solaris 10 or later')
def configure(self):
if not self.path:
self.module.fail_json(msg='Missing required argument: path') | class Zone(object):
if int(self.os_minor) < 10:
self.module.fail_json(msg='This module requires Solaris 10 or later')
match = re.match('^[a-zA-Z0-9][-_.a-zA-Z0-9]{0,62}$', self.name)
if not match:
self.module.fail_json(msg="Provided zone name is not a valid zone name. "
... |
def get_catalog(self, user_id, tenant_id, metadata=None):
class ServiceController(wsgi.Application):
def __init__(self):
self.catalog_api = Manager()
super(ServiceController, self).__init__()
# CRUD extensions
# NOTE(termie): this OS-KSADM stuff is not very consistent
def get_services(s... | def get_catalog(self, user_id, tenant_id, metadata=None):
class ServiceController(wsgi.Application):
def __init__(self):
self.catalog_api = Manager()
self.identity_api = identity.Manager()
self.policy_api = policy.Manager()
self.token_api = token.Manager()
super(ServiceContro... |
import httplib
import json
from lxml import etree
import nose.exc |
import httplib
import json
import uuid
from lxml import etree
import nose.exc |
def assertValidMultipleChoiceResponse(self, r):
def assertValidVersionResponse(self, r):
self.assertValidVersion(r.body.get('version'))
class XmlTestCase(RestfulTestCase, CoreApiTests):
xmlns = 'http://docs.openstack.org/identity/api/v2.0' | def assertValidMultipleChoiceResponse(self, r):
def assertValidVersionResponse(self, r):
self.assertValidVersion(r.body.get('version'))
def test_service_crud_requires_auth(self):
"""Service CRUD should 401 without an X-Auth-Token (bug 1006822)."""
# values here don't matter because we s... |
class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(ticklabels)
if name is not None and self.use_index:
ax.set_xlabel(name)
| class BarPlot(MPLPlot):
def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge):
ax.set_xlim((start_edge, end_edge))
if self.xticks is not None:
ax.set_xticks(np.array(self.xticks))
else:
ax.set_xticks(self.tick_pos)
ax.set_xticklabels(tick... |
class TestSeriesPlots(TestPlotBase):
exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]]
self._check_text_labels(ax.get_xticklabels(), exp)
def test_custom_business_day_freq(self):
# GH7222
from pandas.tseries.offsets import CustomBusinessDay | class TestSeriesPlots(TestPlotBase):
exp = ["P{i:02d}".format(i=i) for i in [0, 3, 5, 9]]
self._check_text_labels(ax.get_xticklabels(), exp)
def test_xtick_barPlot(self):
# GH28172
s = pd.Series(range(10), index=["P{i:02d}".format(i=i) for i in range(10)])
ax = s.plot.bar(xt... |
def makecmdoptions(self):
def __str__(self):
return "<SvnAuth username=%s ...>" %(self.username,)
rex_blame = re.compile(r'\s*(\d+)\s*(\S+) (.*)')
class SvnWCCommandPath(common.PathBase):
""" path implementation offering access/modification to svn working copies. | def makecmdoptions(self):
def __str__(self):
return "<SvnAuth username=%s ...>" %(self.username,)
rex_blame = re.compile(r'\s*(\d+)\s+(\S+) (.*)')
class SvnWCCommandPath(common.PathBase):
""" path implementation offering access/modification to svn working copies. |
def capfirst(x):
# Set up regular expressions
re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', 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... | 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(
t... |
class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…')
def test_truncate_words(self):
truncator = text.Truncator('The quick brown fox jumped over the lazy dog.')
self.assertEq... | class TestUtilsText(SimpleTestCase):
# lazy strings are handled correctly
self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(10), 'The quick…')
def test_truncate_chars_html(self):
perf_test_values = [
(('</a' + '\t' * 50000) + '//>', None),
('&' * ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.