buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_load_library_no_algorithm(self):
with self.assertRaises(ValueError) as e:
BasePasswordHasher()._load_library() | class TestUtilsHashPass(SimpleTestCase):
self.assertTrue(check_password('letmein', encoded, setter))
self.assertTrue(state['upgraded'])
def test_check_password_calls_harden_runtime(self):
hasher = get_hasher('default')
encoded = make_password('letmein')
with mock.pa... |
Make api awesomeness
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import inspect
import os
# Import Salt libs
import salt.log # pylint: disable=W0611
import salt.client
import salt.config
import salt.runner
import salt.syspaths
import salt.wheel
import salt.utils.a... | 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 libs
import salt.log # pylint: disable=W0611
import salt.auth
import salt.client
import salt.config
import salt.daemons.masterapi
i... |
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):
self.opts['sock_dir'],
ipc_file))
def run(self, low):
'''
Execute the specified function in the specified client by passing the | class NetapiClient(object):
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_name = "TokenAuthenticationError"
sensitive_... |
class NetapiClient(object):
raise salt.exceptions.EauthAuthenticationError(
'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):
raise salt.exceptions.EauthAuthenticationError(
'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)
... |
# encoding: utf-8
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
# Import Salt Testing libs
from tests.support.paths import TMP_CONF_DIR, TMP
from tests.support.unit import TestCase, skipIf
from tests.support.mock import patch
from te... | # encoding: utf-8
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
import time
import salt.config
import salt.netapi
import salt.utils.files
import salt.utils.platform
import salt.utils.pycrypto
# Import Salt Testing libs
from tests.sup... |
class NetapiSSHClientTest(SSHCase):
'''
opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master'))
self.netapi = salt.netapi.NetapiClient(opts)
# Initialize salt-ssh
self.run_function('test.ping') | class NetapiSSHClientTest(SSHCase):
'''
opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master'))
self.netapi = salt.netapi.NetapiClient(opts)
opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master"))
naopts = copy.deepcopy(opts)
naopts["ignore_h... |
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"... |
from ansible.module_utils.urls import open_url
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s
display = Display()
| from ansible.module_utils.urls import open_url
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s
try:
from urllib.parse import urlparse
except ImportError:
# Python 2
from urlparse import urlparse
display = Display()
|
class GalaxyAPI:
data = self._call_galaxy(url)
results = data['results']
done = (data.get('next_link', None) is None)
while not done:
url = _urljoin(self.api_server, data['next_link'])
data = self._call_galaxy(url)
results +... | class GalaxyAPI:
data = self._call_galaxy(url)
results = data['results']
done = (data.get('next_link', None) is None)
# https://github.com/ansible/ansible/issues/64355
# api_server contains part of the API path but next_link includes the the /api part so stri... |
def test_get_collection_versions_pagination(api_version, token_type, token_ins,
assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type
assert mock_open.mock_calls[2][2... | def test_get_collection_versions_pagination(api_version, token_type, token_ins,
assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == '%s my token' % token_type
assert mock_open.mock_calls[2][2... |
class Language(object):
"""
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
if ENABLE_PIPELINE_ANALYSIS:
analyze_all_pipes(self.pipeline)
return self.pipeline.pop(self.pipe_names.index(name))
def __call__(... | class Language(object):
"""
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
removed = self.pipeline.pop(self.pipe_names.index(name))
if ENABLE_PIPELINE_ANALYSIS:
analyze_all_pipes(self.pipeline)
return ... |
def test_analysis_validate_attrs_valid():
def test_analysis_validate_attrs_invalid(attr):
with pytest.raises(ValueError):
validate_attrs([attr]) | def test_analysis_validate_attrs_valid():
def test_analysis_validate_attrs_invalid(attr):
with pytest.raises(ValueError):
validate_attrs([attr])
def test_analysis_validate_attrs_remove_pipe():
"""Test that attributes are validated correctly on remove."""
spacy.language.ENABLE_PIPELINE_ANALYSIS = T... |
class LightSource:
.format(lookup.keys)) from err
# Only apply result where hillshade intensity isn't masked
if hasattr(intensity, 'mask'):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask] | class LightSource:
.format(lookup.keys)) from err
# Only apply result where hillshade intensity isn't masked
if np.ma.is_masked(intensity):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask] |
def test_light_source_shading_default():
assert_array_almost_equal(rgb, expect, decimal=2)
# Numpy 1.9.1 fixed a bug in masked arrays which resulted in
# additional elements being masked when calculating the gradient thus
# the output is different with earlier numpy versions. | def test_light_source_shading_default():
assert_array_almost_equal(rgb, expect, decimal=2)
def test_light_source_shading_empty_mask():
y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j]
z0 = 10 * np.cos(x**2 + y**2)
z1 = np.ma.array(z0)
cmap = plt.cm.copper
ls = mcolors.LightSource(315, 45)
rgb0 =... |
notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(... |
options:
a list of strings (see examples).
type: raw
required: true
params:
description:
- Additional module parameters.
type: dict
extends_documentation_fragment:
- ldap.documentation
''' | options:
a list of strings (see examples).
type: raw
required: true
extends_documentation_fragment:
- ldap.documentation
''' |
EXAMPLES = r'''
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowExpire
values: []
state: exact
params: "{{ ldap_auth }}"
'''
RETURN = r''' | EXAMPLES = r'''
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowEx... |
modlist:
'''
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes | modlist:
'''
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes |
def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
module.params.update(module.params['par... | def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
... |
notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(params) parameter s... |
options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
params:
description:
- List of options which allows to overwrite any of the task or the
I(attributes) options. To remove an option, se... | options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
state:
description:
- The target state of the entry. |
EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
params: "{{ ldap_auth }}"
"""
| EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
args: "{{ ldap_au... |
RETURN = """
"""
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types | RETURN = """
"""
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types |
def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
state = module.params['state']
# Check if objectClass is present when needed | def main():
module.fail_json(msg=missing_required_lib('python-ldap'),
exception=LDAP_IMP_ERR)
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
... |
def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
for key, ... | def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Instantiate the LdapEntry object
ldap = LdapEntry(module)
|
class MinimumLengthValidator:
) % {'min_length': self.min_length}
class UserAttributeSimilarityValidator:
"""
Validate whether the password is sufficiently different from the user's | class MinimumLengthValidator:
) % {'min_length': self.min_length}
def exceeds_maximum_length_ratio(password, max_similarity, value):
"""
Test that value is within a reasonable range of password.
The following ratio calculations are based on testing SequenceMatcher like
this:
for i in ran... |
class UserAttributeSimilarityValidator:
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
self.user_attributes = user_attributes
self.max_similarity = max_similarity
def validate(self, password, user=None):
if not user:
return
for att... | class UserAttributeSimilarityValidator:
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
self.user_attributes = user_attributes
if max_similarity < 0.1:
raise ValueError('max_similarity must be at least 0.1')
self.max_similarity = max_similarity
... |
class UserAttributeSimilarityValidatorTest(TestCase):
max_similarity=1,
).validate(user.first_name, user=user)
self.assertEqual(cm.exception.messages, [expected_error % "first name"])
# max_similarity=0 rejects all passwords.
with self.assertRaises(ValidationError) as... | class UserAttributeSimilarityValidatorTest(TestCase):
max_similarity=1,
).validate(user.first_name, user=user)
self.assertEqual(cm.exception.messages, [expected_error % "first name"])
# Very low max_similarity is rejected.
msg = 'max_similarity must be at least 0.1'
... |
from .engine import create_engine # noqa nosort
from .engine import engine_from_config # noqa nosort
__version__ = '1.3.0b3'
def __go(lcls): | from .engine import create_engine # noqa nosort
from .engine import engine_from_config # noqa nosort
__version__ = "1.3.0b3"
def __go(lcls): |
except ImportError:
_python_UUID = None
AUTOCOMMIT_REGEXP = re.compile(
r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|"
"IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE)", | except ImportError:
_python_UUID = None
IDX_USING = re.compile(r"^(?:btree|hash|gist|gin|[\w_]+)$", re.I)
AUTOCOMMIT_REGEXP = re.compile(
r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|"
"IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE)", |
class PGDDLCompiler(compiler.DDLCompiler):
using = index.dialect_options["postgresql"]["using"]
if using:
text += "USING %s " % preparer.quote(using)
ops = index.dialect_options["postgresql"]["ops"]
text += "(%s)" % ( | class PGDDLCompiler(compiler.DDLCompiler):
using = index.dialect_options["postgresql"]["using"]
if using:
text += (
"USING %s "
% self.preparer.validate_sql_phrase(using, IDX_USING).lower()
)
ops = index.dialect_options["postgresql"]["ops... |
class PGDDLCompiler(compiler.DDLCompiler):
"%s WITH %s" % (self.sql_compiler.process(expr, **kw), op)
)
text += "EXCLUDE USING %s (%s)" % (
constraint.using,
", ".join(elements),
)
if constraint.where is not None: | class PGDDLCompiler(compiler.DDLCompiler):
"%s WITH %s" % (self.sql_compiler.process(expr, **kw), op)
)
text += "EXCLUDE USING %s (%s)" % (
self.preparer.validate_sql_phrase(
constraint.using, IDX_USING
).lower(),
", ".join(elements... |
class ExcludeConstraint(ColumnCollectionConstraint):
where = None
def __init__(self, *elements, **kw):
r"""
Create an :class:`.ExcludeConstraint` object. | class ExcludeConstraint(ColumnCollectionConstraint):
where = None
@elements._document_text_coercion(
"where",
":class:`.ExcludeConstraint`",
":paramref:`.ExcludeConstraint.where`",
)
def __init__(self, *elements, **kw):
r"""
Create an :class:`.ExcludeConstraint`... |
class ExcludeConstraint(ColumnCollectionConstraint):
)
:param \*elements:
A sequence of two tuples of the form ``(column, operator)`` where
"column" is a SQL expression element or a raw SQL string, most
typically a :class:`.Column` object,
and "operator" is a... | class ExcludeConstraint(ColumnCollectionConstraint):
)
:param \*elements:
A sequence of two tuples of the form ``(column, operator)`` where
"column" is a SQL expression element or a raw SQL string, most
typically a :class:`.Column` object, and "operator" is a string
... |
class ExcludeConstraint(ColumnCollectionConstraint):
If set, emit WHERE <predicate> when issuing DDL
for this constraint.
.. note::
A plain string passed here is interpreted as an arbitrary SQL
expression; when passing a plain string, any necessary quoting... | class ExcludeConstraint(ColumnCollectionConstraint):
If set, emit WHERE <predicate> when issuing DDL
for this constraint.
"""
columns = []
render_exprs = [] |
class ExcludeConstraint(ColumnCollectionConstraint):
# backwards compat
self.operators[name] = operator
expr = expression._literal_as_text(expr)
render_exprs.append((expr, name, operator))
self._render_exprs = render_exprs
ColumnCollectionConstr... | class ExcludeConstraint(ColumnCollectionConstraint):
# backwards compat
self.operators[name] = operator
expr = expression._literal_as_column(expr)
render_exprs.append((expr, name, operator))
self._render_exprs = render_exprs
ColumnCollectionCon... |
class ExcludeConstraint(ColumnCollectionConstraint):
self.using = kw.get("using", "gist")
where = kw.get("where")
if where is not None:
self.where = expression._literal_as_text(where)
def copy(self, **kw):
elements = [(col, self.operators[col]) for col in self.columns.ke... | class ExcludeConstraint(ColumnCollectionConstraint):
self.using = kw.get("using", "gist")
where = kw.get("where")
if where is not None:
self.where = expression._literal_as_text(
where, allow_coercion_to_text=True
)
def copy(self, **kw):
elemen... |
class Session(_SessionClassMethods):
in order to execute the statement.
"""
clause = expression._literal_as_text(clause)
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw) | class Session(_SessionClassMethods):
in order to execute the statement.
"""
clause = expression._literal_as_text(
clause, allow_coercion_to_text=True
)
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw) |
RESERVED_WORDS = set(
)
LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I)
ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"])
BIND_PARAMS = re.compile(r"(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])", re.UNICODE)
BIND_PARAMS_ESC = re.compile(r"\x5c(:[\w\$]*)(?![:\w\$])", re.UNICODE)
| RESERVED_WORDS = set(
)
LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I)
LEGAL_CHARACTERS_PLUS_SPACE = re.compile(r"^[A-Z0-9_ $]+$", re.I)
ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"])
FK_ON_DELETE = re.compile(
r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
)
FK_ON... |
class SQLCompiler(Compiled):
else:
col = with_cols[element.element]
except KeyError:
# treat it like text()
util.warn_limited(
"Can't resolve label reference %r; converting to text()",
util.ellipses_string(element.element),
... | class SQLCompiler(Compiled):
else:
col = with_cols[element.element]
except KeyError:
elements._no_text_coercion(
element.element,
exc.CompileError,
"Can't resolve label reference for ORDER BY / GROUP BY.",
)
... |
class SQLCompiler(Compiled):
if func._has_args:
name += "%(expr)s"
else:
name = func.name + "%(expr)s"
return ".".join(list(func.packagenames) + [name]) % {
"expr": self.function_argspec(func, **kwargs)
}
def vi... | class SQLCompiler(Compiled):
if func._has_args:
name += "%(expr)s"
else:
name = func.name
name = (
self.preparer.quote(name)
if self.preparer._requires_quotes_illegal_chars(name)
e... |
class DDLCompiler(Compiled):
def define_constraint_cascades(self, constraint):
text = ""
if constraint.ondelete is not None:
text += " ON DELETE %s" % constraint.ondelete
if constraint.onupdate is not None:
text += " ON UPDATE %s" % constraint.onupdate
return ... | class DDLCompiler(Compiled):
def define_constraint_cascades(self, constraint):
text = ""
if constraint.ondelete is not None:
text += " ON DELETE %s" % self.preparer.validate_sql_phrase(
constraint.ondelete, FK_ON_DELETE
)
if constraint.onupdate is not ... |
class DDLCompiler(Compiled):
else:
text += " NOT DEFERRABLE"
if constraint.initially is not None:
text += " INITIALLY %s" % constraint.initially
return text
def define_constraint_match(self, constraint): | class DDLCompiler(Compiled):
else:
text += " NOT DEFERRABLE"
if constraint.initially is not None:
text += " INITIALLY %s" % self.preparer.validate_sql_phrase(
constraint.initially, FK_INITIALLY
)
return text
def define_constraint_m... |
class IdentifierPreparer(object):
return value.replace(self.escape_to_quote, self.escape_quote)
def quote_identifier(self, value):
"""Quote an identifier.
| class IdentifierPreparer(object):
return value.replace(self.escape_to_quote, self.escape_quote)
def validate_sql_phrase(self, element, reg):
"""keyword sequence filter.
a filter for elements that are intended to represent keyword sequences,
such as "INITIALLY", "INTIALLY DEFERRED"... |
class IdentifierPreparer(object):
or (lc_value != value)
)
def quote_schema(self, schema, force=None):
"""Conditionally quote a schema name.
| class IdentifierPreparer(object):
or (lc_value != value)
)
def _requires_quotes_illegal_chars(self, value):
"""Return True if the given identifier requires quoting, but
not taking case convention into account."""
return not self.legal_characters.match(util.text_type(valu... |
def _clone(element, **kw):
return element._clone()
def collate(expression, collation):
"""Return the clause ``expression COLLATE collation``.
| def _clone(element, **kw):
return element._clone()
def _document_text_coercion(paramname, meth_rst, param_rst):
return util.add_parameter_text(
paramname,
(
".. warning:: "
"The %s argument to %s can be passed as a Python string argument, "
"which will be tr... |
class TextClause(Executable, ClauseElement):
"refer to the :meth:`.TextClause.columns` method.",
),
)
def _create_text(
self, text, bind=None, bindparams=None, typemap=None, autocommit=None
): | class TextClause(Executable, ClauseElement):
"refer to the :meth:`.TextClause.columns` method.",
),
)
@_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`")
def _create_text(
self, text, bind=None, bindparams=None, typemap=None, autocommit=None
): |
def _literal_and_labels_as_label_reference(element):
def _expression_literal_as_text(element):
return _literal_as_text(element, warn=True)
def _literal_as_text(element, warn=False):
if isinstance(element, Visitable):
return element
elif hasattr(element, "__clause_element__"):
return elem... | def _literal_and_labels_as_label_reference(element):
def _expression_literal_as_text(element):
return _literal_as_text(element)
def _literal_as(element, text_fallback):
if isinstance(element, Visitable):
return element
elif hasattr(element, "__clause_element__"):
return element.__clause_... |
def _interpret_as_column_or_from(element):
elif isinstance(element, (numbers.Number)):
return ColumnClause(str(element), is_literal=True)
else:
element = str(element)
# give into temptation, as this fact we are guessing about
# is not one we've previously ever needed our users te... | def _interpret_as_column_or_from(element):
elif isinstance(element, (numbers.Number)):
return ColumnClause(str(element), is_literal=True)
else:
_no_column_coercion(element)
return ColumnClause(element, is_literal=guess_is_literal)
|
from .elements import _expression_literal_as_text # noqa
from .elements import _is_column # noqa
from .elements import _labeled # noqa
from .elements import _literal_as_binds # noqa
from .elements import _literal_as_label_reference # noqa
from .elements import _literal_as_text # noqa
from .elements import _only_c... | from .elements import _expression_literal_as_text # noqa
from .elements import _is_column # noqa
from .elements import _labeled # noqa
from .elements import _literal_as_binds # noqa
from .elements import _literal_as_column # noqa
from .elements import _literal_as_label_reference # noqa
from .elements import _lite... |
from .base import ColumnCollection
from .base import DialectKWArgs
from .base import SchemaEventTarget
from .elements import _as_truncated
from .elements import _literal_as_text
from .elements import ClauseElement
from .elements import ColumnClause | from .base import ColumnCollection
from .base import DialectKWArgs
from .base import SchemaEventTarget
from .elements import _as_truncated
from .elements import _document_text_coercion
from .elements import _literal_as_text
from .elements import ClauseElement
from .elements import ColumnClause |
class CheckConstraint(ColumnCollectionConstraint):
_allow_multiple_tables = True
def __init__(
self,
sqltext, | class CheckConstraint(ColumnCollectionConstraint):
_allow_multiple_tables = True
@_document_text_coercion(
"sqltext",
":class:`.CheckConstraint`",
":paramref:`.CheckConstraint.sqltext`",
)
def __init__(
self,
sqltext, |
class CheckConstraint(ColumnCollectionConstraint):
"""
self.sqltext = _literal_as_text(sqltext, warn=False)
columns = []
visitors.traverse(self.sqltext, {}, {"column": columns.append}) | class CheckConstraint(ColumnCollectionConstraint):
"""
self.sqltext = _literal_as_text(sqltext, allow_coercion_to_text=True)
columns = []
visitors.traverse(self.sqltext, {}, {"column": columns.append}) |
from .elements import _clause_element_as_expr
from .elements import _clone
from .elements import _cloned_difference
from .elements import _cloned_intersection
from .elements import _expand_cloned
from .elements import _interpret_as_column_or_from
from .elements import _literal_and_labels_as_label_reference
from .elemen... | from .elements import _clause_element_as_expr
from .elements import _clone
from .elements import _cloned_difference
from .elements import _cloned_intersection
from .elements import _document_text_coercion
from .elements import _expand_cloned
from .elements import _interpret_as_column_or_from
from .elements import _lite... |
from .elements import ClauseElement
from .elements import ClauseList
from .elements import Grouping
from .elements import literal_column
from .elements import TextClause
from .elements import True_
from .elements import UnaryExpression
from .. import exc | from .elements import ClauseElement
from .elements import ClauseList
from .elements import Grouping
from .elements import literal_column
from .elements import True_
from .elements import UnaryExpression
from .. import exc |
def _interpret_as_from(element):
insp = inspection.inspect(element, raiseerr=False)
if insp is None:
if isinstance(element, util.string_types):
util.warn_limited(
"Textual SQL FROM expression %(expr)r should be "
"explicitly declared as text(%(expr)r), "
... | def _interpret_as_from(element):
insp = inspection.inspect(element, raiseerr=False)
if insp is None:
if isinstance(element, util.string_types):
_no_text_coercion(element)
try:
return insp.selectable
except AttributeError: |
class HasPrefixes(object):
_prefixes = ()
@_generative
def prefix_with(self, *expr, **kw):
r"""Add one or more expressions following the statement keyword, i.e.
SELECT, INSERT, UPDATE, or DELETE. Generative. | class HasPrefixes(object):
_prefixes = ()
@_generative
@_document_text_coercion(
"expr",
":meth:`.HasPrefixes.prefix_with`",
":paramref:`.HasPrefixes.prefix_with.*expr`",
)
def prefix_with(self, *expr, **kw):
r"""Add one or more expressions following the statement ke... |
class HasPrefixes(object):
def _setup_prefixes(self, prefixes, dialect=None):
self._prefixes = self._prefixes + tuple(
[(_literal_as_text(p, warn=False), dialect) for p in prefixes]
)
| class HasPrefixes(object):
def _setup_prefixes(self, prefixes, dialect=None):
self._prefixes = self._prefixes + tuple(
[
(_literal_as_text(p, allow_coercion_to_text=True), dialect)
for p in prefixes
]
)
|
class HasSuffixes(object):
_suffixes = ()
@_generative
def suffix_with(self, *expr, **kw):
r"""Add one or more expressions following the statement as a whole.
| class HasSuffixes(object):
_suffixes = ()
@_generative
@_document_text_coercion(
"expr",
":meth:`.HasSuffixes.suffix_with`",
":paramref:`.HasSuffixes.suffix_with.*expr`",
)
def suffix_with(self, *expr, **kw):
r"""Add one or more expressions following the statement as... |
class HasSuffixes(object):
def _setup_suffixes(self, suffixes, dialect=None):
self._suffixes = self._suffixes + tuple(
[(_literal_as_text(p, warn=False), dialect) for p in suffixes]
)
| class HasSuffixes(object):
def _setup_suffixes(self, suffixes, dialect=None):
self._suffixes = self._suffixes + tuple(
[
(_literal_as_text(p, allow_coercion_to_text=True), dialect)
for p in suffixes
]
)
|
from .deprecations import inject_docstring_text # noqa
from .deprecations import pending_deprecation # noqa
from .deprecations import warn_deprecated # noqa
from .deprecations import warn_pending_deprecation # noqa
from .langhelpers import as_interface # noqa
from .langhelpers import asbool # noqa
from .langhelpe... | from .deprecations import inject_docstring_text # noqa
from .deprecations import pending_deprecation # noqa
from .deprecations import warn_deprecated # noqa
from .deprecations import warn_pending_deprecation # noqa
from .langhelpers import add_parameter_text # noqa
from .langhelpers import as_interface # noqa
fro... |
functionality."""
import re
import textwrap
import warnings
from . import compat
from .langhelpers import decorator
from .. import exc
| functionality."""
import re
import warnings
from . import compat
from .langhelpers import decorator
from .langhelpers import inject_docstring_text
from .langhelpers import inject_param_text
from .. import exc
|
def _decorate_with_warning(func, wtype, message, docstring_header=None):
decorated.__doc__ = doc
decorated._sa_warn = lambda: warnings.warn(message, wtype, stacklevel=3)
return decorated
def _dedent_docstring(text):
split_text = text.split("\n", 1)
if len(split_text) == 1:
return text
... | def _decorate_with_warning(func, wtype, message, docstring_header=None):
decorated.__doc__ = doc
decorated._sa_warn = lambda: warnings.warn(message, wtype, stacklevel=3)
return decorated |
import itertools
import operator
import re
import sys
import types
import warnings
| import itertools
import operator
import re
import sys
import textwrap
import types
import warnings
|
def quoted_token_parser(value):
idx += 1
return ["".join(token) for token in result] | def quoted_token_parser(value):
idx += 1
return ["".join(token) for token in result]
def add_parameter_text(params, text):
params = _collections.to_list(params)
def decorate(fn):
doc = fn.__doc__ is not None and fn.__doc__ or ""
if doc:
doc = inject_param_text(doc, {p... |
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
Column(
"id",
Integer,
ForeignKey("t1.id", deferrable=True, initially="XYZ"),
primary_key=True,
),
) | class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
Column(
"id",
Integer,
ForeignKey("t1.id", deferrable=True, initially="DEFERRED"),
primary_key=True,
),
) |
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
schema.CreateTable(t2),
"CREATE TABLE t2 (id INTEGER NOT NULL, "
"PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES t1 (id) "
"DEFERRABLE INITIALLY XYZ)",
)
def test_match_kw_raises(self): | class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
schema.CreateTable(t2),
"CREATE TABLE t2 (id INTEGER NOT NULL, "
"PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES t1 (id) "
"DEFERRABLE INITIALLY DEFERRED)",
)
def test_match_kw_raises(self): |
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
"WITH (buffering = off)",
)
def test_create_index_with_tablespace(self):
m = MetaData()
tbl = Table("testtbl", m, Column("data", String)) | class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
"WITH (buffering = off)",
)
def test_create_index_with_using_unusual_conditions(self):
m = MetaData()
tbl = Table("testtbl", m, Column("data", String))
self.assert_compile(
schema.CreateIndex(
... |
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
"(room::TEXT WITH =)",
)
def test_exclude_constraint_cast(self):
m = MetaData()
tbl = Table("testtbl", m, Column("room", String)) | class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
"(room::TEXT WITH =)",
)
def test_exclude_constraint_colname_needs_quoting(self):
m = MetaData()
cons = ExcludeConstraint(("Some Column Name", "="))
Table("testtbl", m, Column("Some Column Name", String), cons)
... |
from sqlalchemy.sql import operators
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import in_
from sqlalchemy.testing impo... | from sqlalchemy.sql import operators
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import in_
from sqlalchemy.testing import is_ |
class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
.order_by("email_address")
)
with expect_warnings("Can't resolve label reference 'email_address'"):
self.assert_compile(
q,
"SELECT users.id AS users_id, users.name AS users_name,... | class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
.order_by("email_address")
)
assert_raises_message(
sa.exc.CompileError,
"Can't resolve label reference for ORDER BY / GROUP BY.",
q.all,
)
def test_deferred_fk_col(self):
... |
from sqlalchemy.orm.util import join
from sqlalchemy.orm.util import with_parent
from sqlalchemy.sql import expression
from sqlalchemy.sql import operators
from sqlalchemy.testing import assert_warnings
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import fixtures
from sqlalchemy.testing imp... | from sqlalchemy.orm.util import join
from sqlalchemy.orm.util import with_parent
from sqlalchemy.sql import expression
from sqlalchemy.sql import operators
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_ |
class ColumnPropertyTest(_fixtures.FixtureTest, AssertsCompiledSQL):
ua = aliased(User)
q = s.query(ua).order_by("email_ad")
def go():
self.assert_compile(
q,
"SELECT (SELECT max(addresses.email_address) AS max_1 "
"FROM addresses WHER... | class ColumnPropertyTest(_fixtures.FixtureTest, AssertsCompiledSQL):
ua = aliased(User)
q = s.query(ua).order_by("email_ad")
assert_raises_message(
sa.exc.CompileError,
"Can't resolve label reference for ORDER BY / GROUP BY",
q.with_labels().statement.compile... |
class TextTest(QueryTest, AssertsCompiledSQL):
def test_fulltext(self):
User = self.classes.User
with expect_warnings("Textual SQL"):
eq_(
create_session()
.query(User)
.from_statement("select * from users order by id")
.al... | class TextTest(QueryTest, AssertsCompiledSQL):
def test_fulltext(self):
User = self.classes.User
assert_raises_message(
sa_exc.ArgumentError,
"Textual SQL expression",
create_session().query(User).from_statement,
"select * from users order by id",
... |
class TextTest(QueryTest, AssertsCompiledSQL):
def test_binds_coerce(self):
User = self.classes.User
with expect_warnings("Textual SQL expression"):
eq_(
create_session()
.query(User)
.filter("id in (:id1, :id2)")
.params(i... | class TextTest(QueryTest, AssertsCompiledSQL):
def test_binds_coerce(self):
User = self.classes.User
assert_raises_message(
sa_exc.ArgumentError,
r"Textual SQL expression 'id in \(:id1, :id2\)' "
"should be explicitly declared",
create_session().query... |
class TextTest(QueryTest, AssertsCompiledSQL):
# the queries here are again "invalid" from a SQL perspective, as the
# "name" field isn't matched up to anything.
#
with expect_warnings("Can't resolve label reference 'name';"):
self.assert_compile(
s.query(User... | class TextTest(QueryTest, AssertsCompiledSQL):
# the queries here are again "invalid" from a SQL perspective, as the
# "name" field isn't matched up to anything.
#
q = (
s.query(User)
.options(joinedload("addresses"))
.order_by(desc("name"))
... |
class TextTest(QueryTest, AssertsCompiledSQL):
.limit(1)
.offset(0)
)
with expect_warnings(
"Can't resolve label reference 'email_address desc'"
):
eq_(
[
(
User(
... | class TextTest(QueryTest, AssertsCompiledSQL):
.limit(1)
.offset(0)
)
assert_raises_message(
sa_exc.CompileError,
"Can't resolve label reference for ORDER BY / GROUP BY",
result.all,
)
class TextErrorTest(QueryTest, AssertsCompiledSQ... |
class TextWarningTest(QueryTest, AssertsCompiledSQL):
arg,
)
with expect_warnings("Textual "):
stmt = fn(arg)
self.assert_compile(stmt, expected)
def test_filter(self):
User = self.classes.User
self._test(
Session().query(User.id).fil... | class TextWarningTest(QueryTest, AssertsCompiledSQL):
arg,
)
def test_filter(self):
User = self.classes.User
self._test(Session().query(User.id).filter, "myid == 5", "myid == 5")
def test_having(self):
User = self.classes.User
self._test(Session().query(User... |
class TextWarningTest(QueryTest, AssertsCompiledSQL):
Session().query(User.id).from_statement,
"select id from user",
"select id from user",
"select id from user",
)
| class TextWarningTest(QueryTest, AssertsCompiledSQL):
Session().query(User.id).from_statement,
"select id from user",
"select id from user",
)
|
class DDLTest(fixtures.TestBase, AssertsCompiledSQL):
schema_translate_map=schema_translate_map,
)
class SchemaTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default" | class DDLTest(fixtures.TestBase, AssertsCompiledSQL):
schema_translate_map=schema_translate_map,
)
def test_fk_render(self):
a = Table("a", MetaData(), Column("q", Integer))
b = Table("b", MetaData(), Column("p", Integer))
self.assert_compile(
schema.AddCons... |
class DefaultTest(fixtures.TestBase):
):
assert_raises_message(
sa.exc.ArgumentError,
"SQL expression object or string expected, got object of type "
"<.* 'list'> instead",
t.select,
[const], | class DefaultTest(fixtures.TestBase):
):
assert_raises_message(
sa.exc.ArgumentError,
"SQL expression object expected, got object of type "
"<.* 'list'> instead",
t.select,
[const], |
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
def test_underscores(self):
self.assert_compile(func.if_(), "if()")
def test_generic_now(self):
assert isinstance(func.now().type, sqltypes.DateTime)
| class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
def test_underscores(self):
self.assert_compile(func.if_(), "if()")
def test_underscores_packages(self):
self.assert_compile(func.foo_.bar_.if_(), "foo.bar.if()")
def test_uppercase(self):
# for now, we need to keep case ins... |
from sqlalchemy.sql import column
from sqlalchemy.sql import table
from sqlalchemy.sql import util as sql_util
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import assert_warnings
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
from sqlalchemy.testing ... | from sqlalchemy.sql import column
from sqlalchemy.sql import table
from sqlalchemy.sql import util as sql_util
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.types import Nu... |
class AsFromTest(fixtures.TestBase, AssertsCompiledSQL):
eq_(set(t.element._bindparams), set(["bat", "foo", "bar"]))
class TextWarningsTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def _test(self, fn, arg, offending_clause, expected):
with expect_warnings("Textual "):
... | class AsFromTest(fixtures.TestBase, AssertsCompiledSQL):
eq_(set(t.element._bindparams), set(["bat", "foo", "bar"]))
class TextErrorsTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def _test(self, fn, arg, offending_clause):
assert_raises_message(
exc.Argument... |
class TextWarningsTest(fixtures.TestBase, AssertsCompiledSQL):
)
def test_where(self):
self._test(
select([table1.c.myid]).where,
"myid == 5",
"myid == 5",
"SELECT mytable.myid FROM mytable WHERE myid == 5",
)
def test_column(self):
... | class TextWarningsTest(fixtures.TestBase, AssertsCompiledSQL):
)
def test_where(self):
self._test(select([table1.c.myid]).where, "myid == 5", "myid == 5")
def test_column(self):
self._test(select, ["myid"], "myid")
def test_having(self):
self._test(select([table1.c.myid]).... |
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL):
def test_unresolvable_warning_order_by(self):
stmt = select([table1.c.myid]).order_by("foobar")
self._test_warning(
stmt, "foobar", "SELECT mytable.myid FROM mytable ORDER BY foobar"
)
def test_group_b... | class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL):
def test_unresolvable_warning_order_by(self):
stmt = select([table1.c.myid]).order_by("foobar")
self._test_exception(stmt, "foobar")
def test_group_by_label(self):
stmt = select([table1.c.myid.label("foo")]).group... |
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL):
def test_unresolvable_warning_group_by(self):
stmt = select([table1.c.myid]).group_by("foobar")
self._test_warning(
stmt, "foobar", "SELECT mytable.myid FROM mytable GROUP BY foobar"
)
def test_asc(sel... | class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL):
def test_unresolvable_warning_group_by(self):
stmt = select([table1.c.myid]).group_by("foobar")
self._test_exception(stmt, "foobar")
def test_asc(self):
stmt = select([table1.c.myid]).order_by(asc("name"), "descri... |
class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL):
.order_by("myid", "t1name", "x")
)
def go():
# the labels here are anonymized, so label naming
# can't catch these.
self.assert_compile(
s1,
"SELECT m... | class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL):
.order_by("myid", "t1name", "x")
)
assert_raises_message(
exc.CompileError,
r"Can't resolve label reference for ORDER BY / GROUP BY. "
"Textual SQL "
"expression 't1name'... |
class InlineParser(ScannerParser):
#: _emphasis_ __strong__
ASTERISK_EMPHASIS = (
r'(\*{1,2})(?=[^\s*])('
r'(?:\\[\\*]|[^*])*'
r'(?:' + ESCAPE_TEXT + r'|[^\s*]))\1'
)
UNDERSCORE_EMPHASIS = (
r'\b(_{1,2})(?=[^\s_])([\s\S]*?' | class InlineParser(ScannerParser):
#: _emphasis_ __strong__
ASTERISK_EMPHASIS = (
r'(\*{1,2})(?=[^\s*])('
r'(?:(?:(?<!\\)(?:\\\\)*\*)|[^*])+'
r')(?<!\\)\1'
)
UNDERSCORE_EMPHASIS = (
r'\b(_{1,2})(?=[^\s_])([\s\S]*?' |
class Client(object):
xs.rawDataOutFn = self.rawDataOut
def disconnected(self, xs):
print('Disconnected.')
self.finished.callback(None)
| class Client(object):
xs.rawDataOutFn = self.rawDataOut
def disconnected(self, reason):
print('Disconnected.')
print(reason)
self.finished.callback(None)
|
class BasicAuthenticator(xmlstream.ConnectAuthenticator):
xs.version = (0, 0)
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(IQAuthInitializer, True),
]
for initClass, required in in... | class BasicAuthenticator(xmlstream.ConnectAuthenticator):
xs.version = (0, 0)
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [
xmlstream.TLSInitiatingInitializer(xs, required=False),
IQAuthInitializer(xs),
]
# TODO: move regis... |
class SessionInitializer(xmlstream.BaseFeatureInitiatingInitializer):
def XMPPClientFactory(jid, password):
"""
Client factory for XMPP 1.0 (only).
| class SessionInitializer(xmlstream.BaseFeatureInitiatingInitializer):
def XMPPClientFactory(jid, password, configurationForTLS=None):
"""
Client factory for XMPP 1.0 (only).
|
def XMPPClientFactory(jid, password):
@param jid: Jabber ID to connect with.
@type jid: L{jid.JID}
@param password: password to authenticate with.
@type password: L{unicode}
@return: XML stream factory.
@rtype: L{xmlstream.XmlStreamFactory}
"""
a = XMPPAuthenticator(jid, password)
r... | def XMPPClientFactory(jid, password):
@param jid: Jabber ID to connect with.
@type jid: L{jid.JID}
@param password: password to authenticate with.
@type password: L{unicode}
@param configurationForTLS: An object which creates appropriately
configured TLS connections. This is passed to C{s... |
class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
resource binding step, and this is stored in this instance
variable.
@type jid: L{jid.JID}
@ivar password: password to be used during SASL authentication.
@type password: L{unicode}
"""
namespace = 'jabber:client... | class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
resource binding step, and this is stored in this instance
variable.
@type jid: L{jid.JID}
@ivar password: password to be used during SASL authentication.
@type password: L{unicode}
"""
namespace = 'jabber:clien... |
class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
"""
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [CheckVersionInitializer(xs)]
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(sasl.SASLInitiatingInitializer, True),
... | class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
"""
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [
CheckVersionInitializer(xs),
xmlstream.TLSInitiatingInitializer(
xs, required=True,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.