buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def authenticate(username, password): """ service = __opts__.get("auth.pam.service", "login") if isinstance(username, six.text_type): username = username.encode(__salt_system_encoding__) if isinstance(password, six.text_type): password = password.encode(__salt_system_encoding__) if ...
def authenticate(username, password): """ service = __opts__.get("auth.pam.service", "login") if isinstance(username, str): username = username.encode(__salt_system_encoding__) if isinstance(password, str): password = password.encode(__salt_system_encoding__) if isinstance(service, ...
def authenticate(username, password): retval = PAM_AUTHENTICATE(handle, 0) if retval == 0: PAM_ACCT_MGMT(handle, 0) PAM_END(handle, 0) return retval == 0
def authenticate(username, password): retval = PAM_AUTHENTICATE(handle, 0) if retval == 0: retval = PAM_ACCT_MGMT(handle, 0) PAM_END(handle, 0) return retval == 0
import salt.utils.json import salt.utils.stringutils import salt.utils.url import salt.utils.yaml from jinja2 import BaseLoader, Markup, TemplateNotFound, nodes from jinja2.environment import TemplateModule from jinja2.exceptions import TemplateRuntimeError from jinja2.ext import Extension
import salt.utils.json import salt.utils.stringutils import salt.utils.url import salt.utils.yaml from jinja2 import BaseLoader, TemplateNotFound, nodes from jinja2.environment import TemplateModule from jinja2.exceptions import TemplateRuntimeError from jinja2.ext import Extension
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test from salt.utils.odict import OrderedDict from salt.utils.versions import LooseVersion log = logging.getLogger(__name__) __all__ = ["SaltCacheLoader", "SerializerExtension"]
from salt.utils.decorators.jinja import jinja_filter, jinja_global, jinja_test from salt.utils.odict import OrderedDict from salt.utils.versions import LooseVersion try: from markupsafe import Markup except ImportError: # jinja < 3.1 from jinja2 import Markup log = logging.getLogger(__name__) __all__ = [...
def method_call(obj, f_name, *f_args, **f_kwargs): return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs) @jinja2.contextfunction def show_full_context(ctx): return salt.utils.data.simple_types_filter( {key: value for key, value in ctx.items()}
def method_call(obj, f_name, *f_args, **f_kwargs): return getattr(obj, f_name, lambda *args, **kwargs: None)(*f_args, **f_kwargs) try: contextfunction = jinja2.contextfunction except AttributeError: contextfunction = jinja2.pass_context @contextfunction def show_full_context(ctx): return salt.utils....
def stderr(branch_name): def new_command(branch_name): return [cmd.format(branch_name) for cmd in [ 'git branch -d {0} && git branch {0}', 'git branch -D {0} && git branch {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, branch_name', [ ('git branch foo', 'foo'), ('git branch b...
def stderr(branch_name): def new_command(branch_name): return [cmd.format(branch_name) for cmd in [ 'git branch -d {0} && git branch {0}', 'git branch -d {0} && git checkout -b {0}', 'git branch -D {0} && git branch {0}', 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}'...
from thefuck.utils import eager @git_support def match(command): return ('branch' in command.script and "fatal: A branch named '" in command.stderr and " already exists." in command.stderr)
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.stderr and " already exists." in command.stderr)
def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0] new_command_templates = [['git branch -d {0}', 'git branch {0}'], ['git branch -D {0}', 'git branch {0}'], ['git checko...
def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", command.stderr)[0] new_command_templates = [['git branch -d {0}', 'git branch {0}'], ['git branch -d {0}', 'git checkout -b {0}'], ['git b...
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). type: bool default: 'no'
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). - This setting affects packages installed from a repository as well as "local" packages installed from the filesystem or a URL. ...
class DnfModule(YumDnf): results=[], ) if self.download_only: for package in self.base.transaction.install_set: response['results'].append("Downloaded: {0}".format(package))
class DnfModule(YumDnf): results=[], ) # Validate GPG. This is NOT done in dnf.Base (it's done in the # upstream CLI subclass of dnf.Base) if not self.disable_gpg_check: for package in self.base.transaction....
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # There is no hostname validation when DEBUG=True if settings.DEBUG: return host domain, port = split_domain_port(host) if domain and ...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_disabled_in_debug_mode(self): """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass.""" request = HttpRequest() ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ ...
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): if is_object_dtype(dtype): return tslib.ints_to_pydatetime(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) # allow frequency conversions
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): if is_object_dtype(dtype): return tslib.ints_to_pydatetime(arr.view(np.int64)) elif dtype == np.int64: if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") ...
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): if is_object_dtype(dtype): return tslibs.ints_to_pytimedelta(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) if dtype not in [_INT64_DTYPE, _TD_DTYPE]:
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): if is_object_dtype(dtype): return tslibs.ints_to_pytimedelta(arr.view(np.int64)) elif dtype == np.int64: if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") ...
import pytest import pandas.util._test_decorators as td import pandas.core.dtypes.common as com from pandas.core.dtypes.dtypes import ( CategoricalDtype,
import pytest import pandas.util._test_decorators as td from pandas.core.dtypes.cast import astype_nansafe import pandas.core.dtypes.common as com from pandas.core.dtypes.dtypes import ( CategoricalDtype,
from pandas.core.dtypes.dtypes import ( IntervalDtype, PeriodDtype, ) import pandas as pd from pandas.conftest import (
from pandas.core.dtypes.dtypes import ( IntervalDtype, PeriodDtype, ) from pandas.core.dtypes.missing import isna import pandas as pd from pandas.conftest import (
def test__get_dtype_fails(input_param, expected_error_message): ) def test__is_dtype_type(input_param, result): assert com._is_dtype_type(input_param, lambda tipo: tipo == result)
def test__get_dtype_fails(input_param, expected_error_message): ) def test__is_dtype_type(input_param, result): assert com._is_dtype_type(input_param, lambda tipo: tipo == result) @pytest.mark.parametrize("val", [np.datetime64("NaT"), np.timedelta64("NaT")]) @pytest.mark.parametrize("typ", [np.int64]) def test_as...
from collections import namedtuple import re from ..exceptions import LocationParseError url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
from collections import namedtuple import re from ..exceptions import LocationParseError from ..packages.six.moves.urllib.parse import quote url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
def parse_url(url): # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 if _contains_disallowed_url_pchar_re.search(url): raise LocationParseError("URL can't contain control characters. {!r}".format(url)) scheme = None auth = None
def parse_url(url): # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 url = _contains_disallowed_url_pchar_re.sub(lambda match: quote(match.group()), url) scheme = None auth = None
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_parse_url_contains_control_characters(self): # see CVE-2019-9740 with pytest.raises(LocationParseError): parse_url('http://localhost:8000/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:') ...
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') @pytest.mark.parametrize('url, expected_url', [ ( 'http://localhost/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:', Url('http', host='localhost', port=None, path='/%20HTTP/1.1%0D...
class tqdm(object): # Format left/right sides of the bar, and format the bar # later in the remaining space (avoid breaking display) l_bar_user, r_bar_user = bar_format.split('{bar}') l_bar, r_bar = l_bar.format(**bar_args), r_bar.format(**...
class tqdm(object): # Format left/right sides of the bar, and format the bar # later in the remaining space (avoid breaking display) l_bar_user, r_bar_user = bar_format.split('{bar}') l_bar, r_bar = l_bar_user.format(**bar_args), r_bar_user...
def test_format_meter(): "100KiB [00:13, 7.69KiB/s]" assert format_meter(100, 1000, 12, ncols=0, rate=7.33) == \ " 10% 100/1000 [00:12<02:02, 7.33it/s]" assert format_meter(20, 100, 12, ncols=30, rate=8.1, bar_format=r'{l_bar}{bar}|{n_fmt}/{total_fmt}') == \ " 20...
def test_format_meter(): "100KiB [00:13, 7.69KiB/s]" assert format_meter(100, 1000, 12, ncols=0, rate=7.33) == \ " 10% 100/1000 [00:12<02:02, 7.33it/s]" # Check that bar_format correctly adapts {bar} size to the rest assert format_meter(20, 100, 12, ncols=13, rate=8.1, ...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode() except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_brok...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exceptio...
import datetime import unittest from unittest import mock from urllib.parse import quote_plus
import datetime import sys import unittest from unittest import mock from urllib.parse import quote_plus
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, smart_bytes, smart_text, uri_to_iri, ) from django.utils.functional import Simp...
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_text, uri_to_iri, ) from django.ut...
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested ...
def generate_context( context = OrderedDict([]) try: with open(context_file) as file_handle: obj = json.load(file_handle, object_pairs_hook=OrderedDict) except ValueError as e: # JSON decoding error. Let's throw a new exception that is more
def generate_context( context = OrderedDict([]) try: with open(context_file, encoding='utf-8') as file_handle: obj = json.load(file_handle, object_pairs_hook=OrderedDict) except ValueError as e: # JSON decoding error. Let's throw a new exception that is more
def test_default_context_replacement_in_generate_context(): assert generated_context == expected_context @pytest.fixture def template_context(): """Fixture. Populates template content for future tests."""
def test_default_context_replacement_in_generate_context(): assert generated_context == expected_context def test_generate_context_decodes_non_ascii_chars(): """Verify `generate_context` correctly decodes non-ascii chars.""" expected_context = {'non_ascii': OrderedDict([('full_name', 'éèà'),])} gener...
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('man read'), ['read --help', 'man 3 read', 'man 2 read']), (Command('man 2 read'), 'man 3 read'), (Command('man 3 read'), 'man 2 read'), (Command('man -s2 read'), 'man -s3 read'),
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('man read'), ['man 3 read', 'man 2 read', 'read --help']), (Command('man missing', stderr="No manual entry for missing\n"), ['missing --help']), (Command('man 2 read'), 'man 3 read'), (Command('man 3 read'), 'man ...
def get_new_command(command): if '2' in command.script: return command.script.replace("2", "3") split_cmd2 = command.script_parts split_cmd3 = split_cmd2[:] split_cmd2.insert(1, ' 2 ') split_cmd3.insert(1, ' 3 ') last_arg = command.script_parts[-1] return [ last_arg + ' -...
def get_new_command(command): if '2' in command.script: return command.script.replace("2", "3") last_arg = command.script_parts[-1] help_command = last_arg + ' --help' # If there are no man pages for last_arg, suggest `last_arg --help` instead. # Otherwise, suggest `--help` after suggestin...
pjoin = os.path.join # Constants #----------------------------------------------------------------------------- bundled_version = (4, 3, 1) vs = '%i.%i.%i' % bundled_version libzmq = "zeromq-%s.tar.gz" % vs libzmq_url = "https://github.com/zeromq/libzmq/releases/download/v{vs}/{libzmq}".format( vs=vs, libzmq=l...
pjoin = os.path.join # Constants #----------------------------------------------------------------------------- bundled_version = (4, 3, 2) vs = '%i.%i.%i' % bundled_version libzmq = "zeromq-%s.tar.gz" % vs libzmq_url = "https://github.com/zeromq/libzmq/releases/download/v{vs}/{libzmq}".format( vs=vs, libzmq=l...
class KerasRegressor(BaseWrapper): Predictions. """ kwargs = self.filter_sk_params(Sequential.predict, kwargs) return np.squeeze(self.model.predict(x, **kwargs)) def score(self, x, y, **kwargs): """Returns the mean loss on the given test data and labels.
class KerasRegressor(BaseWrapper): Predictions. """ kwargs = self.filter_sk_params(Sequential.predict, kwargs) return np.squeeze(self.model.predict(x, **kwargs), axis=-1) def score(self, x, y, **kwargs): """Returns the mean loss on the given test data and labels.
def assert_regression_works(reg): assert preds.shape == (num_test, ) if __name__ == '__main__': pytest.main([__file__])
def assert_regression_works(reg): assert preds.shape == (num_test, ) def test_regression_predict_shape_correct_num_test_0(): assert_regression_predict_shape_correct(num_test=0) def test_regression_predict_shape_correct_num_test_1(): assert_regression_predict_shape_correct(num_test=1) def assert_regres...
Make api awesomeness """ from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import inspect import os import salt.client import salt.client.ssh.client import salt.config import salt.exceptions # Import Salt libs
Make api awesomeness """ from __future__ import absolute_import, print_function, unicode_literals import copy # Import Python libs import inspect import logging import os import salt.auth import salt.client import salt.client.ssh.client import salt.config import salt.daemons.masterapi import salt.exceptions # Impor...
import salt.log # pylint: disable=W0611 import salt.runner import salt.syspaths import salt.utils.args import salt.wheel # Import third party libs from salt.ext import six class NetapiClient(object): """
import salt.log # pylint: disable=W0611 import salt.runner import salt.syspaths import salt.utils.args import salt.utils.minions import salt.wheel from salt.defaults import DEFAULT_TARGET_DELIM # Import third party libs from salt.ext import six log = logging.getLogger(__name__) class NetapiClient(object): """
class NetapiClient(object): def __init__(self, opts): self.opts = opts def _is_master_running(self): """
class NetapiClient(object): def __init__(self, opts): self.opts = opts self.loadauth = salt.auth.LoadAuth(opts) self.key = salt.daemons.masterapi.access_keys(self.opts) minopts = copy.deepcopy(self.opts) minopts["enable_ssh_minions"] = True self.ckminions = salt.util...
class NetapiClient(object): ipc_file = "workers.ipc" return os.path.exists(os.path.join(self.opts["sock_dir"], ipc_file)) def run(self, low): """ Execute the specified function in the specified client by passing the
class NetapiClient(object): ipc_file = "workers.ipc" return os.path.exists(os.path.join(self.opts["sock_dir"], ipc_file)) def _prep_auth_info(self, clear_load): sensitive_load_keys = [] key = None if "token" in clear_load: auth_type = "token" err_...
class NetapiClient(object): "Raw shell option not allowed." ) l_fun = getattr(self, low["client"]) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get("args", ()), **f_call.get("kwargs", {}))
class NetapiClient(object): "Raw shell option not allowed." ) if low["client"] == "ssh": self._authorize_ssh(low) l_fun = getattr(self, low["client"]) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get("args", ()), **f_call...
# encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import logging import os import time
# encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import copy import logging import os import time
import pytest import salt.config import salt.netapi import salt.utils.files from salt.exceptions import EauthAuthenticationError from tests.support.case import SSHCase from tests.support.helpers import ( SaveRequestsPostHandler, Webserver,
import pytest import salt.config import salt.netapi import salt.utils.files import salt.utils.platform import salt.utils.pycrypto from salt.exceptions import EauthAuthenticationError from tests.support.case import ModuleCase, SSHCase from tests.support.helpers import ( SaveRequestsPostHandler, Webserver,
class NetapiSSHClientTest(SSHCase): """ opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) self.netapi = salt.netapi.NetapiClient(opts) self.priv_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "key_test") self.rosters = os.path.join(RUNTIME_VARS.TMP_CONF_DIR)...
class NetapiSSHClientTest(SSHCase): """ opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) self.netapi = salt.netapi.NetapiClient(opts) self.priv_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "key_test") self.rosters = os.path.join(RUNTIME_VARS.TMP_CONF_DIR) ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "fun": "xx", "eauth": "xx", "ssh_priv": "aaa|id>{} #".format(path), } ret = self.netapi.run(low) self.assertFalse(os...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "ssh_priv": "aaa|id>{} #".format(path), "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password":...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", } ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "fun": "test.ping", "eauth": "auto", ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_options": ["|id>{} #".f...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_port": "hhhhh|id>{} #"....
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": "hhhhh|id>{} #, lol"...
import time import warnings from io import BytesIO from typing import AnyStr, Callable, Optional from urllib.parse import ( ParseResultBytes, unquote_to_bytes as unquote,
import time import warnings from io import BytesIO from typing import AnyStr, Callable, Optional, Tuple from urllib.parse import ( ParseResultBytes, unquote_to_bytes as unquote,
def toChunk(data): return (networkString(f"{len(data):x}"), b"\r\n", data, b"\r\n") def fromChunk(data): """ Convert chunk to string. @type data: C{bytes} @return: tuple of (result, remaining) - both C{bytes}.
def toChunk(data): return (networkString(f"{len(data):x}"), b"\r\n", data, b"\r\n") def _ishexdigits(b: bytes) -> bool: """ Is the string case-insensitively hexidecimal? It must be composed of one or more characters in the ranges a-f, A-F and 0-9. """ for c in b: if c not in b"012...
def fromChunk(data): byte string. """ prefix, rest = data.split(b"\r\n", 1) length = int(prefix, 16) if length < 0: raise ValueError("Chunk length must be >= 0, not %d" % (length,)) if rest[length : length + 2] != b"\r\n":
def fromChunk(data): byte string. """ prefix, rest = data.split(b"\r\n", 1) length = _hexint(prefix) if length < 0: raise ValueError("Chunk length must be >= 0, not %d" % (length,)) if rest[length : length + 2] != b"\r\n":
def noMoreData(self): maxChunkSizeLineLength = 1024 class _ChunkedTransferDecoder: """ Protocol for decoding I{chunked} Transfer-Encoding, as defined by RFC 7230,
def noMoreData(self): maxChunkSizeLineLength = 1024 _chunkExtChars = ( b"\t !\"#$%&'()*+,-./0123456789:;<=>?@" b"ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`" b"abcdefghijklmnopqrstuvwxyz{|}~" b"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" b"\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b...
def _dataReceived_CHUNK_LENGTH(self) -> bool: endOfLengthIndex = self._buffer.find(b";", 0, eolIndex) if endOfLengthIndex == -1: endOfLengthIndex = eolIndex try: length = int(self._buffer[0:endOfLengthIndex], 16) except ValueError: raise _MalformedChun...
def _dataReceived_CHUNK_LENGTH(self) -> bool: endOfLengthIndex = self._buffer.find(b";", 0, eolIndex) if endOfLengthIndex == -1: endOfLengthIndex = eolIndex rawLength = self._buffer[0:endOfLengthIndex] try: length = _hexint(rawLength) except ValueError: ...
def lineReceived(self, line): self.setRawMode() elif line[0] in b" \t": # Continuation of a multi line header. self.__header = self.__header + b"\n" + line # Regular header line. # Processing of header line is delayed to allow accumulating multi # ...
def lineReceived(self, line): self.setRawMode() elif line[0] in b" \t": # Continuation of a multi line header. self.__header += b" " + line.lstrip(b" \t") # Regular header line. # Processing of header line is delayed to allow accumulating multi # l...
def fail(): # Can this header determine the length? if header == b"content-length": try: length = int(data) except ValueError:
def fail(): # Can this header determine the length? if header == b"content-length": if not data.isdigit(): return fail() try: length = int(data) except ValueError:
def headerReceived(self, line): return False header = header.lower() data = data.strip() if not self._maybeChooseTransferDecoder(header, data): return False
def headerReceived(self, line): return False header = header.lower() data = data.strip(b" \t") if not self._maybeChooseTransferDecoder(header, data): return False
def test_extensions(self): p.dataReceived(b"3; x-foo=bar\r\nabc\r\n") self.assertEqual(L, [b"abc"]) def test_oversizedChunkSizeLine(self): """ L{_ChunkedTransferDecoder.dataReceived} raises
def test_extensions(self): p.dataReceived(b"3; x-foo=bar\r\nabc\r\n") self.assertEqual(L, [b"abc"]) def test_extensionsMalformed(self): """ L{_ChunkedTransferDecoder.dataReceived} raises L{_MalformedChunkedDataError} when the chunk extension fields contain invalid ch...
def test_malformedChunkSizeNegative(self): http._MalformedChunkedDataError, p.dataReceived, b"-3\r\nabc\r\n" ) def test_malformedChunkEnd(self): r""" L{_ChunkedTransferDecoder.dataReceived} raises
def test_malformedChunkSizeNegative(self): http._MalformedChunkedDataError, p.dataReceived, b"-3\r\nabc\r\n" ) def test_malformedChunkSizeHex(self): """ L{_ChunkedTransferDecoder.dataReceived} raises L{_MalformedChunkedDataError} when the chunk size is prefixed with ...
def testChunks(self): chunked = b"".join(http.toChunk(s)) self.assertEqual((s, b""), http.fromChunk(chunked)) self.assertRaises(ValueError, http.fromChunk, b"-5\r\nmalformed!\r\n") def testConcatenatedChunks(self): chunked = b"".join([b"".join(http.toChunk(t)) for t in self....
def testChunks(self): chunked = b"".join(http.toChunk(s)) self.assertEqual((s, b""), http.fromChunk(chunked)) self.assertRaises(ValueError, http.fromChunk, b"-5\r\nmalformed!\r\n") self.assertRaises(ValueError, http.fromChunk, b"0xa\r\nmalformed!\r\n") self.assertRaises(V...
def test_headersMultiline(self): Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is preserved. See RFC 7230 section ...
def test_headersMultiline(self): Line folded headers are handled by L{HTTPChannel} by replacing each fold with a single space by the time they are made available to the L{Request}. Any leading whitespace in the folded lines of the header value is replaced with a single space, per: ...
def process(self): ) self.assertEqual( request.requestHeaders.getRawHeaders(b"space"), [b"space space"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"spaces"), [b"spaces spaces spaces"], ) self.assertEqua...
def process(self): ) self.assertEqual( request.requestHeaders.getRawHeaders(b"space"), [b"space space"], ) self.assertEqual( request.requestHeaders.getRawHeaders(b"spaces"), [b"spaces spaces spaces"], ) self.assertEqual( ...
def test_duplicateContentLengths(self): ] ) def test_duplicateContentLengthsWithPipelinedRequests(self): """ Two pipelined requests, the first of which includes multiple
def test_duplicateContentLengths(self): ] ) def test_contentLengthMalformed(self): """ A request with a non-integer C{Content-Length} header fails with a 400 response without calling L{Request.process}. """ self.assertRequestRejected( [ ...
def test_sendHeaderSanitizesLinearWhitespace(self): transport.value().splitlines(), [b": ".join([sanitizedBytes, sanitizedBytes])], )
def test_sendHeaderSanitizesLinearWhitespace(self): transport.value().splitlines(), [b": ".join([sanitizedBytes, sanitizedBytes])], ) class HexHelperTests(unittest.SynchronousTestCase): """ Test the L{http._hexint} and L{http._ishexdigits} helper functions. """ ...
class DataFrame(NDFrame): " or if the Series has a name" ) if other.name is None: index = None else: # other must have the same index name as self, otherwise # index name will be reset index = In...
class DataFrame(NDFrame): " or if the Series has a name" ) index = Index([other.name], name=self.index.name) idx_diff = other.index.difference(self.columns) try: combined_columns = self.columns.append(idx_diff) except T...
class TestDataFrameConcatCommon: expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])}) tm.assert_frame_equal(result, expected) def test_update(self): df = DataFrame( [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]
class TestDataFrameConcatCommon: expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "timestamp", ["2019-07-19 07:04:57+0100", "2019-07-19 07:04:57"] ) def test_append_timestamps_aware_or_naive(self, tz_...
import hashlib import json import random import string import sys import tempfile
import hashlib import json import random import stat import string import sys import tempfile
def build(self): cache_file = os.path.join( tempfile.gettempdir(), "rply-%s-%s-%s.json" % (self.VERSION, self.cache_id, self.compute_grammar_hash(g)) ) table = None if os.path.exists(cache_file): with open(cache_file) as f: data = json...
def build(self): cache_file = os.path.join( tempfile.gettempdir(), "rply-%s-%s-%s-%s.json" % (self.VERSION, os.getuid(), self.cache_id, self.compute_grammar_hash(g)) ) table = None if os.path.exists(cache_file): with open(cache_file) as f: ...
from .common import ( is_unsigned_integer_dtype, pandas_dtype, ) from .dtypes import DatetimeTZDtype, ExtensionDtype, PeriodDtype from .generic import ( ABCDataFrame, ABCDatetimeArray,
from .common import ( is_unsigned_integer_dtype, pandas_dtype, ) from .dtypes import DatetimeTZDtype, ExtensionDtype, IntervalDtype, PeriodDtype from .generic import ( ABCDataFrame, ABCDatetimeArray,
def infer_dtype_from_scalar(val, pandas_dtype: bool = False): if lib.is_period(val): dtype = PeriodDtype(freq=val.freq) val = val.ordinal return dtype, val
def infer_dtype_from_scalar(val, pandas_dtype: bool = False): if lib.is_period(val): dtype = PeriodDtype(freq=val.freq) val = val.ordinal elif lib.is_interval(val): subtype = infer_dtype_from_scalar(val.left, pandas_dtype=True)[0] dtype = IntervalDtype(sub...
from pandas.core.dtypes.cast import ( ) from pandas.core.dtypes.common import is_dtype_equal from pandas import Categorical, Period, Series, Timedelta, Timestamp, date_range import pandas.util.testing as tm
from pandas.core.dtypes.cast import ( ) from pandas.core.dtypes.common import is_dtype_equal from pandas import ( Categorical, Interval, Period, Series, Timedelta, Timestamp, date_range, ) import pandas.util.testing as tm
def test_infer_from_scalar_tz(tz, pandas_dtype): assert val == exp_val def test_infer_dtype_from_scalar_errors(): msg = "invalid ndarray passed to infer_dtype_from_scalar"
def test_infer_from_scalar_tz(tz, pandas_dtype): assert val == exp_val @pytest.mark.parametrize( "left, right, subtype", [ (0, 1, "int64"), (0.0, 1.0, "float64"), (Timestamp(0), Timestamp(1), "datetime64[ns]"), (Timestamp(0, tz="UTC"), Timestamp(1, tz="UTC"), "datetime64[ns...
capfirst = allow_lazy(capfirst, six.text_type) # 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*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines ...
capfirst = allow_lazy(capfirst, six.text_type) # 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 r...
class TestUtilsText(SimpleTestCase): self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9')
class TestUtilsText(SimpleTestCase): self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>' truncator = text.Truncator(re_tag_catastrophic_test) self.assertEqual(re_tag_catastrophic_test, t...
# if greater than this, the number is in ms, if less than or equal it's in seconds # (in seconds this is 11th October 2603, in ms it's 20th August 1970) MS_WATERSHED = int(2e10) StrBytesIntFloat = Union[str, bytes, int, float]
# if greater than this, the number is in ms, if less than or equal it's in seconds # (in seconds this is 11th October 2603, in ms it's 20th August 1970) MS_WATERSHED = int(2e10) # slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 MAX_NUMBER = int(3e20) StrBytesIntFloat = Union[str, by...
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: while abs(seconds) > MS_WATERSHED: seconds /= 1000 dt = EPOCH + timedelta(seconds=seconds)
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: if seconds > MAX_NUMBER: return datetime.max elif seconds < -MAX_NUMBER: return datetime.min while abs(seconds) > MS_WATERSHED: seconds /...
def create_tz(minutes): (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns ], ) def test_date_parsing(value, result): if result == errors.DateError: with ...
def create_tz(minutes): (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns ('infinity', date(9999, 12, 31)), ('inf', date(9999, 12, 31)), (float('...
def test_time_parsing(value, result): (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21,...
def test_time_parsing(value, result): (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21,...
class Model(BaseModel): 'type': 'value_error.unicodedecode', 'msg': "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte", }
class Model(BaseModel): 'type': 'value_error.unicodedecode', 'msg': "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte", } def test_nan(): class Model(BaseModel): dt: datetime d: date with pytest.raises(ValidationError) as exc_info: Model(dt='n...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collection_tar, files_member_obj) ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) try: with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collectio...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name))) b_dest_filepath = os.path.join(b_dest, ...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name))) b_dest_filepath = os.path.abspath(os.pa...
__metaclass__ = type import json import os import pytest import tarfile import uuid
__metaclass__ = type import json import os import pytest import re import tarfile import uuid
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): os.path.isfile(output_file) def test_require_one_of_collections_requirements_with_both(): cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', 'namespace.collection', '-r', 'requirements.yml'])
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): os.path.isfile(output_file) def test_extract_tar_file_outside_dir(tmp_path_factory): filename = u'ÅÑŚÌβŁÈ' temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename))) tar_file = os.path.join(temp_dir, to_bytes('%s...
class BinGrouper(BaseGrouper): ngroups, ) @cache_readonly def result_index(self): if len(self.binlabels) != 0 and isna(self.binlabels[0]):
class BinGrouper(BaseGrouper): ngroups, ) @cache_readonly def recons_codes(self): # get unique result indices, and prepend 0 as groupby starts from the first return [np.r_[0, np.flatnonzero(self.bins[1:] != self.bins[:-1]) + 1]] @cache_readonly def result_index(self...
from itertools import product import numpy as np import pytest from pandas import DataFrame, MultiIndex, Series, date_range import pandas.util.testing as tm
from itertools import product import numpy as np import pytest from pandas import DataFrame, Grouper, MultiIndex, Series, date_range, to_datetime import pandas.util.testing as tm
def test_series_groupby_value_counts( # have to sort on index because of unstable sort on values left, right = map(rebuild_index, (left, right)) # xref GH9212 tm.assert_series_equal(left.sort_index(), right.sort_index())
def test_series_groupby_value_counts( # have to sort on index because of unstable sort on values left, right = map(rebuild_index, (left, right)) # xref GH9212 tm.assert_series_equal(left.sort_index(), right.sort_index()) def test_series_groupby_value_counts_with_grouper(): # GH28479 df = DataFram...
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('man read'), ['read --help', 'man 3 read', 'man 2 read']), (Command('man 2 read'), 'man 3 read'), (Command('man 3 read'), 'man 2 read'), (Command('man -s2 read'), 'man -s3 read'),
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('man read'), ['man 3 read', 'man 2 read', 'read --help']), (Command('man missing', stderr="No manual entry for missing\n"), ['missing --help']), (Command('man 2 read'), 'man 3 read'), (Command('man 3 read'), 'man ...
def get_new_command(command): if '2' in command.script: return command.script.replace("2", "3") split_cmd2 = command.script_parts split_cmd3 = split_cmd2[:] split_cmd2.insert(1, ' 2 ') split_cmd3.insert(1, ' 3 ') last_arg = command.script_parts[-1] return [ last_arg + ' -...
def get_new_command(command): if '2' in command.script: return command.script.replace("2", "3") last_arg = command.script_parts[-1] help_command = last_arg + ' --help' # If there are no man pages for last_arg, suggest `last_arg --help` instead. # Otherwise, suggest `--help` after suggestin...
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith('$') else self.regex.search(path) ) if match: # If there are any n...
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append('$') return ''.join(parts), converters
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append(r'\Z') return ''.join(parts), converters
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo/<nonexistent:var>/', empty_view) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls') class ConverterTests(SimpleTestCase):
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo/<nonexistent:var>/', empty_view) def test_path_trailing_newlines(self): tests = [ '/articles/2003/\n', '/articles/2010/\n', '/en/foo/\n', ...
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 str(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') @unittest.skipUnless(symlinks_supported(), 'Must be able to symlink to run this test.') def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied."""
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...
from django.contrib.gis.db.models.fields import ExtentField from django.db.models.aggregates import Aggregate __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union']
from django.contrib.gis.db.models.fields import ExtentField from django.db.models import Value from django.db.models.aggregates import Aggregate __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union']
class GeoAggregate(Aggregate): return super(GeoAggregate, self).as_sql(compiler, connection) def as_oracle(self, compiler, connection): if not hasattr(self, 'tolerance'): self.tolerance = 0.05 self.extra['tolerance'] = self.tolerance if not self.is_extent: se...
class GeoAggregate(Aggregate): return super(GeoAggregate, self).as_sql(compiler, connection) def as_oracle(self, compiler, connection): if not self.is_extent: tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05) clone = self.copy() expressi...
class OracleToleranceMixin(object): tolerance = 0.05 def as_oracle(self, compiler, connection): tol = self.extra.get('tolerance', self.tolerance) self.template = "%%(function)s(%%(expressions)s, %s)" % tol return super(OracleToleranceMixin, self).as_sql(compiler, connection)
class OracleToleranceMixin(object): tolerance = 0.05 def as_oracle(self, compiler, connection): tol = self._handle_param( self.extra.get('tolerance', self.tolerance), 'tolerance', NUMERIC_TYPES, ) self.template = "%%(function)s(%%(expressions)s, %s)" ...
from __future__ import unicode_literals from unittest import skipIf from django.contrib.gis.db.models.functions import ( Area, Distance, Length, Perimeter, Transform,
from __future__ import unicode_literals from unittest import skipIf, skipUnless from django.contrib.gis.db.models.functions import ( Area, Distance, Length, Perimeter, Transform,
class DistanceFunctionsTests(TestCase): for i, c in enumerate(qs): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) @no_oracle # Oracle already handles geographic distance calculation. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function') def tes...
class DistanceFunctionsTests(TestCase): for i, c in enumerate(qs): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) @skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_distance_function_tolerance_escaping(s...
from __future__ import unicode_literals import re import tempfile from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union
from __future__ import unicode_literals import re import tempfile import unittest from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union