本文整理汇总了Python中six.get_method_self函数的典型用法代码示例。如果您正苦于以下问题:Python get_method_self函数的具体用法?Python get_method_self怎么用?Python get_method_self使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_method_self函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_add_testcase_info
def test_add_testcase_info(self, mock_methods):
# Build a fake runner
test_case = TestCase()
runner = TestRunner(test_case)
# Populate runner with fake structure
runner.unittests = {}
runner.unittests['mod class.sample_method1'] = True
runner.unittests['mod class.sample_method2'] = False
runner.unittests['mod class.sample_method3'] = True
# Populate fake test_case with 3 fake methods
self1_t = type(six.get_method_self(self.sample_method1))
self2_t = type(six.get_method_self(self.sample_method2))
self3_t = type(six.get_method_self(self.sample_method3))
self1_t.__name__ = self2_t.__name__ = self3_t.__name__ = 'class'
self1_t.__module__ = self2_t.__module__ = self3_t.__module__ = 'mod'
test_methods = [self.sample_method1, self.sample_method2, self.sample_method3]
# Run add_testcase_info
mock_methods.return_value = test_methods
add_testcase_info(test_case, runner)
# Verify that unittests work
suites1 = getattr(self.sample_method1.__func__, '_suites', [])
self.assertEqual('unittest' in suites1, True)
suites2 = getattr(self.sample_method2.__func__, '_suites', [])
self.assertEqual('unittest' not in suites2, True)
self.assertEqual('test_suite' in suites2, True)
suites3 = getattr(self.sample_method3.__func__, '_suites', [])
self.assertEqual('unittest' in suites3, True)
示例2: upgrade_websocket
def upgrade_websocket(self, environ, start_response):
"""
Attempt to upgrade the socket environ['wsgi.input'] into a websocket enabled connection.
"""
websocket_version = environ.get('HTTP_SEC_WEBSOCKET_VERSION', '')
if not websocket_version:
raise UpgradeRequiredError
elif websocket_version not in self.WS_VERSIONS:
raise HandshakeError('Unsupported WebSocket Version: {0}'.format(websocket_version))
key = environ.get('HTTP_SEC_WEBSOCKET_KEY', '').strip()
if not key:
raise HandshakeError('Sec-WebSocket-Key header is missing/empty')
try:
key_len = len(base64.b64decode(key))
except TypeError:
raise HandshakeError('Invalid key: {0}'.format(key))
if key_len != 16:
# 5.2.1 (3)
raise HandshakeError('Invalid key: {0}'.format(key))
sec_ws_accept = base64.b64encode(sha1(six.b(key) + self.WS_GUID).digest())
if six.PY3:
sec_ws_accept = sec_ws_accept.decode('ascii')
headers = [
('Upgrade', 'websocket'),
('Connection', 'Upgrade'),
('Sec-WebSocket-Accept', sec_ws_accept),
('Sec-WebSocket-Version', str(websocket_version)),
]
logger.debug('WebSocket request accepted, switching protocols')
start_response(force_str('101 Switching Protocols'), headers)
six.get_method_self(start_response).finish_content()
return WebSocket(environ['wsgi.input'])
示例3: save_instancemethod0
def save_instancemethod0(pickler, obj): # example: cStringIO.StringI
log.info("Me: %s" % obj) # XXX: obj.__dict__ handled elsewhere?
args = (get_method_function(obj), get_method_self(obj)) if PY3 \
else (get_method_function(obj), get_method_self(obj), obj.im_class)
pickler.save_reduce(MethodType, args, obj=obj)
log.info("# Me")
示例4: _prepare_mw
def _prepare_mw(middleware=None):
"""Check middleware interface and prepare it to iterate.
Args:
middleware: list (or object) of input middleware
Returns:
A middleware list
"""
if middleware is None:
middleware = []
else:
if not isinstance(middleware, list):
middleware = [middleware]
# check basic interface of middleware objects
for mw in middleware:
if not hasattr(mw, 'process_request') and not\
hasattr(mw, 'process_response'):
raise TypeError('{0} is not a valid middlware'.format(str(mw)))
# Check process_request and process_response are bounded methods
for mw_method in ('process_request', 'process_response'):
method_mw_bound = getattr(mw, mw_method, None)
if method_mw_bound is not None:
if six.get_method_self(method_mw_bound) is None:
raise AttributeError(
'{0} must be a bound method'.format(method_mw_bound))\
# pragma: no cover
return middleware
示例5: get_function_path
def get_function_path(function, bound_to=None):
"""Get received function path (as string), to import function later
with `import_string`.
"""
if isinstance(function, six.string_types):
return function
# static and class methods
if hasattr(function, '__func__'):
real_function = function.__func__
elif callable(function):
real_function = function
else:
return function
func_path = []
module = getattr(real_function, '__module__', '__main__')
if module:
func_path.append(module)
if not bound_to:
try:
bound_to = six.get_method_self(function)
except AttributeError:
pass
if bound_to:
if isinstance(bound_to, six.class_types):
func_path.append(bound_to.__name__)
else:
func_path.append(bound_to.__class__.__name__)
func_path.append(real_function.__name__)
return '.'.join(func_path)
示例6: get_bound_method
def get_bound_method(obj, method_name):
"""Get a bound method of the given object by name.
Args:
obj: Object on which to look up the method.
method_name: Name of the method to retrieve.
Returns:
Bound method, or ``None`` if the method does not exist on
the object.
Raises:
AttributeError: The method exists, but it isn't
bound (most likely a class was passed, rather than
an instance of that class).
"""
method = getattr(obj, method_name, None)
if method is not None:
# NOTE(kgriffs): Ensure it is a bound method
if six.get_method_self(method) is None:
# NOTE(kgriffs): In Python 3 this code is unreachable
# because the above will raise AttributeError on its
# own.
msg = '{0} must be a bound method'.format(method)
raise AttributeError(msg)
return method
示例7: get_method_self
def get_method_self(method):
if not inspect.ismethod(method):
return None
try:
return six.get_method_self(method)
except AttributeError:
return None
示例8: test_get_method_self
def test_get_method_self():
class X(object):
def m(self):
pass
x = X()
assert six.get_method_self(x.m) is x
py.test.raises(AttributeError, six.get_method_self, 42)
示例9: find_ctx
def find_ctx(elt):
"""Get the right ctx related to input elt.
In order to keep safe memory as much as possible, it is important to find
the right context element. For example, instead of putting properties on
a function at the level of an instance, it is important to save such
property on the instance because the function.__dict__ is shared with
instance class function, and so, if the instance is deleted from memory,
the property is still present in the class memory. And so on, it is
impossible to identify the right context in such case if all properties
are saved with the same key in the same function which is the function.
"""
result = elt # by default, result is ctx
# if elt is ctx and elt is a method, it is possible to find the best ctx
if ismethod(elt):
# get instance and class of the elt
instance = get_method_self(elt)
# if instance is not None, the right context is the instance
if instance is not None:
result = instance
elif PY2:
result = elt.im_class
return result
示例10: to_dict
def to_dict(self):
test_method_self_t = type(six.get_method_self(self.test_method))
assert not isinstance(test_method_self_t, type(None))
return {
"previous_run": self.previous_run,
"start_time": time.mktime(self.start_time.timetuple()) if self.start_time else None,
"end_time": time.mktime(self.end_time.timetuple()) if self.end_time else None,
"run_time": (self.run_time.seconds + float(self.run_time.microseconds) / 1000000)
if self.run_time is not None
else None,
"normalized_run_time": None
if not self.run_time
else "%.2fs" % (self.run_time.seconds + (self.run_time.microseconds / 1000000.0)),
"complete": self.complete,
"success": self.success,
"failure": self.failure,
"error": self.error,
"interrupted": self.interrupted,
"exception_info": self.format_exception_info(),
"exception_info_pretty": self.format_exception_info(pretty=True),
"exception_only": self.format_exception_only(),
"runner_id": self.runner_id,
"method": {
"module": test_method_self_t.__module__,
"class": test_method_self_t.__name__,
"name": self.test_method.__name__,
"full_name": "%s %s.%s"
% (test_method_self_t.__module__, test_method_self_t.__name__, self.test_method.__name__),
"fixture_type": None
if not inspection.is_fixture_method(self.test_method)
else self.test_method._fixture_type,
},
}
示例11: validate_args
def validate_args(fn, *args, **kwargs):
"""Check that the supplied args are sufficient for calling a function.
>>> validate_args(lambda a: None)
Traceback (most recent call last):
...
MissingArgs: Missing argument(s): a
>>> validate_args(lambda a, b, c, d: None, 0, c=1)
Traceback (most recent call last):
...
MissingArgs: Missing argument(s): b, d
:param fn: the function to check
:param arg: the positional arguments supplied
:param kwargs: the keyword arguments supplied
"""
argspec = inspect.getargspec(fn)
num_defaults = len(argspec.defaults or [])
required_args = argspec.args[:len(argspec.args) - num_defaults]
if six.get_method_self(fn) is not None:
required_args.pop(0)
missing = [arg for arg in required_args if arg not in kwargs]
missing = missing[len(args):]
return missing
示例12: ensure_generator
def ensure_generator(self, fixture):
if fixture._fixture_type in HYBRID_FIXTURES:
# already a context manager, nothing to do
return fixture
if fixture._fixture_type in SETUP_FIXTURES:
def wrapper(self):
fixture()
yield
elif fixture._fixture_type in TEARDOWN_FIXTURES:
def wrapper(self):
yield
fixture()
wrapper.__name__ = fixture.__name__
wrapper.__doc__ = fixture.__doc__
wrapper._fixture_type = fixture._fixture_type
wrapper._fixture_id = fixture._fixture_id
wrapper._defining_class_depth = fixture._defining_class_depth
# http://stackoverflow.com/q/4364565
func_self = six.get_method_self(fixture)
assert func_self is not None
return wrapper.__get__(func_self, type(func_self))
示例13: clear_api_path_map_cache
def clear_api_path_map_cache(self):
"""Clear out cache for api_path_map."""
self._api_path_cache = None
for api_provider in self.api_providers:
if six.get_method_self(
api_provider.clear_api_path_map_cache,
) is not None:
api_provider.clear_api_path_map_cache()
示例14: get_method_self
def get_method_self(method):
"""Gets the ``self`` object attached to this method (or none)."""
if not inspect.ismethod(method):
return None
try:
return six.get_method_self(method)
except AttributeError:
return None
示例15: key_names
def key_names(self):
# If the current page has a last_evaluated_key, use it to determine key attributes
if self._last_evaluated_key:
return self._last_evaluated_key.keys()
# Use the table meta data to determine the key attributes
table_meta = six.get_method_self(self._operation).get_meta_table() # type: ignore # method_self cannot be None
return table_meta.get_key_names(self._kwargs.get('index_name'))