code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def listNames(self, request):
"""Retrieve a list of all names for entities that I contain.
See getEntity.
"""
return self.listStaticNames() | Retrieve a list of all names for entities that I contain.
See getEntity. | listNames | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | MIT |
def nameConstraint(self, name):
"""A method that determines whether an entity may be added to me with a given name.
If the constraint is satisfied, return 1; if the constraint is not
satisfied, either return 0 or raise a descriptive ConstraintViolation.
"""
return 1 | A method that determines whether an entity may be added to me with a given name.
If the constraint is satisfied, return 1; if the constraint is not
satisfied, either return 0 or raise a descriptive ConstraintViolation. | nameConstraint | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | MIT |
def entityConstraint(self, entity):
"""A method that determines whether an entity may be added to me.
If the constraint is satisfied, return 1; if the constraint is not
satisfied, either return 0 or raise a descriptive ConstraintViolation.
"""
return 1 | A method that determines whether an entity may be added to me.
If the constraint is satisfied, return 1; if the constraint is not
satisfied, either return 0 or raise a descriptive ConstraintViolation. | entityConstraint | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | MIT |
def putEntity(self, name, entity):
"""Store an entity if it meets both constraints.
Otherwise raise a ConstraintViolation.
"""
if self.nameConstraint(name):
if self.entityConstraint(entity):
self.reallyPutEntity(name, entity)
else:
raise ConstraintViolation("Entity constraint violated.")
else:
raise ConstraintViolation("Name constraint violated.") | Store an entity if it meets both constraints.
Otherwise raise a ConstraintViolation. | putEntity | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/roots.py | MIT |
def callWithContext(self, newContext, func, *args, **kw):
"""
Call C{func(*args, **kw)} such that the contents of C{newContext} will
be available for it to retrieve using L{getContext}.
@param newContext: A C{dict} of data to push onto the context for the
duration of the call to C{func}.
@param func: A callable which will be called.
@param *args: Any additional positional arguments to pass to C{func}.
@param **kw: Any additional keyword arguments to pass to C{func}.
@return: Whatever is returned by C{func}
@raise: Whatever is raised by C{func}.
"""
self.contexts.append(newContext)
try:
return func(*args,**kw)
finally:
self.contexts.pop() | Call C{func(*args, **kw)} such that the contents of C{newContext} will
be available for it to retrieve using L{getContext}.
@param newContext: A C{dict} of data to push onto the context for the
duration of the call to C{func}.
@param func: A callable which will be called.
@param *args: Any additional positional arguments to pass to C{func}.
@param **kw: Any additional keyword arguments to pass to C{func}.
@return: Whatever is returned by C{func}
@raise: Whatever is raised by C{func}. | callWithContext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/context.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/context.py | MIT |
def getContext(self, key, default=None):
"""
Retrieve the value for a key from the context.
@param key: The key to look up in the context.
@param default: The value to return if C{key} is not found in the
context.
@return: The value most recently remembered in the context for C{key}.
"""
for ctx in reversed(self.contexts):
try:
return ctx[key]
except KeyError:
pass
return default | Retrieve the value for a key from the context.
@param key: The key to look up in the context.
@param default: The value to return if C{key} is not found in the
context.
@return: The value most recently remembered in the context for C{key}. | getContext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/context.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/context.py | MIT |
def __init__(self, offset, name=None):
"""
Construct a L{FixedOffsetTimeZone} with a fixed offset.
@param offset: a delta representing the offset from UTC.
@type offset: L{timedelta}
@param name: A name to be given for this timezone.
@type name: L{str} or L{None}
"""
self.offset = offset
self.name = name | Construct a L{FixedOffsetTimeZone} with a fixed offset.
@param offset: a delta representing the offset from UTC.
@type offset: L{timedelta}
@param name: A name to be given for this timezone.
@type name: L{str} or L{None} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | MIT |
def fromSignHoursMinutes(cls, sign, hours, minutes):
"""
Construct a L{FixedOffsetTimeZone} from an offset described by sign
('+' or '-'), hours, and minutes.
@note: For protocol compatibility with AMP, this method never uses 'Z'
@param sign: A string describing the positive or negative-ness of the
offset.
@param hours: The number of hours in the offset.
@type hours: L{int}
@param minutes: The number of minutes in the offset
@type minutes: L{int}
@return: A time zone with the given offset, and a name describing the
offset.
@rtype: L{FixedOffsetTimeZone}
"""
name = "%s%02i:%02i" % (sign, hours, minutes)
if sign == "-":
hours = -hours
minutes = -minutes
elif sign != "+":
raise ValueError("Invalid sign for timezone %r" % (sign,))
return cls(timedelta(hours=hours, minutes=minutes), name) | Construct a L{FixedOffsetTimeZone} from an offset described by sign
('+' or '-'), hours, and minutes.
@note: For protocol compatibility with AMP, this method never uses 'Z'
@param sign: A string describing the positive or negative-ness of the
offset.
@param hours: The number of hours in the offset.
@type hours: L{int}
@param minutes: The number of minutes in the offset
@type minutes: L{int}
@return: A time zone with the given offset, and a name describing the
offset.
@rtype: L{FixedOffsetTimeZone} | fromSignHoursMinutes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | MIT |
def fromLocalTimeStamp(cls, timeStamp):
"""
Create a time zone with a fixed offset corresponding to a time stamp in
the system's locally configured time zone.
@param timeStamp: a time stamp
@type timeStamp: L{int}
@return: a time zone
@rtype: L{FixedOffsetTimeZone}
"""
offset = (
datetime.fromtimestamp(timeStamp) -
datetime.utcfromtimestamp(timeStamp)
)
return cls(offset) | Create a time zone with a fixed offset corresponding to a time stamp in
the system's locally configured time zone.
@param timeStamp: a time stamp
@type timeStamp: L{int}
@return: a time zone
@rtype: L{FixedOffsetTimeZone} | fromLocalTimeStamp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | MIT |
def utcoffset(self, dt):
"""
Return this timezone's offset from UTC.
"""
return self.offset | Return this timezone's offset from UTC. | utcoffset | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | MIT |
def dst(self, dt):
"""
Return a zero C{datetime.timedelta} for the daylight saving time
offset, since there is never one.
"""
return timedelta(0) | Return a zero C{datetime.timedelta} for the daylight saving time
offset, since there is never one. | dst | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | MIT |
def tzname(self, dt):
"""
Return a string describing this timezone.
"""
if self.name is not None:
return self.name
# XXX this is wrong; the tests are
dt = datetime.fromtimestamp(0, self)
return dt.strftime("UTC%z") | Return a string describing this timezone. | tzname | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/_tzhelper.py | MIT |
def format_frames(frames, write, detail="default"):
"""
Format and write frames.
@param frames: is a list of frames as used by Failure.frames, with
each frame being a list of
(funcName, fileName, lineNumber, locals.items(), globals.items())
@type frames: list
@param write: this will be called with formatted strings.
@type write: callable
@param detail: Four detail levels are available:
default, brief, verbose, and verbose-vars-not-captured.
C{Failure.printDetailedTraceback} uses the latter when the caller asks
for verbose, but no vars were captured, so that an explicit warning
about the missing data is shown.
@type detail: string
"""
if detail not in ('default', 'brief', 'verbose',
'verbose-vars-not-captured'):
raise ValueError(
"Detail must be default, brief, verbose, or "
"verbose-vars-not-captured. (not %r)" % (detail,))
w = write
if detail == "brief":
for method, filename, lineno, localVars, globalVars in frames:
w('%s:%s:%s\n' % (filename, lineno, method))
elif detail == "default":
for method, filename, lineno, localVars, globalVars in frames:
w(' File "%s", line %s, in %s\n' % (filename, lineno, method))
w(' %s\n' % linecache.getline(filename, lineno).strip())
elif detail == "verbose-vars-not-captured":
for method, filename, lineno, localVars, globalVars in frames:
w("%s:%d: %s(...)\n" % (filename, lineno, method))
w(' [Capture of Locals and Globals disabled (use captureVars=True)]\n')
elif detail == "verbose":
for method, filename, lineno, localVars, globalVars in frames:
w("%s:%d: %s(...)\n" % (filename, lineno, method))
w(' [ Locals ]\n')
# Note: the repr(val) was (self.pickled and val) or repr(val)))
for name, val in localVars:
w(" %s : %s\n" % (name, repr(val)))
w(' ( Globals )\n')
for name, val in globalVars:
w(" %s : %s\n" % (name, repr(val))) | Format and write frames.
@param frames: is a list of frames as used by Failure.frames, with
each frame being a list of
(funcName, fileName, lineNumber, locals.items(), globals.items())
@type frames: list
@param write: this will be called with formatted strings.
@type write: callable
@param detail: Four detail levels are available:
default, brief, verbose, and verbose-vars-not-captured.
C{Failure.printDetailedTraceback} uses the latter when the caller asks
for verbose, but no vars were captured, so that an explicit warning
about the missing data is shown.
@type detail: string | format_frames | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def _Traceback(stackFrames, tbFrames):
"""
Construct a fake traceback object using a list of frames. Note that
although frames generally include locals and globals, this information
is not kept by this method, since locals and globals are not used in
standard tracebacks.
@param stackFrames: [(methodname, filename, lineno, locals, globals), ...]
@param tbFrames: [(methodname, filename, lineno, locals, globals), ...]
"""
assert len(tbFrames) > 0, "Must pass some frames"
# We deliberately avoid using recursion here, as the frames list may be
# long.
# 'stackFrames' is a list of frames above (ie, older than) the point the
# exception was caught, with oldest at the start. Start by building these
# into a linked list of _Frame objects (with the f_back links pointing back
# towards the oldest frame).
stack = None
for sf in stackFrames:
stack = _Frame(sf, stack)
# 'tbFrames' is a list of frames from the point the exception was caught,
# down to where it was thrown, with the oldest at the start. Add these to
# the linked list of _Frames, but also wrap each one with a _Traceback
# frame which is linked in the opposite direction (towards the newest
# frame).
stack = _Frame(tbFrames[0], stack)
firstTb = tb = _TracebackFrame(stack)
for sf in tbFrames[1:]:
stack = _Frame(sf, stack)
tb.tb_next = _TracebackFrame(stack)
tb = tb.tb_next
# Return the first _TracebackFrame.
return firstTb | Construct a fake traceback object using a list of frames. Note that
although frames generally include locals and globals, this information
is not kept by this method, since locals and globals are not used in
standard tracebacks.
@param stackFrames: [(methodname, filename, lineno, locals, globals), ...]
@param tbFrames: [(methodname, filename, lineno, locals, globals), ...] | _Traceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def __init__(self, frame):
"""
@param frame: _Frame object
"""
self.tb_frame = frame
self.tb_lineno = frame.f_lineno
self.tb_next = None | @param frame: _Frame object | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def __init__(self, frameinfo, back):
"""
@param frameinfo: (methodname, filename, lineno, locals, globals)
@param back: previous (older) stack frame
@type back: C{frame}
"""
name, filename, lineno, localz, globalz = frameinfo
self.f_code = _Code(name, filename)
self.f_lineno = lineno
self.f_globals = {}
self.f_locals = {}
self.f_back = back | @param frameinfo: (methodname, filename, lineno, locals, globals)
@param back: previous (older) stack frame
@type back: C{frame} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def _extraneous(f):
"""
Mark the given callable as extraneous to inlineCallbacks exception
reporting; don't show these functions.
@param f: a function that you NEVER WANT TO SEE AGAIN in ANY TRACEBACK
reported by Failure.
@type f: function
@return: f
"""
_inlineCallbacksExtraneous.append(f.__code__)
return f | Mark the given callable as extraneous to inlineCallbacks exception
reporting; don't show these functions.
@param f: a function that you NEVER WANT TO SEE AGAIN in ANY TRACEBACK
reported by Failure.
@type f: function
@return: f | _extraneous | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def __init__(self, exc_value=None, exc_type=None, exc_tb=None,
captureVars=False):
"""
Initialize me with an explanation of the error.
By default, this will use the current C{exception}
(L{sys.exc_info}()). However, if you want to specify a
particular kind of failure, you can pass an exception as an
argument.
If no C{exc_value} is passed, then an "original" C{Failure} will
be searched for. If the current exception handler that this
C{Failure} is being constructed in is handling an exception
raised by L{raiseException}, then this C{Failure} will act like
the original C{Failure}.
For C{exc_tb} only L{traceback} instances or L{None} are allowed.
If L{None} is supplied for C{exc_value}, the value of C{exc_tb} is
ignored, otherwise if C{exc_tb} is L{None}, it will be found from
execution context (ie, L{sys.exc_info}).
@param captureVars: if set, capture locals and globals of stack
frames. This is pretty slow, and makes no difference unless you
are going to use L{printDetailedTraceback}.
"""
global count
count = count + 1
self.count = count
self.type = self.value = tb = None
self.captureVars = captureVars
if isinstance(exc_value, str) and exc_type is None:
raise TypeError("Strings are not supported by Failure")
stackOffset = 0
if exc_value is None:
exc_value = self._findFailure()
if exc_value is None:
self.type, self.value, tb = sys.exc_info()
if self.type is None:
raise NoCurrentExceptionError()
stackOffset = 1
elif exc_type is None:
if isinstance(exc_value, Exception):
self.type = exc_value.__class__
else:
# Allow arbitrary objects.
self.type = type(exc_value)
self.value = exc_value
else:
self.type = exc_type
self.value = exc_value
if isinstance(self.value, Failure):
self._extrapolate(self.value)
return
if hasattr(self.value, "__failure__"):
# For exceptions propagated through coroutine-awaiting (see
# Deferred.send, AKA Deferred.__next__), which can't be raised as
# Failure because that would mess up the ability to except: them:
self._extrapolate(self.value.__failure__)
# Clean up the inherently circular reference established by storing
# the failure there. This should make the common case of a Twisted
# / Deferred-returning coroutine somewhat less hard on the garbage
# collector.
del self.value.__failure__
return
if tb is None:
if exc_tb:
tb = exc_tb
elif getattr(self.value, "__traceback__", None):
# Python 3
tb = self.value.__traceback__
frames = self.frames = []
stack = self.stack = []
# Added 2003-06-23 by Chris Armstrong. Yes, I actually have a
# use case where I need this traceback object, and I've made
# sure that it'll be cleaned up.
self.tb = tb
if tb:
f = tb.tb_frame
elif not isinstance(self.value, Failure):
# We don't do frame introspection since it's expensive,
# and if we were passed a plain exception with no
# traceback, it's not useful anyway
f = stackOffset = None
while stackOffset and f:
# This excludes this Failure.__init__ frame from the
# stack, leaving it to start with our caller instead.
f = f.f_back
stackOffset -= 1
# Keeps the *full* stack. Formerly in spread.pb.print_excFullStack:
#
# The need for this function arises from the fact that several
# PB classes have the peculiar habit of discarding exceptions
# with bareword "except:"s. This premature exception
# catching means tracebacks generated here don't tend to show
# what called upon the PB object.
while f:
if captureVars:
localz = f.f_locals.copy()
if f.f_locals is f.f_globals:
globalz = {}
else:
globalz = f.f_globals.copy()
for d in globalz, localz:
if "__builtins__" in d:
del d["__builtins__"]
localz = localz.items()
globalz = globalz.items()
else:
localz = globalz = ()
stack.insert(0, (
f.f_code.co_name,
f.f_code.co_filename,
f.f_lineno,
localz,
globalz,
))
f = f.f_back
while tb is not None:
f = tb.tb_frame
if captureVars:
localz = f.f_locals.copy()
if f.f_locals is f.f_globals:
globalz = {}
else:
globalz = f.f_globals.copy()
for d in globalz, localz:
if "__builtins__" in d:
del d["__builtins__"]
localz = list(localz.items())
globalz = list(globalz.items())
else:
localz = globalz = ()
frames.append((
f.f_code.co_name,
f.f_code.co_filename,
tb.tb_lineno,
localz,
globalz,
))
tb = tb.tb_next
if inspect.isclass(self.type) and issubclass(self.type, Exception):
parentCs = getmro(self.type)
self.parents = list(map(reflect.qual, parentCs))
else:
self.parents = [self.type] | Initialize me with an explanation of the error.
By default, this will use the current C{exception}
(L{sys.exc_info}()). However, if you want to specify a
particular kind of failure, you can pass an exception as an
argument.
If no C{exc_value} is passed, then an "original" C{Failure} will
be searched for. If the current exception handler that this
C{Failure} is being constructed in is handling an exception
raised by L{raiseException}, then this C{Failure} will act like
the original C{Failure}.
For C{exc_tb} only L{traceback} instances or L{None} are allowed.
If L{None} is supplied for C{exc_value}, the value of C{exc_tb} is
ignored, otherwise if C{exc_tb} is L{None}, it will be found from
execution context (ie, L{sys.exc_info}).
@param captureVars: if set, capture locals and globals of stack
frames. This is pretty slow, and makes no difference unless you
are going to use L{printDetailedTraceback}. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def _extrapolate(self, otherFailure):
"""
Extrapolate from one failure into another, copying its stack frames.
@param otherFailure: Another L{Failure}, whose traceback information,
if any, should be preserved as part of the stack presented by this
one.
@type otherFailure: L{Failure}
"""
# Copy all infos from that failure (including self.frames).
self.__dict__ = copy.copy(otherFailure.__dict__)
# If we are re-throwing a Failure, we merge the stack-trace stored in
# the failure with the current exception's stack. This integrated with
# throwExceptionIntoGenerator and allows to provide full stack trace,
# even if we go through several layers of inlineCallbacks.
_, _, tb = sys.exc_info()
frames = []
while tb is not None:
f = tb.tb_frame
if f.f_code not in _inlineCallbacksExtraneous:
frames.append((
f.f_code.co_name,
f.f_code.co_filename,
tb.tb_lineno, (), ()
))
tb = tb.tb_next
# Merging current stack with stack stored in the Failure.
frames.extend(self.frames)
self.frames = frames | Extrapolate from one failure into another, copying its stack frames.
@param otherFailure: Another L{Failure}, whose traceback information,
if any, should be preserved as part of the stack presented by this
one.
@type otherFailure: L{Failure} | _extrapolate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def trap(self, *errorTypes):
"""
Trap this failure if its type is in a predetermined list.
This allows you to trap a Failure in an error callback. It will be
automatically re-raised if it is not a type that you expect.
The reason for having this particular API is because it's very useful
in Deferred errback chains::
def _ebFoo(self, failure):
r = failure.trap(Spam, Eggs)
print('The Failure is due to either Spam or Eggs!')
if r == Spam:
print('Spam did it!')
elif r == Eggs:
print('Eggs did it!')
If the failure is not a Spam or an Eggs, then the Failure will be
'passed on' to the next errback. In Python 2 the Failure will be
raised; in Python 3 the underlying exception will be re-raised.
@type errorTypes: L{Exception}
"""
error = self.check(*errorTypes)
if not error:
if _PY3:
self.raiseException()
else:
raise self
return error | Trap this failure if its type is in a predetermined list.
This allows you to trap a Failure in an error callback. It will be
automatically re-raised if it is not a type that you expect.
The reason for having this particular API is because it's very useful
in Deferred errback chains::
def _ebFoo(self, failure):
r = failure.trap(Spam, Eggs)
print('The Failure is due to either Spam or Eggs!')
if r == Spam:
print('Spam did it!')
elif r == Eggs:
print('Eggs did it!')
If the failure is not a Spam or an Eggs, then the Failure will be
'passed on' to the next errback. In Python 2 the Failure will be
raised; in Python 3 the underlying exception will be re-raised.
@type errorTypes: L{Exception} | trap | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def check(self, *errorTypes):
"""
Check if this failure's type is in a predetermined list.
@type errorTypes: list of L{Exception} classes or
fully-qualified class names.
@returns: the matching L{Exception} type, or None if no match.
"""
for error in errorTypes:
err = error
if inspect.isclass(error) and issubclass(error, Exception):
err = reflect.qual(error)
if err in self.parents:
return error
return None | Check if this failure's type is in a predetermined list.
@type errorTypes: list of L{Exception} classes or
fully-qualified class names.
@returns: the matching L{Exception} type, or None if no match. | check | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def throwExceptionIntoGenerator(self, g):
"""
Throw the original exception into the given generator,
preserving traceback information if available.
@return: The next value yielded from the generator.
@raise StopIteration: If there are no more values in the generator.
@raise anything else: Anything that the generator raises.
"""
# Note that the actual magic to find the traceback information
# is done in _findFailure.
return g.throw(self.type, self.value, self.tb) | Throw the original exception into the given generator,
preserving traceback information if available.
@return: The next value yielded from the generator.
@raise StopIteration: If there are no more values in the generator.
@raise anything else: Anything that the generator raises. | throwExceptionIntoGenerator | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def _findFailure(cls):
"""
Find the failure that represents the exception currently in context.
"""
tb = sys.exc_info()[-1]
if not tb:
return
secondLastTb = None
lastTb = tb
while lastTb.tb_next:
secondLastTb = lastTb
lastTb = lastTb.tb_next
lastFrame = lastTb.tb_frame
# NOTE: f_locals.get('self') is used rather than
# f_locals['self'] because psyco frames do not contain
# anything in their locals() dicts. psyco makes debugging
# difficult anyhow, so losing the Failure objects (and thus
# the tracebacks) here when it is used is not that big a deal.
# Handle raiseException-originated exceptions
if lastFrame.f_code is cls.raiseException.__code__:
return lastFrame.f_locals.get('self')
# Handle throwExceptionIntoGenerator-originated exceptions
# this is tricky, and differs if the exception was caught
# inside the generator, or above it:
# It is only really originating from
# throwExceptionIntoGenerator if the bottom of the traceback
# is a yield.
# Pyrex and Cython extensions create traceback frames
# with no co_code, but they can't yield so we know it's okay to
# just return here.
if ((not lastFrame.f_code.co_code) or
lastFrame.f_code.co_code[lastTb.tb_lasti] != cls._yieldOpcode):
return
# If the exception was caught above the generator.throw
# (outside the generator), it will appear in the tb (as the
# second last item):
if secondLastTb:
frame = secondLastTb.tb_frame
if frame.f_code is cls.throwExceptionIntoGenerator.__code__:
return frame.f_locals.get('self')
# If the exception was caught below the generator.throw
# (inside the generator), it will appear in the frames' linked
# list, above the top-level traceback item (which must be the
# generator frame itself, thus its caller is
# throwExceptionIntoGenerator).
frame = tb.tb_frame.f_back
if frame and frame.f_code is cls.throwExceptionIntoGenerator.__code__:
return frame.f_locals.get('self') | Find the failure that represents the exception currently in context. | _findFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def __getstate__(self):
"""Avoid pickling objects in the traceback.
"""
if self.pickled:
return self.__dict__
c = self.__dict__.copy()
c['frames'] = [
[
v[0], v[1], v[2],
_safeReprVars(v[3]),
_safeReprVars(v[4]),
] for v in self.frames
]
# Added 2003-06-23. See comment above in __init__
c['tb'] = None
if self.stack is not None:
# XXX: This is a band-aid. I can't figure out where these
# (failure.stack is None) instances are coming from.
c['stack'] = [
[
v[0], v[1], v[2],
_safeReprVars(v[3]),
_safeReprVars(v[4]),
] for v in self.stack
]
c['pickled'] = 1
return c | Avoid pickling objects in the traceback. | __getstate__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def cleanFailure(self):
"""
Remove references to other objects, replacing them with strings.
On Python 3, this will also set the C{__traceback__} attribute of the
exception instance to L{None}.
"""
self.__dict__ = self.__getstate__()
if getattr(self.value, "__traceback__", None):
# Python 3
self.value.__traceback__ = None | Remove references to other objects, replacing them with strings.
On Python 3, this will also set the C{__traceback__} attribute of the
exception instance to L{None}. | cleanFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def getTracebackObject(self):
"""
Get an object that represents this Failure's stack that can be passed
to traceback.extract_tb.
If the original traceback object is still present, return that. If this
traceback object has been lost but we still have the information,
return a fake traceback object (see L{_Traceback}). If there is no
traceback information at all, return None.
"""
if self.tb is not None:
return self.tb
elif len(self.frames) > 0:
return _Traceback(self.stack, self.frames)
else:
return None | Get an object that represents this Failure's stack that can be passed
to traceback.extract_tb.
If the original traceback object is still present, return that. If this
traceback object has been lost but we still have the information,
return a fake traceback object (see L{_Traceback}). If there is no
traceback information at all, return None. | getTracebackObject | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def getErrorMessage(self):
"""
Get a string of the exception which caused this Failure.
"""
if isinstance(self.value, Failure):
return self.value.getErrorMessage()
return reflect.safe_str(self.value) | Get a string of the exception which caused this Failure. | getErrorMessage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def printTraceback(self, file=None, elideFrameworkCode=False,
detail='default'):
"""
Emulate Python's standard error reporting mechanism.
@param file: If specified, a file-like object to which to write the
traceback.
@param elideFrameworkCode: A flag indicating whether to attempt to
remove uninteresting frames from within Twisted itself from the
output.
@param detail: A string indicating how much information to include
in the traceback. Must be one of C{'brief'}, C{'default'}, or
C{'verbose'}.
"""
if file is None:
from twisted.python import log
file = log.logerr
w = file.write
if detail == 'verbose' and not self.captureVars:
# We don't have any locals or globals, so rather than show them as
# empty make the output explicitly say that we don't have them at
# all.
formatDetail = 'verbose-vars-not-captured'
else:
formatDetail = detail
# Preamble
if detail == 'verbose':
w('*--- Failure #%d%s---\n' %
(self.count,
(self.pickled and ' (pickled) ') or ' '))
elif detail == 'brief':
if self.frames:
hasFrames = 'Traceback'
else:
hasFrames = 'Traceback (failure with no frames)'
w("%s: %s: %s\n" % (
hasFrames,
reflect.safe_str(self.type),
reflect.safe_str(self.value)))
else:
w('Traceback (most recent call last):\n')
# Frames, formatted in appropriate style
if self.frames:
if not elideFrameworkCode:
format_frames(self.stack[-traceupLength:], w, formatDetail)
w("%s\n" % (EXCEPTION_CAUGHT_HERE,))
format_frames(self.frames, w, formatDetail)
elif not detail == 'brief':
# Yeah, it's not really a traceback, despite looking like one...
w("Failure: ")
# Postamble, if any
if not detail == 'brief':
w("%s: %s\n" % (reflect.qual(self.type),
reflect.safe_str(self.value)))
# Chaining
if isinstance(self.value, Failure):
# TODO: indentation for chained failures?
file.write(" (chained Failure)\n")
self.value.printTraceback(file, elideFrameworkCode, detail)
if detail == 'verbose':
w('*--- End of Failure #%d ---\n' % self.count) | Emulate Python's standard error reporting mechanism.
@param file: If specified, a file-like object to which to write the
traceback.
@param elideFrameworkCode: A flag indicating whether to attempt to
remove uninteresting frames from within Twisted itself from the
output.
@param detail: A string indicating how much information to include
in the traceback. Must be one of C{'brief'}, C{'default'}, or
C{'verbose'}. | printTraceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def printBriefTraceback(self, file=None, elideFrameworkCode=0):
"""
Print a traceback as densely as possible.
"""
self.printTraceback(file, elideFrameworkCode, detail='brief') | Print a traceback as densely as possible. | printBriefTraceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def printDetailedTraceback(self, file=None, elideFrameworkCode=0):
"""
Print a traceback with detailed locals and globals information.
"""
self.printTraceback(file, elideFrameworkCode, detail='verbose') | Print a traceback with detailed locals and globals information. | printDetailedTraceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def _safeReprVars(varsDictItems):
"""
Convert a list of (name, object) pairs into (name, repr) pairs.
L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
exceptions will be raised by faulty C{__repr__} methods.
@param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
C{locals().items()}.
@returns: a sequence of (name, repr) pairs.
"""
return [(name, reflect.safe_repr(obj)) for (name, obj) in varsDictItems] | Convert a list of (name, object) pairs into (name, repr) pairs.
L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
exceptions will be raised by faulty C{__repr__} methods.
@param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
C{locals().items()}.
@returns: a sequence of (name, repr) pairs. | _safeReprVars | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None,
captureVars=False,
Failure__init__=Failure.__init__):
"""
Initialize failure object, possibly spawning pdb.
"""
if (exc_value, exc_type, exc_tb) == (None, None, None):
exc = sys.exc_info()
if not exc[0] == self.__class__ and DO_POST_MORTEM:
try:
strrepr = str(exc[1])
except:
strrepr = "broken str"
print("Jumping into debugger for post-mortem of exception '%s':" %
(strrepr,))
import pdb
pdb.post_mortem(exc[2])
Failure__init__(self, exc_value, exc_type, exc_tb, captureVars) | Initialize failure object, possibly spawning pdb. | _debuginit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def startDebugMode():
"""
Enable debug hooks for Failures.
"""
Failure.__init__ = _debuginit | Enable debug hooks for Failures. | startDebugMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/failure.py | MIT |
def __call__(eventDict):
"""
Log an event.
@type eventDict: C{dict} with C{str} keys.
@param eventDict: A dictionary with arbitrary keys. However, these
keys are often available:
- C{message}: A C{tuple} of C{str} containing messages to be
logged.
- C{system}: A C{str} which indicates the "system" which is
generating this event.
- C{isError}: A C{bool} indicating whether this event represents
an error.
- C{failure}: A L{failure.Failure} instance
- C{why}: Used as header of the traceback in case of errors.
- C{format}: A string format used in place of C{message} to
customize the event. The intent is for the observer to format
a message by doing something like C{format % eventDict}.
""" | Log an event.
@type eventDict: C{dict} with C{str} keys.
@param eventDict: A dictionary with arbitrary keys. However, these
keys are often available:
- C{message}: A C{tuple} of C{str} containing messages to be
logged.
- C{system}: A C{str} which indicates the "system" which is
generating this event.
- C{isError}: A C{bool} indicating whether this event represents
an error.
- C{failure}: A L{failure.Failure} instance
- C{why}: Used as header of the traceback in case of errors.
- C{format}: A string format used in place of C{message} to
customize the event. The intent is for the observer to format
a message by doing something like C{format % eventDict}. | __call__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def callWithLogger(logger, func, *args, **kw):
"""
Utility method which wraps a function in a try:/except:, logs a failure if
one occurs, and uses the system's logPrefix.
"""
try:
lp = logger.logPrefix()
except KeyboardInterrupt:
raise
except:
lp = '(buggy logPrefix method)'
err(system=lp)
try:
return callWithContext({"system": lp}, func, *args, **kw)
except KeyboardInterrupt:
raise
except:
err(system=lp) | Utility method which wraps a function in a try:/except:, logs a failure if
one occurs, and uses the system's logPrefix. | callWithLogger | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def observers(self):
"""
Property returning all observers registered on this L{LogPublisher}.
@return: observers previously added with L{LogPublisher.addObserver}
@rtype: L{list} of L{callable}
"""
return [x.legacyObserver for x in self._legacyObservers] | Property returning all observers registered on this L{LogPublisher}.
@return: observers previously added with L{LogPublisher.addObserver}
@rtype: L{list} of L{callable} | observers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def _startLogging(self, other, setStdout):
"""
Begin logging to the L{LogBeginner} associated with this
L{LogPublisher}.
@param other: the observer to log to.
@type other: L{LogBeginner}
@param setStdout: if true, send standard I/O to the observer as well.
@type setStdout: L{bool}
"""
wrapped = LegacyLogObserverWrapper(other)
self._legacyObservers.append(wrapped)
self._logBeginner.beginLoggingTo([wrapped], True, setStdout) | Begin logging to the L{LogBeginner} associated with this
L{LogPublisher}.
@param other: the observer to log to.
@type other: L{LogBeginner}
@param setStdout: if true, send standard I/O to the observer as well.
@type setStdout: L{bool} | _startLogging | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def _stopLogging(self):
"""
Clean-up hook for fixing potentially global state. Only for testing of
this module itself. If you want less global state, use the new
warnings system in L{twisted.logger}.
"""
if self._warningsModule.showwarning == self.showwarning:
self._warningsModule.showwarning = self._oldshowwarning | Clean-up hook for fixing potentially global state. Only for testing of
this module itself. If you want less global state, use the new
warnings system in L{twisted.logger}. | _stopLogging | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def addObserver(self, other):
"""
Add a new observer.
@type other: Provider of L{ILogObserver}
@param other: A callable object that will be called with each new log
message (a dict).
"""
wrapped = LegacyLogObserverWrapper(other)
self._legacyObservers.append(wrapped)
self._observerPublisher.addObserver(wrapped) | Add a new observer.
@type other: Provider of L{ILogObserver}
@param other: A callable object that will be called with each new log
message (a dict). | addObserver | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def removeObserver(self, other):
"""
Remove an observer.
"""
for observer in self._legacyObservers:
if observer.legacyObserver == other:
self._legacyObservers.remove(observer)
self._observerPublisher.removeObserver(observer)
break | Remove an observer. | removeObserver | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def msg(self, *message, **kw):
"""
Log a new message.
The message should be a native string, i.e. bytes on Python 2 and
Unicode on Python 3. For compatibility with both use the native string
syntax, for example::
>>> log.msg('Hello, world.')
You MUST avoid passing in Unicode on Python 2, and the form::
>>> log.msg('Hello ', 'world.')
This form only works (sometimes) by accident.
Keyword arguments will be converted into items in the event
dict that is passed to L{ILogObserver} implementations.
Each implementation, in turn, can define keys that are used
by it specifically, in addition to common keys listed at
L{ILogObserver.__call__}.
For example, to set the C{system} parameter while logging
a message::
>>> log.msg('Started', system='Foo')
"""
actualEventDict = (context.get(ILogContext) or {}).copy()
actualEventDict.update(kw)
actualEventDict['message'] = message
actualEventDict['time'] = time.time()
if "isError" not in actualEventDict:
actualEventDict["isError"] = 0
_publishNew(self._publishPublisher, actualEventDict, textFromEventDict) | Log a new message.
The message should be a native string, i.e. bytes on Python 2 and
Unicode on Python 3. For compatibility with both use the native string
syntax, for example::
>>> log.msg('Hello, world.')
You MUST avoid passing in Unicode on Python 2, and the form::
>>> log.msg('Hello ', 'world.')
This form only works (sometimes) by accident.
Keyword arguments will be converted into items in the event
dict that is passed to L{ILogObserver} implementations.
Each implementation, in turn, can define keys that are used
by it specifically, in addition to common keys listed at
L{ILogObserver.__call__}.
For example, to set the C{system} parameter while logging
a message::
>>> log.msg('Started', system='Foo') | msg | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def _actually(something):
"""
A decorator that returns its argument rather than the thing it is
decorating.
This allows the documentation generator to see an alias for a method or
constant as an object with a docstring and thereby document it and
allow references to it statically.
@param something: An object to create an alias for.
@type something: L{object}
@return: a 1-argument callable that returns C{something}
@rtype: L{object}
"""
def decorate(thingWithADocstring):
return something
return decorate | A decorator that returns its argument rather than the thing it is
decorating.
This allows the documentation generator to see an alias for a method or
constant as an object with a docstring and thereby document it and
allow references to it statically.
@param something: An object to create an alias for.
@type something: L{object}
@return: a 1-argument callable that returns C{something}
@rtype: L{object} | _actually | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def addObserver(observer):
"""
Add a log observer to the global publisher.
@see: L{LogPublisher.addObserver}
@param observer: a log observer
@type observer: L{callable}
""" | Add a log observer to the global publisher.
@see: L{LogPublisher.addObserver}
@param observer: a log observer
@type observer: L{callable} | addObserver | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def removeObserver(observer):
"""
Remove a log observer from the global publisher.
@see: L{LogPublisher.removeObserver}
@param observer: a log observer previously added with L{addObserver}
@type observer: L{callable}
""" | Remove a log observer from the global publisher.
@see: L{LogPublisher.removeObserver}
@param observer: a log observer previously added with L{addObserver}
@type observer: L{callable} | removeObserver | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def msg(*message, **event):
"""
Publish a message to the global log publisher.
@see: L{LogPublisher.msg}
@param message: the log message
@type message: C{tuple} of L{str} (native string)
@param event: fields for the log event
@type event: L{dict} mapping L{str} (native string) to L{object}
""" | Publish a message to the global log publisher.
@see: L{LogPublisher.msg}
@param message: the log message
@type message: C{tuple} of L{str} (native string)
@param event: fields for the log event
@type event: L{dict} mapping L{str} (native string) to L{object} | msg | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def showwarning():
"""
Publish a Python warning through the global log publisher.
@see: L{LogPublisher.showwarning}
""" | Publish a Python warning through the global log publisher.
@see: L{LogPublisher.showwarning} | showwarning | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def _safeFormat(fmtString, fmtDict):
"""
Try to format a string, swallowing all errors to always return a string.
@note: For backward-compatibility reasons, this function ensures that it
returns a native string, meaning C{bytes} in Python 2 and C{unicode} in
Python 3.
@param fmtString: a C{%}-format string
@param fmtDict: string formatting arguments for C{fmtString}
@return: A native string, formatted from C{fmtString} and C{fmtDict}.
@rtype: L{str}
"""
# There's a way we could make this if not safer at least more
# informative: perhaps some sort of str/repr wrapper objects
# could be wrapped around the things inside of C{fmtDict}. That way
# if the event dict contains an object with a bad __repr__, we
# can only cry about that individual object instead of the
# entire event dict.
try:
text = fmtString % fmtDict
except KeyboardInterrupt:
raise
except:
try:
text = ('Invalid format string or unformattable object in '
'log message: %r, %s' % (fmtString, fmtDict))
except:
try:
text = ('UNFORMATTABLE OBJECT WRITTEN TO LOG with fmt %r, '
'MESSAGE LOST' % (fmtString,))
except:
text = ('PATHOLOGICAL ERROR IN BOTH FORMAT STRING AND '
'MESSAGE DETAILS, MESSAGE LOST')
# Return a native string
if _PY3:
if isinstance(text, bytes):
text = text.decode("utf-8")
else:
if isinstance(text, unicode):
text = text.encode("utf-8")
return text | Try to format a string, swallowing all errors to always return a string.
@note: For backward-compatibility reasons, this function ensures that it
returns a native string, meaning C{bytes} in Python 2 and C{unicode} in
Python 3.
@param fmtString: a C{%}-format string
@param fmtDict: string formatting arguments for C{fmtString}
@return: A native string, formatted from C{fmtString} and C{fmtDict}.
@rtype: L{str} | _safeFormat | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def textFromEventDict(eventDict):
"""
Extract text from an event dict passed to a log observer. If it cannot
handle the dict, it returns None.
The possible keys of eventDict are:
- C{message}: by default, it holds the final text. It's required, but can
be empty if either C{isError} or C{format} is provided (the first
having the priority).
- C{isError}: boolean indicating the nature of the event.
- C{failure}: L{failure.Failure} instance, required if the event is an
error.
- C{why}: if defined, used as header of the traceback in case of errors.
- C{format}: string format used in place of C{message} to customize
the event. It uses all keys present in C{eventDict} to format
the text.
Other keys will be used when applying the C{format}, or ignored.
"""
edm = eventDict['message']
if not edm:
if eventDict['isError'] and 'failure' in eventDict:
why = eventDict.get('why')
if why:
why = reflect.safe_str(why)
else:
why = 'Unhandled Error'
try:
traceback = eventDict['failure'].getTraceback()
except Exception as e:
traceback = '(unable to obtain traceback): ' + str(e)
text = (why + '\n' + traceback)
elif 'format' in eventDict:
text = _safeFormat(eventDict['format'], eventDict)
else:
# We don't know how to log this
return None
else:
text = ' '.join(map(reflect.safe_str, edm))
return text | Extract text from an event dict passed to a log observer. If it cannot
handle the dict, it returns None.
The possible keys of eventDict are:
- C{message}: by default, it holds the final text. It's required, but can
be empty if either C{isError} or C{format} is provided (the first
having the priority).
- C{isError}: boolean indicating the nature of the event.
- C{failure}: L{failure.Failure} instance, required if the event is an
error.
- C{why}: if defined, used as header of the traceback in case of errors.
- C{format}: string format used in place of C{message} to customize
the event. It uses all keys present in C{eventDict} to format
the text.
Other keys will be used when applying the C{format}, or ignored. | textFromEventDict | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def getTimezoneOffset(self, when):
"""
Return the current local timezone offset from UTC.
@type when: C{int}
@param when: POSIX (ie, UTC) timestamp for which to find the offset.
@rtype: C{int}
@return: The number of seconds offset from UTC. West is positive,
east is negative.
"""
offset = datetime.utcfromtimestamp(when) - datetime.fromtimestamp(when)
return offset.days * (60 * 60 * 24) + offset.seconds | Return the current local timezone offset from UTC.
@type when: C{int}
@param when: POSIX (ie, UTC) timestamp for which to find the offset.
@rtype: C{int}
@return: The number of seconds offset from UTC. West is positive,
east is negative. | getTimezoneOffset | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def formatTime(self, when):
"""
Format the given UTC value as a string representing that time in the
local timezone.
By default it's formatted as an ISO8601-like string (ISO8601 date and
ISO8601 time separated by a space). It can be customized using the
C{timeFormat} attribute, which will be used as input for the underlying
L{datetime.datetime.strftime} call.
@type when: C{int}
@param when: POSIX (ie, UTC) timestamp for which to find the offset.
@rtype: C{str}
"""
if self.timeFormat is not None:
return datetime.fromtimestamp(when).strftime(self.timeFormat)
tzOffset = -self.getTimezoneOffset(when)
when = datetime.utcfromtimestamp(when + tzOffset)
tzHour = abs(int(tzOffset / 60 / 60))
tzMin = abs(int(tzOffset / 60 % 60))
if tzOffset < 0:
tzSign = '-'
else:
tzSign = '+'
return '%d-%02d-%02d %02d:%02d:%02d%s%02d%02d' % (
when.year, when.month, when.day,
when.hour, when.minute, when.second,
tzSign, tzHour, tzMin) | Format the given UTC value as a string representing that time in the
local timezone.
By default it's formatted as an ISO8601-like string (ISO8601 date and
ISO8601 time separated by a space). It can be customized using the
C{timeFormat} attribute, which will be used as input for the underlying
L{datetime.datetime.strftime} call.
@type when: C{int}
@param when: POSIX (ie, UTC) timestamp for which to find the offset.
@rtype: C{str} | formatTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def emit(self, eventDict):
"""
Format the given log event as text and write it to the output file.
@param eventDict: a log event
@type eventDict: L{dict} mapping L{str} (native string) to L{object}
"""
text = textFromEventDict(eventDict)
if text is None:
return
timeStr = self.formatTime(eventDict["time"])
fmtDict = {
"system": eventDict["system"],
"text": text.replace("\n", "\n\t")
}
msgStr = _safeFormat("[%(system)s] %(text)s\n", fmtDict)
util.untilConcludes(self.write, timeStr + " " + msgStr)
util.untilConcludes(self.flush) # Hoorj! | Format the given log event as text and write it to the output file.
@param eventDict: a log event
@type eventDict: L{dict} mapping L{str} (native string) to L{object} | emit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def __init__(self, loggerName="twisted"):
"""
@param loggerName: identifier used for getting logger.
@type loggerName: C{str}
"""
self._newObserver = NewSTDLibLogObserver(loggerName) | @param loggerName: identifier used for getting logger.
@type loggerName: C{str} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def emit(self, eventDict):
"""
Receive a twisted log entry, format it and bridge it to python.
By default the logging level used is info; log.err produces error
level, and you can customize the level by using the C{logLevel} key::
>>> log.msg('debugging', logLevel=logging.DEBUG)
"""
if 'log_format' in eventDict:
_publishNew(self._newObserver, eventDict, textFromEventDict) | Receive a twisted log entry, format it and bridge it to python.
By default the logging level used is info; log.err produces error
level, and you can customize the level by using the C{logLevel} key::
>>> log.msg('debugging', logLevel=logging.DEBUG) | emit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def startLogging(file, *a, **kw):
"""
Initialize logging to a specified file.
@return: A L{FileLogObserver} if a new observer is added, None otherwise.
"""
if isinstance(file, LoggingFile):
return
flo = FileLogObserver(file)
startLoggingWithObserver(flo.emit, *a, **kw)
return flo | Initialize logging to a specified file.
@return: A L{FileLogObserver} if a new observer is added, None otherwise. | startLogging | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def startLoggingWithObserver(observer, setStdout=1):
"""
Initialize logging to a specified observer. If setStdout is true
(defaults to yes), also redirect sys.stdout and sys.stderr
to the specified file.
"""
theLogPublisher._startLogging(observer, setStdout)
msg("Log opened.") | Initialize logging to a specified observer. If setStdout is true
(defaults to yes), also redirect sys.stdout and sys.stderr
to the specified file. | startLoggingWithObserver | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def write(self, bytes):
"""
Do nothing.
@param bytes: data
@type bytes: L{bytes}
""" | Do nothing.
@param bytes: data
@type bytes: L{bytes} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def discardLogs():
"""
Discard messages logged via the global C{logfile} object.
"""
global logfile
logfile = NullFile() | Discard messages logged via the global C{logfile} object. | discardLogs | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def emit(self, eventDict):
"""
Emit an event dict.
@param eventDict: an event dict
@type eventDict: dict
"""
if eventDict["isError"]:
text = textFromEventDict(eventDict)
self.stderr.write(text)
self.stderr.flush() | Emit an event dict.
@param eventDict: an event dict
@type eventDict: dict | emit | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/log.py | MIT |
def sendmsg(socket, data, ancillary=[], flags=0):
"""
Send a message on a socket.
@param socket: The socket to send the message on.
@type socket: L{socket.socket}
@param data: Bytes to write to the socket.
@type data: bytes
@param ancillary: Extra data to send over the socket outside of the normal
datagram or stream mechanism. By default no ancillary data is sent.
@type ancillary: C{list} of C{tuple} of C{int}, C{int}, and C{bytes}.
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@type flags: C{int}
@return: The return value of the underlying syscall, if it succeeds.
"""
if _PY3:
return socket.sendmsg([data], ancillary, flags)
else:
return send1msg(socket.fileno(), data, flags, ancillary) | Send a message on a socket.
@param socket: The socket to send the message on.
@type socket: L{socket.socket}
@param data: Bytes to write to the socket.
@type data: bytes
@param ancillary: Extra data to send over the socket outside of the normal
datagram or stream mechanism. By default no ancillary data is sent.
@type ancillary: C{list} of C{tuple} of C{int}, C{int}, and C{bytes}.
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@type flags: C{int}
@return: The return value of the underlying syscall, if it succeeds. | sendmsg | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/sendmsg.py | MIT |
def recvmsg(socket, maxSize=8192, cmsgSize=4096, flags=0):
"""
Receive a message on a socket.
@param socket: The socket to receive the message on.
@type socket: L{socket.socket}
@param maxSize: The maximum number of bytes to receive from the socket using
the datagram or stream mechanism. The default maximum is 8192.
@type maxSize: L{int}
@param cmsgSize: The maximum number of bytes to receive from the socket
outside of the normal datagram or stream mechanism. The default maximum
is 4096.
@type cmsgSize: L{int}
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@type flags: L{int}
@return: A named 3-tuple of the bytes received using the datagram/stream
mechanism, a L{list} of L{tuple}s giving ancillary received data, and
flags as an L{int} describing the data received.
"""
if _PY3:
# In Twisted's sendmsg.c, the csmg_space is defined as:
# int cmsg_size = 4096;
# cmsg_space = CMSG_SPACE(cmsg_size);
# Since the default in Python 3's socket is 0, we need to define our
# own default of 4096. -hawkie
data, ancillary, flags = socket.recvmsg(
maxSize, CMSG_SPACE(cmsgSize), flags)[0:3]
else:
data, flags, ancillary = recv1msg(
socket.fileno(), flags, maxSize, cmsgSize)
return RecievedMessage(data=data, ancillary=ancillary, flags=flags) | Receive a message on a socket.
@param socket: The socket to receive the message on.
@type socket: L{socket.socket}
@param maxSize: The maximum number of bytes to receive from the socket using
the datagram or stream mechanism. The default maximum is 8192.
@type maxSize: L{int}
@param cmsgSize: The maximum number of bytes to receive from the socket
outside of the normal datagram or stream mechanism. The default maximum
is 4096.
@type cmsgSize: L{int}
@param flags: Flags to affect how the message is sent. See the C{MSG_}
constants in the sendmsg(2) manual page. By default no flags are set.
@type flags: L{int}
@return: A named 3-tuple of the bytes received using the datagram/stream
mechanism, a L{list} of L{tuple}s giving ancillary received data, and
flags as an L{int} describing the data received. | recvmsg | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/sendmsg.py | MIT |
def getSocketFamily(socket):
"""
Return the family of the given socket.
@param socket: The socket to get the family of.
@type socket: L{socket.socket}
@rtype: L{int}
"""
if _PY3:
return socket.family
else:
return getsockfam(socket.fileno()) | Return the family of the given socket.
@param socket: The socket to get the family of.
@type socket: L{socket.socket}
@rtype: L{int} | getSocketFamily | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/sendmsg.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/sendmsg.py | MIT |
def test_exist(self):
"""
All modules listed in L{notPortedModules} exist on Py2.
"""
root = os.path.dirname(os.path.dirname(twisted.__file__))
for module in notPortedModules:
segments = module.split(".")
segments[-1] += ".py"
path = os.path.join(root, *segments)
alternateSegments = module.split(".") + ["__init__.py"]
packagePath = os.path.join(root, *alternateSegments)
self.assertTrue(os.path.exists(path) or
os.path.exists(packagePath),
"Module {0} does not exist".format(module)) | All modules listed in L{notPortedModules} exist on Py2. | test_exist | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_dist3.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_dist3.py | MIT |
def test_notexist(self):
"""
All modules listed in L{notPortedModules} do not exist on Py3.
"""
root = os.path.dirname(os.path.dirname(twisted.__file__))
for module in notPortedModules:
segments = module.split(".")
segments[-1] += ".py"
path = os.path.join(root, *segments)
alternateSegments = module.split(".") + ["__init__.py"]
packagePath = os.path.join(root, *alternateSegments)
self.assertFalse(os.path.exists(path) or
os.path.exists(packagePath),
"Module {0} exists".format(module)) | All modules listed in L{notPortedModules} do not exist on Py3. | test_notexist | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_dist3.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_dist3.py | MIT |
def replaceSysPath(self, sysPath):
"""
Replace sys.path, for the duration of the test, with the given value.
"""
originalSysPath = sys.path[:]
def cleanUpSysPath():
sys.path[:] = originalSysPath
self.addCleanup(cleanUpSysPath)
sys.path[:] = sysPath | Replace sys.path, for the duration of the test, with the given value. | replaceSysPath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/modules_helpers.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/modules_helpers.py | MIT |
def replaceSysModules(self, sysModules):
"""
Replace sys.modules, for the duration of the test, with the given value.
"""
originalSysModules = sys.modules.copy()
def cleanUpSysModules():
sys.modules.clear()
sys.modules.update(originalSysModules)
self.addCleanup(cleanUpSysModules)
sys.modules.clear()
sys.modules.update(sysModules) | Replace sys.modules, for the duration of the test, with the given value. | replaceSysModules | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/modules_helpers.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/modules_helpers.py | MIT |
def pathEntryWithOnePackage(self, pkgname="test_package"):
"""
Generate a L{FilePath} with one package, named C{pkgname}, on it, and
return the L{FilePath} of the path entry.
"""
entry = FilePath(self.mktemp())
pkg = entry.child("test_package")
pkg.makedirs()
pkg.child("__init__.py").setContent(b"")
return entry | Generate a L{FilePath} with one package, named C{pkgname}, on it, and
return the L{FilePath} of the path entry. | pathEntryWithOnePackage | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/modules_helpers.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/modules_helpers.py | MIT |
def test_shortPythonVersion(self):
"""
Verify if the Python version is returned correctly.
"""
ver = shortPythonVersion().split('.')
for i in range(3):
self.assertEqual(int(ver[i]), sys.version_info[i]) | Verify if the Python version is returned correctly. | test_shortPythonVersion | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isKnown(self):
"""
L{Platform.isKnown} returns a boolean indicating whether this is one of
the L{runtime.knownPlatforms}.
"""
platform = Platform()
self.assertTrue(platform.isKnown()) | L{Platform.isKnown} returns a boolean indicating whether this is one of
the L{runtime.knownPlatforms}. | test_isKnown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isVistaConsistency(self):
"""
Verify consistency of L{Platform.isVista}: it can only be C{True} if
L{Platform.isWinNT} and L{Platform.isWindows} are C{True}.
"""
platform = Platform()
if platform.isVista():
self.assertTrue(platform.isWinNT())
self.assertTrue(platform.isWindows())
self.assertFalse(platform.isMacOSX()) | Verify consistency of L{Platform.isVista}: it can only be C{True} if
L{Platform.isWinNT} and L{Platform.isWindows} are C{True}. | test_isVistaConsistency | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isMacOSXConsistency(self):
"""
L{Platform.isMacOSX} can only return C{True} if L{Platform.getType}
returns C{'posix'}.
"""
platform = Platform()
if platform.isMacOSX():
self.assertEqual(platform.getType(), 'posix') | L{Platform.isMacOSX} can only return C{True} if L{Platform.getType}
returns C{'posix'}. | test_isMacOSXConsistency | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isLinuxConsistency(self):
"""
L{Platform.isLinux} can only return C{True} if L{Platform.getType}
returns C{'posix'} and L{sys.platform} starts with C{"linux"}.
"""
platform = Platform()
if platform.isLinux():
self.assertTrue(sys.platform.startswith("linux")) | L{Platform.isLinux} can only return C{True} if L{Platform.getType}
returns C{'posix'} and L{sys.platform} starts with C{"linux"}. | test_isLinuxConsistency | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isWinNT(self):
"""
L{Platform.isWinNT} can return only C{False} or C{True} and can not
return C{True} if L{Platform.getType} is not C{"win32"}.
"""
platform = Platform()
isWinNT = platform.isWinNT()
self.assertIn(isWinNT, (False, True))
if platform.getType() != "win32":
self.assertFalse(isWinNT) | L{Platform.isWinNT} can return only C{False} or C{True} and can not
return C{True} if L{Platform.getType} is not C{"win32"}. | test_isWinNT | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isWinNTDeprecated(self):
"""
L{Platform.isWinNT} is deprecated in favor of L{platform.isWindows}.
"""
platform = Platform()
platform.isWinNT()
warnings = self.flushWarnings([self.test_isWinNTDeprecated])
self.assertEqual(len(warnings), 1)
self.assertEqual(
warnings[0]['message'], self.isWinNTDeprecationMessage) | L{Platform.isWinNT} is deprecated in favor of L{platform.isWindows}. | test_isWinNTDeprecated | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_supportsThreads(self):
"""
L{Platform.supportsThreads} returns C{True} if threads can be created in
this runtime, C{False} otherwise.
"""
# It's difficult to test both cases of this without faking the threading
# module. Perhaps an adequate test is to just test the behavior with
# the current runtime, whatever that happens to be.
try:
namedModule('threading')
except ImportError:
self.assertFalse(Platform().supportsThreads())
else:
self.assertTrue(Platform().supportsThreads()) | L{Platform.supportsThreads} returns C{True} if threads can be created in
this runtime, C{False} otherwise. | test_supportsThreads | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_getType(self):
"""
If an operating system name is supplied to L{Platform}'s initializer,
L{Platform.getType} returns the platform type which corresponds to that
name.
"""
self.assertEqual(Platform('nt').getType(), 'win32')
self.assertEqual(Platform('ce').getType(), 'win32')
self.assertEqual(Platform('posix').getType(), 'posix')
self.assertEqual(Platform('java').getType(), 'java') | If an operating system name is supplied to L{Platform}'s initializer,
L{Platform.getType} returns the platform type which corresponds to that
name. | test_getType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isMacOSX(self):
"""
If a system platform name is supplied to L{Platform}'s initializer, it
is used to determine the result of L{Platform.isMacOSX}, which returns
C{True} for C{"darwin"}, C{False} otherwise.
"""
self.assertTrue(Platform(None, 'darwin').isMacOSX())
self.assertFalse(Platform(None, 'linux2').isMacOSX())
self.assertFalse(Platform(None, 'win32').isMacOSX()) | If a system platform name is supplied to L{Platform}'s initializer, it
is used to determine the result of L{Platform.isMacOSX}, which returns
C{True} for C{"darwin"}, C{False} otherwise. | test_isMacOSX | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_isLinux(self):
"""
If a system platform name is supplied to L{Platform}'s initializer, it
is used to determine the result of L{Platform.isLinux}, which returns
C{True} for values beginning with C{"linux"}, C{False} otherwise.
"""
self.assertFalse(Platform(None, 'darwin').isLinux())
self.assertTrue(Platform(None, 'linux').isLinux())
self.assertTrue(Platform(None, 'linux2').isLinux())
self.assertTrue(Platform(None, 'linux3').isLinux())
self.assertFalse(Platform(None, 'win32').isLinux()) | If a system platform name is supplied to L{Platform}'s initializer, it
is used to determine the result of L{Platform.isLinux}, which returns
C{True} for values beginning with C{"linux"}, C{False} otherwise. | test_isLinux | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_noChecksOnLinux(self):
"""
If the platform is not Linux, C{isDocker()} always returns L{False}.
"""
platform = Platform(None, 'win32')
self.assertFalse(platform.isDocker()) | If the platform is not Linux, C{isDocker()} always returns L{False}. | test_noChecksOnLinux | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_noCGroups(self):
"""
If the platform is Linux, and the cgroups file in C{/proc} does not
exist, C{isDocker()} returns L{False}
"""
platform = Platform(None, 'linux')
self.assertFalse(platform.isDocker(_initCGroupLocation="fakepath")) | If the platform is Linux, and the cgroups file in C{/proc} does not
exist, C{isDocker()} returns L{False} | test_noCGroups | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_cgroupsSuggestsDocker(self):
"""
If the platform is Linux, and the cgroups file (faked out here) exists,
and one of the paths starts with C{/docker/}, C{isDocker()} returns
C{True}.
"""
cgroupsFile = self.mktemp()
with open(cgroupsFile, 'wb') as f:
# real cgroups file from inside a Debian 7 docker container
f.write(b"""10:debug:/
9:net_prio:/
8:perf_event:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f
7:net_cls:/
6:freezer:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f
5:devices:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f
4:blkio:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f
3:cpuacct:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f
2:cpu:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f
1:cpuset:/docker/104155a6453cb67590027e397dc90fc25a06a7508403c797bc89ea43adf8d35f""")
platform = Platform(None, 'linux')
self.assertTrue(platform.isDocker(_initCGroupLocation=cgroupsFile)) | If the platform is Linux, and the cgroups file (faked out here) exists,
and one of the paths starts with C{/docker/}, C{isDocker()} returns
C{True}. | test_cgroupsSuggestsDocker | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def test_cgroupsSuggestsRealSystem(self):
"""
If the platform is Linux, and the cgroups file (faked out here) exists,
and none of the paths starts with C{/docker/}, C{isDocker()} returns
C{False}.
"""
cgroupsFile = self.mktemp()
with open(cgroupsFile, 'wb') as f:
# real cgroups file from a Fedora 17 system
f.write(b"""9:perf_event:/
8:blkio:/
7:net_cls:/
6:freezer:/
5:devices:/
4:memory:/
3:cpuacct,cpu:/
2:cpuset:/
1:name=systemd:/system""")
platform = Platform(None, 'linux')
self.assertFalse(platform.isDocker(_initCGroupLocation=cgroupsFile)) | If the platform is Linux, and the cgroups file (faked out here) exists,
and none of the paths starts with C{/docker/}, C{isDocker()} returns
C{False}. | test_cgroupsSuggestsRealSystem | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_runtime.py | MIT |
def get(self):
"""
Get a known value.
"""
return self.value | Get a known value. | get | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def _makeProxy(self, **attrs):
"""
Create a temporary module proxy object.
@param **kw: Attributes to initialise on the temporary module object
@rtype: L{twistd.python.deprecate._ModuleProxy}
"""
mod = types.ModuleType('foo')
for key, value in attrs.items():
setattr(mod, key, value)
return deprecate._ModuleProxy(mod) | Create a temporary module proxy object.
@param **kw: Attributes to initialise on the temporary module object
@rtype: L{twistd.python.deprecate._ModuleProxy} | _makeProxy | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_getattrPassthrough(self):
"""
Getting a normal attribute on a L{twisted.python.deprecate._ModuleProxy}
retrieves the underlying attribute's value, and raises C{AttributeError}
if a non-existent attribute is accessed.
"""
proxy = self._makeProxy(SOME_ATTRIBUTE='hello')
self.assertIs(proxy.SOME_ATTRIBUTE, 'hello')
self.assertRaises(AttributeError, getattr, proxy, 'DOES_NOT_EXIST') | Getting a normal attribute on a L{twisted.python.deprecate._ModuleProxy}
retrieves the underlying attribute's value, and raises C{AttributeError}
if a non-existent attribute is accessed. | test_getattrPassthrough | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_getattrIntercept(self):
"""
Getting an attribute marked as being deprecated on
L{twisted.python.deprecate._ModuleProxy} results in calling the
deprecated wrapper's C{get} method.
"""
proxy = self._makeProxy()
_deprecatedAttributes = object.__getattribute__(
proxy, '_deprecatedAttributes')
_deprecatedAttributes['foo'] = _MockDeprecatedAttribute(42)
self.assertEqual(proxy.foo, 42) | Getting an attribute marked as being deprecated on
L{twisted.python.deprecate._ModuleProxy} results in calling the
deprecated wrapper's C{get} method. | test_getattrIntercept | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_privateAttributes(self):
"""
Private attributes of L{twisted.python.deprecate._ModuleProxy} are
inaccessible when regular attribute access is used.
"""
proxy = self._makeProxy()
self.assertRaises(AttributeError, getattr, proxy, '_module')
self.assertRaises(
AttributeError, getattr, proxy, '_deprecatedAttributes') | Private attributes of L{twisted.python.deprecate._ModuleProxy} are
inaccessible when regular attribute access is used. | test_privateAttributes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_setattr(self):
"""
Setting attributes on L{twisted.python.deprecate._ModuleProxy} proxies
them through to the wrapped module.
"""
proxy = self._makeProxy()
proxy._module = 1
self.assertNotEqual(object.__getattribute__(proxy, '_module'), 1)
self.assertEqual(proxy._module, 1) | Setting attributes on L{twisted.python.deprecate._ModuleProxy} proxies
them through to the wrapped module. | test_setattr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_repr(self):
"""
L{twisted.python.deprecated._ModuleProxy.__repr__} produces a string
containing the proxy type and a representation of the wrapped module
object.
"""
proxy = self._makeProxy()
realModule = object.__getattribute__(proxy, '_module')
self.assertEqual(
repr(proxy), '<%s module=%r>' % (type(proxy).__name__, realModule)) | L{twisted.python.deprecated._ModuleProxy.__repr__} produces a string
containing the proxy type and a representation of the wrapped module
object. | test_repr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def _getWarningString(self, attr):
"""
Create the warning string used by deprecated attributes.
"""
return _getDeprecationWarningString(
deprecatedattributes.__name__ + '.' + attr,
deprecatedattributes.version,
DEPRECATION_WARNING_FORMAT + ': ' + deprecatedattributes.message) | Create the warning string used by deprecated attributes. | _getWarningString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_deprecatedAttributeHelper(self):
"""
L{twisted.python.deprecate._DeprecatedAttribute} correctly sets its
__name__ to match that of the deprecated attribute and emits a warning
when the original attribute value is accessed.
"""
name = 'ANOTHER_DEPRECATED_ATTRIBUTE'
setattr(deprecatedattributes, name, 42)
attr = deprecate._DeprecatedAttribute(
deprecatedattributes, name, self.version, self.message)
self.assertEqual(attr.__name__, name)
# Since we're accessing the value getter directly, as opposed to via
# the module proxy, we need to match the warning's stack level.
def addStackLevel():
attr.get()
# Access the deprecated attribute.
addStackLevel()
warningsShown = self.flushWarnings([
self.test_deprecatedAttributeHelper])
self.assertIs(warningsShown[0]['category'], DeprecationWarning)
self.assertEqual(
warningsShown[0]['message'],
self._getWarningString(name))
self.assertEqual(len(warningsShown), 1) | L{twisted.python.deprecate._DeprecatedAttribute} correctly sets its
__name__ to match that of the deprecated attribute and emits a warning
when the original attribute value is accessed. | test_deprecatedAttributeHelper | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_deprecatedAttribute(self):
"""
L{twisted.python.deprecate.deprecatedModuleAttribute} wraps a
module-level attribute in an object that emits a deprecation warning
when it is accessed the first time only, while leaving other unrelated
attributes alone.
"""
# Accessing non-deprecated attributes does not issue a warning.
deprecatedattributes.ANOTHER_ATTRIBUTE
warningsShown = self.flushWarnings([self.test_deprecatedAttribute])
self.assertEqual(len(warningsShown), 0)
name = 'DEPRECATED_ATTRIBUTE'
# Access the deprecated attribute. This uses getattr to avoid repeating
# the attribute name.
getattr(deprecatedattributes, name)
warningsShown = self.flushWarnings([self.test_deprecatedAttribute])
self.assertEqual(len(warningsShown), 1)
self.assertIs(warningsShown[0]['category'], DeprecationWarning)
self.assertEqual(
warningsShown[0]['message'],
self._getWarningString(name)) | L{twisted.python.deprecate.deprecatedModuleAttribute} wraps a
module-level attribute in an object that emits a deprecation warning
when it is accessed the first time only, while leaving other unrelated
attributes alone. | test_deprecatedAttribute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_wrappedModule(self):
"""
Deprecating an attribute in a module replaces and wraps that module
instance, in C{sys.modules}, with a
L{twisted.python.deprecate._ModuleProxy} instance but only if it hasn't
already been wrapped.
"""
sys.modules[self._testModuleName] = mod = types.ModuleType('foo')
self.addCleanup(sys.modules.pop, self._testModuleName)
setattr(mod, 'first', 1)
setattr(mod, 'second', 2)
deprecate.deprecatedModuleAttribute(
Version('Twisted', 8, 0, 0),
'message',
self._testModuleName,
'first')
proxy = sys.modules[self._testModuleName]
self.assertNotEqual(proxy, mod)
deprecate.deprecatedModuleAttribute(
Version('Twisted', 8, 0, 0),
'message',
self._testModuleName,
'second')
self.assertIs(proxy, sys.modules[self._testModuleName]) | Deprecating an attribute in a module replaces and wraps that module
instance, in C{sys.modules}, with a
L{twisted.python.deprecate._ModuleProxy} instance but only if it hasn't
already been wrapped. | test_wrappedModule | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def pathEntryTree(self, tree):
"""
Create some files in a hierarchy, based on a dictionary describing those
files. The resulting hierarchy will be placed onto sys.path for the
duration of the test.
@param tree: A dictionary representing a directory structure. Keys are
strings, representing filenames, dictionary values represent
directories, string values represent file contents.
@return: another dictionary similar to the input, with file content
strings replaced with L{FilePath} objects pointing at where those
contents are now stored.
"""
def makeSomeFiles(pathobj, dirdict):
pathdict = {}
for (key, value) in dirdict.items():
child = pathobj.child(key)
if isinstance(value, bytes):
pathdict[key] = child
child.setContent(value)
elif isinstance(value, dict):
child.createDirectory()
pathdict[key] = makeSomeFiles(child, value)
else:
raise ValueError("only strings and dicts allowed as values")
return pathdict
base = FilePath(self.mktemp().encode("utf-8"))
base.makedirs()
result = makeSomeFiles(base, tree)
# On Python 3, sys.path cannot include byte paths:
self.replaceSysPath([base.path.decode("utf-8")] + sys.path)
self.replaceSysModules(sys.modules.copy())
return result | Create some files in a hierarchy, based on a dictionary describing those
files. The resulting hierarchy will be placed onto sys.path for the
duration of the test.
@param tree: A dictionary representing a directory structure. Keys are
strings, representing filenames, dictionary values represent
directories, string values represent file contents.
@return: another dictionary similar to the input, with file content
strings replaced with L{FilePath} objects pointing at where those
contents are now stored. | pathEntryTree | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def simpleModuleEntry(self):
"""
Add a sample module and package to the path, returning a L{FilePath}
pointing at the module which will be loadable as C{package.module}.
"""
paths = self.pathEntryTree(
{b"package": {b"__init__.py": self._packageInit.encode("utf-8"),
b"module.py": b""}})
return paths[b'package'][b'module.py'] | Add a sample module and package to the path, returning a L{FilePath}
pointing at the module which will be loadable as C{package.module}. | simpleModuleEntry | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def checkOneWarning(self, modulePath):
"""
Verification logic for L{test_deprecatedModule}.
"""
from package import module
self.assertEqual(FilePath(module.__file__.encode("utf-8")),
modulePath)
emitted = self.flushWarnings([self.checkOneWarning])
self.assertEqual(len(emitted), 1)
self.assertEqual(emitted[0]['message'],
'package.module was deprecated in Package 1.2.3: '
'message')
self.assertEqual(emitted[0]['category'], DeprecationWarning) | Verification logic for L{test_deprecatedModule}. | checkOneWarning | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_deprecatedModule(self):
"""
If L{deprecatedModuleAttribute} is used to deprecate a module attribute
of a package, only one deprecation warning is emitted when the
deprecated module is imported.
"""
self.checkOneWarning(self.simpleModuleEntry()) | If L{deprecatedModuleAttribute} is used to deprecate a module attribute
of a package, only one deprecation warning is emitted when the
deprecated module is imported. | test_deprecatedModule | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_deprecatedModuleMultipleTimes(self):
"""
If L{deprecatedModuleAttribute} is used to deprecate a module attribute
of a package, only one deprecation warning is emitted when the
deprecated module is subsequently imported.
"""
mp = self.simpleModuleEntry()
# The first time, the code needs to be loaded.
self.checkOneWarning(mp)
# The second time, things are slightly different; the object's already
# in the namespace.
self.checkOneWarning(mp)
# The third and fourth times, things things should all be exactly the
# same, but this is a sanity check to make sure the implementation isn't
# special casing the second time. Also, putting these cases into a loop
# means that the stack will be identical, to make sure that the
# implementation doesn't rely too much on stack-crawling.
for x in range(2):
self.checkOneWarning(mp) | If L{deprecatedModuleAttribute} is used to deprecate a module attribute
of a package, only one deprecation warning is emitted when the
deprecated module is subsequently imported. | test_deprecatedModuleMultipleTimes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def setUp(self):
"""
Create a file that will have known line numbers when emitting warnings.
"""
self.package = FilePath(self.mktemp().encode("utf-8")
).child(b'twisted_private_helper')
self.package.makedirs()
self.package.child(b'__init__.py').setContent(b'')
self.package.child(b'module.py').setContent(b'''
"A module string"
from twisted.python import deprecate
def testFunction():
"A doc string"
a = 1 + 2
return a
def callTestFunction():
b = testFunction()
if b == 3:
deprecate.warnAboutFunction(testFunction, "A Warning String")
''')
# Python 3 doesn't accept bytes in sys.path:
packagePath = self.package.parent().path.decode("utf-8")
sys.path.insert(0, packagePath)
self.addCleanup(sys.path.remove, packagePath)
modules = sys.modules.copy()
self.addCleanup(
lambda: (sys.modules.clear(), sys.modules.update(modules)))
# On Windows on Python 3, most FilePath interactions produce
# DeprecationWarnings, so flush them here so that they don't interfere
# with the tests.
if platform.isWindows() and _PY3:
self.flushWarnings() | Create a file that will have known line numbers when emitting warnings. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_warning(self):
"""
L{deprecate.warnAboutFunction} emits a warning the file and line number
of which point to the beginning of the implementation of the function
passed to it.
"""
def aFunc():
pass
deprecate.warnAboutFunction(aFunc, 'A Warning Message')
warningsShown = self.flushWarnings()
filename = __file__
if filename.lower().endswith('.pyc'):
filename = filename[:-1]
self.assertSamePath(
FilePath(warningsShown[0]["filename"]), FilePath(filename))
self.assertEqual(warningsShown[0]["message"], "A Warning Message") | L{deprecate.warnAboutFunction} emits a warning the file and line number
of which point to the beginning of the implementation of the function
passed to it. | test_warning | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
def test_warningLineNumber(self):
"""
L{deprecate.warnAboutFunction} emits a C{DeprecationWarning} with the
number of a line within the implementation of the function passed to it.
"""
from twisted_private_helper import module
module.callTestFunction()
warningsShown = self.flushWarnings()
self.assertSamePath(
FilePath(warningsShown[0]["filename"].encode("utf-8")),
self.package.sibling(b'twisted_private_helper').child(b'module.py'))
# Line number 9 is the last line in the testFunction in the helper
# module.
self.assertEqual(warningsShown[0]["lineno"], 9)
self.assertEqual(warningsShown[0]["message"], "A Warning String")
self.assertEqual(len(warningsShown), 1) | L{deprecate.warnAboutFunction} emits a C{DeprecationWarning} with the
number of a line within the implementation of the function passed to it. | test_warningLineNumber | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/test/test_deprecate.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.