code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True): ''' Return an auto-proxy for `token` ''' _Client = listener_client[serializer][1] if exposed is None: conn = _Client(token.address, authkey=authkey) try: exposed = dispatch(conn, None, 'get_methods', (token,)) finally: conn.close() if authkey is None and manager is not None: authkey = manager._authkey if authkey is None: authkey = current_process().authkey ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed) proxy = ProxyType(token, serializer, manager=manager, authkey=authkey, incref=incref) proxy._isauto = True return proxy
Return an auto-proxy for `token`
AutoProxy
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/managers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py
MIT
def _join_exited_workers(self): """Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up. """ cleaned = False for i in reversed(range(len(self._pool))): worker = self._pool[i] if worker.exitcode is not None: # worker exited debug('cleaning up worker %d' % i) worker.join() cleaned = True del self._pool[i] return cleaned
Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up.
_join_exited_workers
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/pool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/pool.py
MIT
def _repopulate_pool(self): """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): w = self.Process(target=worker, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild) ) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() debug('added worker')
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
_repopulate_pool
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/pool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/pool.py
MIT
def imap(self, func, iterable, chunksize=1): ''' Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()` ''' assert self._state == RUN if chunksize == 1: result = IMapIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for i, x in enumerate(iterable)), result._set_length)) return result else: assert chunksize > 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapIterator(self._cache) self._taskqueue.put((((result._job, i, mapstar, (x,), {}) for i, x in enumerate(task_batches)), result._set_length)) return (item for chunk in result for item in chunk)
Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()`
imap
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/pool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/pool.py
MIT
def imap_unordered(self, func, iterable, chunksize=1): ''' Like `imap()` method but ordering of results is arbitrary ''' assert self._state == RUN if chunksize == 1: result = IMapUnorderedIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for i, x in enumerate(iterable)), result._set_length)) return result else: assert chunksize > 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapUnorderedIterator(self._cache) self._taskqueue.put((((result._job, i, mapstar, (x,), {}) for i, x in enumerate(task_batches)), result._set_length)) return (item for chunk in result for item in chunk)
Like `imap()` method but ordering of results is arbitrary
imap_unordered
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/pool.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/pool.py
MIT
def exitcode(self): ''' Return exit code of process or `None` if it has yet to stop ''' if self._popen is None: return self._popen return self._popen.poll()
Return exit code of process or `None` if it has yet to stop
exitcode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/process.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/process.py
MIT
def ident(self): ''' Return identifier (PID) of process or `None` if it has yet to start ''' if self is _current_process: return os.getpid() else: return self._popen and self._popen.pid
Return identifier (PID) of process or `None` if it has yet to start
ident
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/process.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/process.py
MIT
def RawValue(typecode_or_type, *args): ''' Returns a ctypes object allocated from shared memory ''' type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) obj = _new_value(type_) ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) obj.__init__(*args) return obj
Returns a ctypes object allocated from shared memory
RawValue
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/sharedctypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/sharedctypes.py
MIT
def RawArray(typecode_or_type, size_or_initializer): ''' Returns a ctypes array allocated from shared memory ''' type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) if isinstance(size_or_initializer, (int, long)): type_ = type_ * size_or_initializer obj = _new_value(type_) ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) return obj else: type_ = type_ * len(size_or_initializer) result = _new_value(type_) result.__init__(*size_or_initializer) return result
Returns a ctypes array allocated from shared memory
RawArray
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/sharedctypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/sharedctypes.py
MIT
def log_to_stderr(level=None): ''' Turn on logging and add a handler which prints to stderr ''' global _log_to_stderr import logging logger = get_logger() formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if level: logger.setLevel(level) _log_to_stderr = True return _logger
Turn on logging and add a handler which prints to stderr
log_to_stderr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/util.py
MIT
def __call__(self, wr=None): ''' Run the callback unless it has already been called or cancelled ''' try: del _finalizer_registry[self._key] except KeyError: sub_debug('finalizer no longer registered') else: if self._pid != os.getpid(): sub_debug('finalizer ignored because different process') res = None else: sub_debug('finalizer calling %s with args %s and kwargs %s', self._callback, self._args, self._kwargs) res = self._callback(*self._args, **self._kwargs) self._weakref = self._callback = self._args = \ self._kwargs = self._key = None return res
Run the callback unless it has already been called or cancelled
__call__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/util.py
MIT
def _run_finalizers(minpriority=None): ''' Run all finalizers whose exit priority is not None and at least minpriority Finalizers with highest priority are called first; finalizers with the same priority will be called in reverse order of creation. ''' if _finalizer_registry is None: # This function may be called after this module's globals are # destroyed. See the _exit_function function in this module for more # notes. return if minpriority is None: f = lambda p : p[0][0] is not None else: f = lambda p : p[0][0] is not None and p[0][0] >= minpriority items = [x for x in _finalizer_registry.items() if f(x)] items.sort(reverse=True) for key, finalizer in items: sub_debug('calling %s', finalizer) try: finalizer() except Exception: import traceback traceback.print_exc() if minpriority is None: _finalizer_registry.clear()
Run all finalizers whose exit priority is not None and at least minpriority Finalizers with highest priority are called first; finalizers with the same priority will be called in reverse order of creation.
_run_finalizers
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/util.py
MIT
def Manager(): ''' Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. ''' from multiprocessing.managers import SyncManager m = SyncManager() m.start() return m
Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects.
Manager
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/__init__.py
MIT
def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus')
Returns the number of CPUs in the system
cpu_count
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/__init__.py
MIT
def freeze_support(): ''' Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. ''' if sys.platform == 'win32' and getattr(sys, 'frozen', False): from multiprocessing.forking import freeze_support freeze_support()
Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit.
freeze_support
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/multiprocessing/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/__init__.py
MIT
def _iterdump(connection): """ Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method, iterdump(). """ cu = connection.cursor() yield('BEGIN TRANSACTION;') # sqlite_master table contains the SQL CREATE statements for the database. q = """ SELECT "name", "type", "sql" FROM "sqlite_master" WHERE "sql" NOT NULL AND "type" == 'table' ORDER BY "name" """ schema_res = cu.execute(q) for table_name, type, sql in schema_res.fetchall(): if table_name == 'sqlite_sequence': yield('DELETE FROM "sqlite_sequence";') elif table_name == 'sqlite_stat1': yield('ANALYZE "sqlite_master";') elif table_name.startswith('sqlite_'): continue # NOTE: Virtual table support not implemented #elif sql.startswith('CREATE VIRTUAL TABLE'): # qtable = table_name.replace("'", "''") # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\ # "VALUES('table','{0}','{0}',0,'{1}');".format( # qtable, # sql.replace("''"))) else: yield('%s;' % sql) # Build the insert statement for each row of the current table table_name_ident = table_name.replace('"', '""') res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident)) column_names = [str(table_info[1]) for table_info in res.fetchall()] q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format( table_name_ident, ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names)) query_res = cu.execute(q) for row in query_res: yield("%s;" % row[0]) # Now when the type is 'index', 'trigger', or 'view' q = """ SELECT "name", "type", "sql" FROM "sqlite_master" WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view') """ schema_res = cu.execute(q) for name, type, sql in schema_res.fetchall(): yield('%s;' % sql) yield('COMMIT;')
Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method, iterdump().
_iterdump
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sqlite3/dump.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sqlite3/dump.py
MIT
def skipIf(condition, reason): """ Skip a test if the condition is true. """ if condition: return skip(reason) return _id
Skip a test if the condition is true.
skipIf
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def skipUnless(condition, reason): """ Skip a test unless the condition is true. """ if not condition: return skip(reason) return _id
Skip a test unless the condition is true.
skipUnless
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ self._testMethodName = methodName self._resultForDoCleanups = None try: testMethod = getattr(self, methodName) except AttributeError: raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) self._testMethodDoc = testMethod.__doc__ self._cleanups = [] # Map types to custom assertEqual functions that will compare # instances of said type in more detail to generate a more useful # error message. self._type_equality_funcs = {} self.addTypeEqualityFunc(dict, 'assertDictEqual') self.addTypeEqualityFunc(list, 'assertListEqual') self.addTypeEqualityFunc(tuple, 'assertTupleEqual') self.addTypeEqualityFunc(set, 'assertSetEqual') self.addTypeEqualityFunc(frozenset, 'assertSetEqual') try: self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual') except NameError: # No unicode support in this build pass
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def shortDescription(self): """Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method's docstring. """ doc = self._testMethodDoc return doc and doc.split("\n")[0].strip() or None
Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the specified test method's docstring.
shortDescription
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def doCleanups(self): """Execute all cleanup functions. Normally called for you after tearDown.""" result = self._resultForDoCleanups ok = True while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) try: function(*args, **kwargs) except KeyboardInterrupt: raise except: ok = False result.addError(self, sys.exc_info()) return ok
Execute all cleanup functions. Normally called for you after tearDown.
doCleanups
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def debug(self): """Run the test without collecting errors in a TestResult""" self.setUp() getattr(self, self._testMethodName)() self.tearDown() while self._cleanups: function, args, kwargs = self._cleanups.pop(-1) function(*args, **kwargs)
Run the test without collecting errors in a TestResult
debug
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertFalse(self, expr, msg=None): """Check that the expression is false.""" if expr: msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr)) raise self.failureException(msg)
Check that the expression is false.
assertFalse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertTrue(self, expr, msg=None): """Check that the expression is true.""" if not expr: msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) raise self.failureException(msg)
Check that the expression is true.
assertTrue
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def _formatMessage(self, msg, standardMsg): """Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus ' : ' and the explicit message """ if not self.longMessage: return msg or standardMsg if msg is None: return standardMsg try: # don't switch to '{}' formatting in Python 2.X # it changes the way unicode input is handled return '%s : %s' % (standardMsg, msg) except UnicodeDecodeError: return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert If longMessage is True: * Use the standard message * If an explicit message is provided, plus ' : ' and the explicit message
_formatMessage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def _getAssertEqualityFunc(self, first, second): """Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types. """ # # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) # and vice versa. I opted for the conservative approach in case # subclasses are not intended to be compared in detail to their super # class instances using a type equality func. This means testing # subtypes won't automagically use the detailed comparison. Callers # should use their type specific assertSpamEqual method to compare # subclasses if the detailed comparison is desired and appropriate. # See the discussion in http://bugs.python.org/issue2578. # if type(first) is type(second): asserter = self._type_equality_funcs.get(type(first)) if asserter is not None: if isinstance(asserter, basestring): asserter = getattr(self, asserter) return asserter return self._baseAssertEqual
Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human readable error message for those types.
_getAssertEqualityFunc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def _baseAssertEqual(self, first, second, msg=None): """The default assertEqual implementation, not type specific.""" if not first == second: standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
The default assertEqual implementation, not type specific.
_baseAssertEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg)
Fail if the two objects are unequal as determined by the '==' operator.
assertEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertNotEqual(self, first, second, msg=None): """Fail if the two objects are equal as determined by the '!=' operator. """ if not first != second: msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first), safe_repr(second))) raise self.failureException(msg)
Fail if the two objects are equal as determined by the '!=' operator.
assertNotEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). If the two objects compare equal then they will automatically compare almost equal. """ if first == second: # shortcut return if delta is not None and places is not None: raise TypeError("specify delta or places not both") if delta is not None: if abs(first - second) <= delta: return standardMsg = '%s != %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if round(abs(second-first), places) == 0: return standardMsg = '%s != %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). If the two objects compare equal then they will automatically compare almost equal.
assertAlmostEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None): """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). Objects that are equal automatically fail. """ if delta is not None and places is not None: raise TypeError("specify delta or places not both") if delta is not None: if not (first == second) and abs(first - second) > delta: return standardMsg = '%s == %s within %s delta' % (safe_repr(first), safe_repr(second), safe_repr(delta)) else: if places is None: places = 7 if not (first == second) and round(abs(second-first), places) != 0: return standardMsg = '%s == %s within %r places' % (safe_repr(first), safe_repr(second), places) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). Objects that are equal automatically fail.
assertNotAlmostEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): """An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences. """ if seq_type is not None: seq_type_name = seq_type.__name__ if not isinstance(seq1, seq_type): raise self.failureException('First sequence is not a %s: %s' % (seq_type_name, safe_repr(seq1))) if not isinstance(seq2, seq_type): raise self.failureException('Second sequence is not a %s: %s' % (seq_type_name, safe_repr(seq2))) else: seq_type_name = "sequence" differing = None try: len1 = len(seq1) except (TypeError, NotImplementedError): differing = 'First %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: try: len2 = len(seq2) except (TypeError, NotImplementedError): differing = 'Second %s has no length. Non-sequence?' % ( seq_type_name) if differing is None: if seq1 == seq2: return seq1_repr = safe_repr(seq1) seq2_repr = safe_repr(seq2) if len(seq1_repr) > 30: seq1_repr = seq1_repr[:30] + '...' if len(seq2_repr) > 30: seq2_repr = seq2_repr[:30] + '...' elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) differing = '%ss differ: %s != %s\n' % elements for i in xrange(min(len1, len2)): try: item1 = seq1[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of first %s\n' % (i, seq_type_name)) break try: item2 = seq2[i] except (TypeError, IndexError, NotImplementedError): differing += ('\nUnable to index element %d of second %s\n' % (i, seq_type_name)) break if item1 != item2: differing += ('\nFirst differing element %d:\n%s\n%s\n' % (i, safe_repr(item1), safe_repr(item2))) break else: if (len1 == len2 and seq_type is None and type(seq1) != type(seq2)): # The sequences are the same, but have differing types. return if len1 > len2: differing += ('\nFirst %s contains %d additional ' 'elements.\n' % (seq_type_name, len1 - len2)) try: differing += ('First extra element %d:\n%s\n' % (len2, safe_repr(seq1[len2]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of first %s\n' % (len2, seq_type_name)) elif len1 < len2: differing += ('\nSecond %s contains %d additional ' 'elements.\n' % (seq_type_name, len2 - len1)) try: differing += ('First extra element %d:\n%s\n' % (len1, safe_repr(seq2[len1]))) except (TypeError, IndexError, NotImplementedError): differing += ('Unable to index element %d ' 'of second %s\n' % (len1, seq_type_name)) standardMsg = differing diffMsg = '\n' + '\n'.join( difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg)
An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. Args: seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no datatype should be enforced. msg: Optional message to use on failure instead of a list of differences.
assertSequenceEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertSetEqual(self, set1, set2, msg=None): """A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). """ try: difference1 = set1.difference(set2) except TypeError, e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError, e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) except TypeError, e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError, e: self.fail('second argument does not support set difference: %s' % e) if not (difference1 or difference2): return lines = [] if difference1: lines.append('Items in the first set but not the second:') for item in difference1: lines.append(repr(item)) if difference2: lines.append('Items in the second set but not the first:') for item in difference2: lines.append(repr(item)) standardMsg = '\n'.join(lines) self.fail(self._formatMessage(msg, standardMsg))
A set-specific equality assertion. Args: set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of differences. assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).
assertSetEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertIn(self, member, container, msg=None): """Just like self.assertTrue(a in b), but with a nicer default message.""" if member not in container: standardMsg = '%s not found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a in b), but with a nicer default message.
assertIn
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertNotIn(self, member, container, msg=None): """Just like self.assertTrue(a not in b), but with a nicer default message.""" if member in container: standardMsg = '%s unexpectedly found in %s' % (safe_repr(member), safe_repr(container)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a not in b), but with a nicer default message.
assertNotIn
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertIs(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is b), but with a nicer default message.""" if expr1 is not expr2: standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a is b), but with a nicer default message.
assertIs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertIsNot(self, expr1, expr2, msg=None): """Just like self.assertTrue(a is not b), but with a nicer default message.""" if expr1 is expr2: standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a is not b), but with a nicer default message.
assertIsNot
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertDictContainsSubset(self, expected, actual, msg=None): """Checks whether actual is a superset of expected.""" missing = [] mismatched = [] for key, value in expected.iteritems(): if key not in actual: missing.append(key) elif value != actual[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(actual[key]))) if not (missing or mismatched): return standardMsg = '' if missing: standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in missing) if mismatched: if standardMsg: standardMsg += '; ' standardMsg += 'Mismatched values: %s' % ','.join(mismatched) self.fail(self._formatMessage(msg, standardMsg))
Checks whether actual is a superset of expected.
assertDictContainsSubset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertItemsEqual(self, expected_seq, actual_seq, msg=None): """An unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. """ first_seq, second_seq = list(expected_seq), list(actual_seq) with warnings.catch_warnings(): if sys.py3kwarning: # Silence Py3k warning raised during the sorting for _msg in ["(code|dict|type) inequality comparisons", "builtin_function_or_method order comparisons", "comparing unequal types"]: warnings.filterwarnings("ignore", _msg, DeprecationWarning) try: first = collections.Counter(first_seq) second = collections.Counter(second_seq) except TypeError: # Handle case with unhashable elements differences = _count_diff_all_purpose(first_seq, second_seq) else: if first == second: return differences = _count_diff_hashable(first_seq, second_seq) if differences: standardMsg = 'Element counts were not equal:\n' lines = ['First has %d, Second has %d: %r' % diff for diff in differences] diffMsg = '\n'.join(lines) standardMsg = self._truncateMessage(standardMsg, diffMsg) msg = self._formatMessage(msg, standardMsg) self.fail(msg)
An unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:: self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq))) Asserts that each element has the same count in both sequences. Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal.
assertItemsEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" self.assertIsInstance(first, basestring, 'First argument is not a string') self.assertIsInstance(second, basestring, 'Second argument is not a string') if first != second: # don't use difflib if the strings are too long if (len(first) > self._diffThreshold or len(second) > self._diffThreshold): self._baseAssertEqual(first, second, msg) firstlines = first.splitlines(True) secondlines = second.splitlines(True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True)) diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg))
Assert that two multi-line strings are equal.
assertMultiLineEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertLess(self, a, b, msg=None): """Just like self.assertTrue(a < b), but with a nicer default message.""" if not a < b: standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a < b), but with a nicer default message.
assertLess
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertLessEqual(self, a, b, msg=None): """Just like self.assertTrue(a <= b), but with a nicer default message.""" if not a <= b: standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a <= b), but with a nicer default message.
assertLessEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertGreater(self, a, b, msg=None): """Just like self.assertTrue(a > b), but with a nicer default message.""" if not a > b: standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a > b), but with a nicer default message.
assertGreater
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertGreaterEqual(self, a, b, msg=None): """Just like self.assertTrue(a >= b), but with a nicer default message.""" if not a >= b: standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b)) self.fail(self._formatMessage(msg, standardMsg))
Just like self.assertTrue(a >= b), but with a nicer default message.
assertGreaterEqual
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertIsNone(self, obj, msg=None): """Same as self.assertTrue(obj is None), with a nicer default message.""" if obj is not None: standardMsg = '%s is not None' % (safe_repr(obj),) self.fail(self._formatMessage(msg, standardMsg))
Same as self.assertTrue(obj is None), with a nicer default message.
assertIsNone
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertIsInstance(self, obj, cls, msg=None): """Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.""" if not isinstance(obj, cls): standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg))
Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.
assertIsInstance
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs): """Asserts that the message in a raised exception matches a regexp. Args: expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs. """ if expected_regexp is not None: expected_regexp = re.compile(expected_regexp) context = _AssertRaisesContext(expected_exception, self, expected_regexp) if callable_obj is None: return context with context: callable_obj(*args, **kwargs)
Asserts that the message in a raised exception matches a regexp. Args: expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected to be found in error message. callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs.
assertRaisesRegexp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertRegexpMatches(self, text, expected_regexp, msg=None): """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regexp, basestring): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): msg = msg or "Regexp didn't match" msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text) raise self.failureException(msg)
Fail the test unless the text matches the regular expression.
assertRegexpMatches
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regexp, basestring): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) if match: msg = msg or "Regexp matched" msg = '%s: %r matches %r in %r' % (msg, text[match.start():match.end()], unexpected_regexp.pattern, text) raise self.failureException(msg)
Fail the test if the text matches the regular expression.
assertNotRegexpMatches
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/case.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/case.py
MIT
def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all tests cases contained in testCaseClass""" if issubclass(testCaseClass, suite.TestSuite): raise TypeError("Test cases should not be derived from TestSuite." \ " Maybe you meant to derive from TestCase?") testCaseNames = self.getTestCaseNames(testCaseClass) if not testCaseNames and hasattr(testCaseClass, 'runTest'): testCaseNames = ['runTest'] loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) return loaded_suite
Return a suite of all tests cases contained in testCaseClass
loadTestsFromTestCase
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/loader.py
MIT
def loadTestsFromModule(self, module, use_load_tests=True): """Return a suite of all tests cases contained in the given module""" tests = [] for name in dir(module): obj = getattr(module, name) if isinstance(obj, type) and issubclass(obj, case.TestCase): tests.append(self.loadTestsFromTestCase(obj)) load_tests = getattr(module, 'load_tests', None) tests = self.suiteClass(tests) if use_load_tests and load_tests is not None: try: return load_tests(self, tests, None) except Exception, e: return _make_failed_load_tests(module.__name__, e, self.suiteClass) return tests
Return a suite of all tests cases contained in the given module
loadTestsFromModule
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/loader.py
MIT
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module. """ parts = name.split('.') if module is None: parts_copy = parts[:] while parts_copy: try: module = __import__('.'.join(parts_copy)) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: parent, obj = obj, getattr(obj, part) if isinstance(obj, types.ModuleType): return self.loadTestsFromModule(obj) elif isinstance(obj, type) and issubclass(obj, case.TestCase): return self.loadTestsFromTestCase(obj) elif (isinstance(obj, types.UnboundMethodType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): name = parts[-1] inst = parent(name) return self.suiteClass([inst]) elif isinstance(obj, suite.TestSuite): return obj elif hasattr(obj, '__call__'): test = obj() if isinstance(test, suite.TestSuite): return test elif isinstance(test, case.TestCase): return self.suiteClass([test]) else: raise TypeError("calling %s returned %s, not a test" % (obj, test)) else: raise TypeError("don't know how to make test from: %s" % obj)
Return a suite of all tests cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module.
loadTestsFromName
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/loader.py
MIT
def getTestCaseNames(self, testCaseClass): """Return a sorted sequence of method names found within testCaseClass """ def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and \ hasattr(getattr(testCaseClass, attrname), '__call__') testFnNames = filter(isTestMethod, dir(testCaseClass)) if self.sortTestMethodsUsing: testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing)) return testFnNames
Return a sorted sequence of method names found within testCaseClass
getTestCaseNames
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/loader.py
MIT
def discover(self, start_dir, pattern='test*.py', top_level_dir=None): """Find and return all test modules from the specified start directory, recursing into subdirectories to find them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with loader, tests, pattern. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover(). """ set_implicit_top = False if top_level_dir is None and self._top_level_dir is not None: # make top_level_dir optional if called from load_tests in a package top_level_dir = self._top_level_dir elif top_level_dir is None: set_implicit_top = True top_level_dir = start_dir top_level_dir = os.path.abspath(top_level_dir) if not top_level_dir in sys.path: # all test modules must be importable from the top level directory # should we *unconditionally* put the start directory in first # in sys.path to minimise likelihood of conflicts between installed # modules and development versions? sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False if os.path.isdir(os.path.abspath(start_dir)): start_dir = os.path.abspath(start_dir) if start_dir != top_level_dir: is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py')) else: # support for discovery from dotted module names try: __import__(start_dir) except ImportError: is_not_importable = True else: the_module = sys.modules[start_dir] top_part = start_dir.split('.')[0] start_dir = os.path.abspath(os.path.dirname((the_module.__file__))) if set_implicit_top: self._top_level_dir = self._get_directory_containing_module(top_part) sys.path.remove(top_level_dir) if is_not_importable: raise ImportError('Start directory is not importable: %r' % start_dir) tests = list(self._find_tests(start_dir, pattern)) return self.suiteClass(tests)
Find and return all test modules from the specified start directory, recursing into subdirectories to find them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with loader, tests, pattern. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover().
discover
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/loader.py
MIT
def _find_tests(self, start_dir, pattern): """Used by discovery. Yields test suites it loads.""" paths = os.listdir(start_dir) for path in paths: full_path = os.path.join(start_dir, path) if os.path.isfile(full_path): if not VALID_MODULE_NAME.match(path): # valid Python identifiers only continue if not self._match_path(path, full_path, pattern): continue # if the test file matches, load it name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) except: yield _make_failed_import_test(name, self.suiteClass) else: mod_file = os.path.abspath(getattr(module, '__file__', full_path)) realpath = os.path.splitext(os.path.realpath(mod_file))[0] fullpath_noext = os.path.splitext(os.path.realpath(full_path))[0] if realpath.lower() != fullpath_noext.lower(): module_dir = os.path.dirname(realpath) mod_name = os.path.splitext(os.path.basename(full_path))[0] expected_dir = os.path.dirname(full_path) msg = ("%r module incorrectly imported from %r. Expected %r. " "Is this module globally installed?") raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): continue load_tests = None tests = None if fnmatch(path, pattern): # only check load_tests if the package directory itself matches the filter name = self._get_name_from_path(full_path) package = self._get_module_from_name(name) load_tests = getattr(package, 'load_tests', None) tests = self.loadTestsFromModule(package, use_load_tests=False) if load_tests is None: if tests is not None: # tests loaded from package file yield tests # recurse into the package for test in self._find_tests(full_path, pattern): yield test else: try: yield load_tests(self, tests, pattern) except Exception, e: yield _make_failed_load_tests(package.__name__, e, self.suiteClass)
Used by discovery. Yields test suites it loads.
_find_tests
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/loader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/loader.py
MIT
def startTest(self, test): "Called when the given test is about to be run" self.testsRun += 1 self._mirrorOutput = False self._setupStdout()
Called when the given test is about to be run
startTest
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def startTestRun(self): """Called once before any tests are executed. See startTest for a method called before each test. """
Called once before any tests are executed. See startTest for a method called before each test.
startTestRun
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def stopTest(self, test): """Called when the given test has been run""" self._restoreStdout() self._mirrorOutput = False
Called when the given test has been run
stopTest
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def stopTestRun(self): """Called once after all tests are executed. See stopTest for a method called after each test. """
Called once after all tests are executed. See stopTest for a method called after each test.
stopTestRun
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ self.errors.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True
Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().
addError
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def addFailure(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().""" self.failures.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True
Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().
addFailure
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def addExpectedFailure(self, test, err): """Called when an expected failure/error occurred.""" self.expectedFailures.append( (test, self._exc_info_to_string(err, test)))
Called when an expected failure/error occurred.
addExpectedFailure
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def wasSuccessful(self): "Tells whether or not this result was a success" return len(self.failures) == len(self.errors) == 0
Tells whether or not this result was a success
wasSuccessful
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def stop(self): "Indicates that the tests should be aborted" self.shouldStop = True
Indicates that the tests should be aborted
stop
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def _exc_info_to_string(self, err, test): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: # Skip assert*() traceback levels length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' msgLines.append(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' msgLines.append(STDERR_LINE % error) return ''.join(msgLines)
Converts a sys.exc_info()-style tuple of values into a string.
_exc_info_to_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/result.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/result.py
MIT
def run(self, test): "Run the given test case or test suite." result = self._makeResult() registerResult(result) result.failfast = self.failfast result.buffer = self.buffer startTime = time.time() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() try: test(result) finally: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() stopTime = time.time() timeTaken = stopTime - startTime result.printErrors() if hasattr(result, 'separator2'): self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run != 1 and "s" or "", timeTaken)) self.stream.writeln() expectedFails = unexpectedSuccesses = skipped = 0 try: results = map(len, (result.expectedFailures, result.unexpectedSuccesses, result.skipped)) except AttributeError: pass else: expectedFails, unexpectedSuccesses, skipped = results infos = [] if not result.wasSuccessful(): self.stream.write("FAILED") failed, errored = map(len, (result.failures, result.errors)) if failed: infos.append("failures=%d" % failed) if errored: infos.append("errors=%d" % errored) else: self.stream.write("OK") if skipped: infos.append("skipped=%d" % skipped) if expectedFails: infos.append("expected failures=%d" % expectedFails) if unexpectedSuccesses: infos.append("unexpected successes=%d" % unexpectedSuccesses) if infos: self.stream.writeln(" (%s)" % (", ".join(infos),)) else: self.stream.write("\n") return result
Run the given test case or test suite.
run
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/runner.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/runner.py
MIT
def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False
A crude way to tell apart testcases and suites with duck-typing
_isnotsuite
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/suite.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/suite.py
MIT
def sorted_list_difference(expected, actual): """Finds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those elements in the "expected" list but not in the "actual" list, and the second contains those elements in the "actual" list but not in the "expected" list. Duplicate elements in either input list are ignored. """ i = j = 0 missing = [] unexpected = [] while True: try: e = expected[i] a = actual[j] if e < a: missing.append(e) i += 1 while expected[i] == e: i += 1 elif e > a: unexpected.append(a) j += 1 while actual[j] == a: j += 1 else: i += 1 try: while expected[i] == e: i += 1 finally: j += 1 while actual[j] == a: j += 1 except IndexError: missing.extend(expected[i:]) unexpected.extend(actual[j:]) break return missing, unexpected
Finds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those elements in the "expected" list but not in the "actual" list, and the second contains those elements in the "actual" list but not in the "expected" list. Duplicate elements in either input list are ignored.
sorted_list_difference
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/util.py
MIT
def unorderable_list_difference(expected, actual, ignore_duplicate=False): """Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance. """ missing = [] unexpected = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) if ignore_duplicate: for lst in expected, actual: try: while True: lst.remove(item) except ValueError: pass if ignore_duplicate: while actual: item = actual.pop() unexpected.append(item) try: while True: actual.remove(item) except ValueError: pass return missing, unexpected # anything left in actual is unexpected return missing, actual
Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance.
unorderable_list_difference
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/util.py
MIT
def _count_diff_all_purpose(actual, expected): 'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ' # elements need not be hashable s, t = list(actual), list(expected) m, n = len(s), len(t) NULL = object() result = [] for i, elem in enumerate(s): if elem is NULL: continue cnt_s = cnt_t = 0 for j in range(i, m): if s[j] == elem: cnt_s += 1 s[j] = NULL for j, other_elem in enumerate(t): if other_elem == elem: cnt_t += 1 t[j] = NULL if cnt_s != cnt_t: diff = _Mismatch(cnt_s, cnt_t, elem) result.append(diff) for i, elem in enumerate(t): if elem is NULL: continue cnt_t = 0 for j in range(i, n): if t[j] == elem: cnt_t += 1 t[j] = NULL diff = _Mismatch(0, cnt_t, elem) result.append(diff) return result
Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ
_count_diff_all_purpose
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/util.py
MIT
def _ordered_count(iterable): 'Return dict of element counts, in the order they were first seen' c = OrderedDict() for elem in iterable: c[elem] = c.get(elem, 0) + 1 return c
Return dict of element counts, in the order they were first seen
_ordered_count
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/util.py
MIT
def _count_diff_hashable(actual, expected): 'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ' # elements must be hashable s, t = _ordered_count(actual), _ordered_count(expected) result = [] for elem, cnt_s in s.items(): cnt_t = t.get(elem, 0) if cnt_s != cnt_t: diff = _Mismatch(cnt_s, cnt_t, elem) result.append(diff) for elem, cnt_t in t.items(): if elem not in s: diff = _Mismatch(0, cnt_t, elem) result.append(diff) return result
Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ
_count_diff_hashable
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/unittest/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/unittest/util.py
MIT
def setup_environ(self): """Set up the environment for one request""" env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread'] = self.wsgi_multithread env['wsgi.multiprocess'] = self.wsgi_multiprocess if self.wsgi_file_wrapper is not None: env['wsgi.file_wrapper'] = self.wsgi_file_wrapper if self.origin_server and self.server_software: env.setdefault('SERVER_SOFTWARE',self.server_software)
Set up the environment for one request
setup_environ
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def finish_response(self): """Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call 'self.close()' once the response is finished. """ try: if not self.result_is_file() or not self.sendfile(): for data in self.result: self.write(data) self.finish_content() finally: self.close()
Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call 'self.close()' once the response is finished.
finish_response
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def set_content_length(self): """Compute Content-Length or switch to chunked encoding if possible""" try: blocks = len(self.result) except (TypeError,AttributeError,NotImplementedError): pass else: if blocks==1: self.headers['Content-Length'] = str(self.bytes_sent) return # XXX Try for chunked encoding if origin server and client is 1.1
Compute Content-Length or switch to chunked encoding if possible
set_content_length
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def write(self, data): """'write()' callable as specified by PEP 333""" assert type(data) is StringType,"write() argument must be string" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: self.bytes_sent += len(data) # XXX check Content-Length and truncate if too many bytes written? self._write(data) self._flush()
'write()' callable as specified by PEP 333
write
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def finish_content(self): """Ensure headers and content have both been sent""" if not self.headers_sent: # Only zero Content-Length if not set by the application (so # that HEAD requests can be satisfied properly, see #3839) self.headers.setdefault('Content-Length', "0") self.send_headers() else: pass # XXX check if content-length was too short?
Ensure headers and content have both been sent
finish_content
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def close(self): """Close the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection. """ try: if hasattr(self.result,'close'): self.result.close() finally: self.result = self.headers = self.status = self.environ = None self.bytes_sent = 0; self.headers_sent = False
Close the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection.
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def result_is_file(self): """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'""" wrapper = self.wsgi_file_wrapper return wrapper is not None and isinstance(self.result,wrapper)
True if 'self.result' is an instance of 'self.wsgi_file_wrapper'
result_is_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def log_exception(self,exc_info): """Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. """ try: from traceback import print_exception stderr = self.get_stderr() print_exception( exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr ) stderr.flush() finally: exc_info = None
Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format.
log_exception
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def handle_error(self): """Log current error, and send error output to client if possible""" self.log_exception(sys.exc_info()) if not self.headers_sent: self.result = self.error_output(self.environ, self.start_response) self.finish_response() # XXX else: attempt advanced recovery techniques for HTML or text?
Log current error, and send error output to client if possible
handle_error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/handlers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/handlers.py
MIT
def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: if quote or tspecials.search(value): value = value.replace('\\', '\\\\').replace('"', r'\"') return '%s="%s"' % (param, value) else: return '%s=%s' % (param, value) else: return param
Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true.
_formatparam
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/headers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/headers.py
MIT
def __delitem__(self,name): """Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing. """ name = name.lower() self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name]
Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing.
__delitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/headers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/headers.py
MIT
def get_all(self, name): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list. """ name = name.lower() return [kv[1] for kv in self._headers if kv[0].lower()==name]
Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list.
get_all
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/headers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/headers.py
MIT
def get(self,name,default=None): """Get the first header value for 'name', or return 'default'""" name = name.lower() for k,v in self._headers: if k.lower()==name: return v return default
Get the first header value for 'name', or return 'default'
get
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/headers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/headers.py
MIT
def setdefault(self,name,value): """Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'.""" result = self.get(name) if result is None: self._headers.append((name,value)) return value else: return result
Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'.
setdefault
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/headers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/headers.py
MIT
def add_header(self, _name, _value, **_params): """Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None. """ parts = [] if _value is not None: parts.append(_value) for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, "; ".join(parts)))
Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None.
add_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/headers.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/headers.py
MIT
def make_server( host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler ): """Create a new WSGI server listening on `host` and `port` for `app`""" server = server_class((host, port), handler_class) server.set_app(app) return server
Create a new WSGI server listening on `host` and `port` for `app`
make_server
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/simple_server.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/simple_server.py
MIT
def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http'
Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
guess_scheme
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/util.py
MIT
def application_uri(environ): """Return the application's base URI (no PATH_INFO or QUERY_STRING)""" url = environ['wsgi.url_scheme']+'://' from urllib import quote if environ.get('HTTP_HOST'): url += environ['HTTP_HOST'] else: url += environ['SERVER_NAME'] if environ['wsgi.url_scheme'] == 'https': if environ['SERVER_PORT'] != '443': url += ':' + environ['SERVER_PORT'] else: if environ['SERVER_PORT'] != '80': url += ':' + environ['SERVER_PORT'] url += quote(environ.get('SCRIPT_NAME') or '/') return url
Return the application's base URI (no PATH_INFO or QUERY_STRING)
application_uri
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/util.py
MIT
def request_uri(environ, include_query=1): """Return the full request URI, optionally including the query string""" url = application_uri(environ) from urllib import quote path_info = quote(environ.get('PATH_INFO',''),safe='/;=,') if not environ.get('SCRIPT_NAME'): url += path_info[1:] else: url += path_info if include_query and environ.get('QUERY_STRING'): url += '?' + environ['QUERY_STRING'] return url
Return the full request URI, optionally including the query string
request_uri
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/util.py
MIT
def shift_path_info(environ): """Shift a name from PATH_INFO to SCRIPT_NAME, returning it If there are no remaining path segments in PATH_INFO, return None. Note: 'environ' is modified in-place; use a copy if you need to keep the original PATH_INFO or SCRIPT_NAME. Note: when PATH_INFO is just a '/', this returns '' and appends a trailing '/' to SCRIPT_NAME, even though empty path segments are normally ignored, and SCRIPT_NAME doesn't normally end in a '/'. This is intentional behavior, to ensure that an application can tell the difference between '/x' and '/x/' when traversing to objects. """ path_info = environ.get('PATH_INFO','') if not path_info: return None path_parts = path_info.split('/') path_parts[1:-1] = [p for p in path_parts[1:-1] if p and p != '.'] name = path_parts[1] del path_parts[1] script_name = environ.get('SCRIPT_NAME','') script_name = posixpath.normpath(script_name+'/'+name) if script_name.endswith('/'): script_name = script_name[:-1] if not name and not script_name.endswith('/'): script_name += '/' environ['SCRIPT_NAME'] = script_name environ['PATH_INFO'] = '/'.join(path_parts) # Special case: '/.' on PATH_INFO doesn't get stripped, # because we don't strip the last element of PATH_INFO # if there's only one path part left. Instead of fixing this # above, we fix it here so that PATH_INFO gets normalized to # an empty string in the environ. if name=='.': name = None return name
Shift a name from PATH_INFO to SCRIPT_NAME, returning it If there are no remaining path segments in PATH_INFO, return None. Note: 'environ' is modified in-place; use a copy if you need to keep the original PATH_INFO or SCRIPT_NAME. Note: when PATH_INFO is just a '/', this returns '' and appends a trailing '/' to SCRIPT_NAME, even though empty path segments are normally ignored, and SCRIPT_NAME doesn't normally end in a '/'. This is intentional behavior, to ensure that an application can tell the difference between '/x' and '/x/' when traversing to objects.
shift_path_info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/util.py
MIT
def setup_testing_defaults(environ): """Update 'environ' with trivial defaults for testing purposes This adds various parameters required for WSGI, including HTTP_HOST, SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, and all of the wsgi.* variables. It only supplies default values, and does not replace any existing settings for these variables. This routine is intended to make it easier for unit tests of WSGI servers and applications to set up dummy environments. It should *not* be used by actual WSGI servers or applications, since the data is fake! """ environ.setdefault('SERVER_NAME','127.0.0.1') environ.setdefault('SERVER_PROTOCOL','HTTP/1.0') environ.setdefault('HTTP_HOST',environ['SERVER_NAME']) environ.setdefault('REQUEST_METHOD','GET') if 'SCRIPT_NAME' not in environ and 'PATH_INFO' not in environ: environ.setdefault('SCRIPT_NAME','') environ.setdefault('PATH_INFO','/') environ.setdefault('wsgi.version', (1,0)) environ.setdefault('wsgi.run_once', 0) environ.setdefault('wsgi.multithread', 0) environ.setdefault('wsgi.multiprocess', 0) from StringIO import StringIO environ.setdefault('wsgi.input', StringIO("")) environ.setdefault('wsgi.errors', StringIO()) environ.setdefault('wsgi.url_scheme',guess_scheme(environ)) if environ['wsgi.url_scheme']=='http': environ.setdefault('SERVER_PORT', '80') elif environ['wsgi.url_scheme']=='https': environ.setdefault('SERVER_PORT', '443')
Update 'environ' with trivial defaults for testing purposes This adds various parameters required for WSGI, including HTTP_HOST, SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, and all of the wsgi.* variables. It only supplies default values, and does not replace any existing settings for these variables. This routine is intended to make it easier for unit tests of WSGI servers and applications to set up dummy environments. It should *not* be used by actual WSGI servers or applications, since the data is fake!
setup_testing_defaults
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/util.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/util.py
MIT
def validator(application): """ When applied between a WSGI server and a WSGI application, this middleware will check for WSGI compliancy on a number of levels. This middleware does not modify the request or response in any way, but will raise an AssertionError if anything seems off (except for a failure to close the application iterator, which will be printed to stderr -- there's no way to raise an exception at that point). """ def lint_app(*args, **kw): assert_(len(args) == 2, "Two arguments required") assert_(not kw, "No keyword arguments allowed") environ, start_response = args check_environ(environ) # We use this to check if the application returns without # calling start_response: start_response_started = [] def start_response_wrapper(*args, **kw): assert_(len(args) == 2 or len(args) == 3, ( "Invalid number of arguments: %s" % (args,))) assert_(not kw, "No keyword arguments allowed") status = args[0] headers = args[1] if len(args) == 3: exc_info = args[2] else: exc_info = None check_status(status) check_headers(headers) check_content_type(status, headers) check_exc_info(exc_info) start_response_started.append(None) return WriteWrapper(start_response(*args)) environ['wsgi.input'] = InputWrapper(environ['wsgi.input']) environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors']) iterator = application(environ, start_response_wrapper) assert_(iterator is not None and iterator != False, "The application must return an iterator, if only an empty list") check_iterator(iterator) return IteratorWrapper(iterator, start_response_started) return lint_app
When applied between a WSGI server and a WSGI application, this middleware will check for WSGI compliancy on a number of levels. This middleware does not modify the request or response in any way, but will raise an AssertionError if anything seems off (except for a failure to close the application iterator, which will be printed to stderr -- there's no way to raise an exception at that point).
validator
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/wsgiref/validate.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/validate.py
MIT
def _good_enough(dom, features): "_good_enough(dom, features) -> Return 1 if the dom offers the features" for f,v in features: if not dom.hasFeature(f,v): return 0 return 1
_good_enough(dom, features) -> Return 1 if the dom offers the features
_good_enough
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/domreg.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/domreg.py
MIT
def getDOMImplementation(name = None, features = ()): """getDOMImplementation(name = None, features = ()) -> DOM implementation. Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns DOMImplementation object if the import succeeds. If name is not given, consider the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to hasFeature.""" import os creator = None mod = well_known_implementations.get(name) if mod: mod = __import__(mod, {}, {}, ['getDOMImplementation']) return mod.getDOMImplementation() elif name: return registered[name]() elif "PYTHON_DOM" in os.environ: return getDOMImplementation(name = os.environ["PYTHON_DOM"]) # User did not specify a name, try implementations in arbitrary # order, returning the one that has the required features if isinstance(features, StringTypes): features = _parse_feature_string(features) for creator in registered.values(): dom = creator() if _good_enough(dom, features): return dom for creator in well_known_implementations.keys(): try: dom = getDOMImplementation(name = creator) except StandardError: # typically ImportError, or AttributeError continue if _good_enough(dom, features): return dom raise ImportError,"no suitable DOM implementation found"
getDOMImplementation(name = None, features = ()) -> DOM implementation. Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns DOMImplementation object if the import succeeds. If name is not given, consider the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature, version) pairs which are passed to hasFeature.
getDOMImplementation
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/domreg.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/domreg.py
MIT
def getParser(self): """Return the parser object, creating a new one if needed.""" if not self._parser: self._parser = self.createParser() self._intern_setdefault = self._parser.intern.setdefault self._parser.buffer_text = True self._parser.ordered_attributes = True self._parser.specified_attributes = True self.install(self._parser) return self._parser
Return the parser object, creating a new one if needed.
getParser
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def reset(self): """Free all data structures used during DOM construction.""" self.document = theDOMImplementation.createDocument( EMPTY_NAMESPACE, None, None) self.curNode = self.document self._elem_info = self.document._elem_info self._cdata = False
Free all data structures used during DOM construction.
reset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def install(self, parser): """Install the callbacks needed to build the DOM into the parser.""" # This creates circular references! parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.first_element_handler parser.EndElementHandler = self.end_element_handler parser.ProcessingInstructionHandler = self.pi_handler if self._options.entities: parser.EntityDeclHandler = self.entity_decl_handler parser.NotationDeclHandler = self.notation_decl_handler if self._options.comments: parser.CommentHandler = self.comment_handler if self._options.cdata_sections: parser.StartCdataSectionHandler = self.start_cdata_section_handler parser.EndCdataSectionHandler = self.end_cdata_section_handler parser.CharacterDataHandler = self.character_data_handler_cdata else: parser.CharacterDataHandler = self.character_data_handler parser.ExternalEntityRefHandler = self.external_entity_ref_handler parser.XmlDeclHandler = self.xml_decl_handler parser.ElementDeclHandler = self.element_decl_handler parser.AttlistDeclHandler = self.attlist_decl_handler
Install the callbacks needed to build the DOM into the parser.
install
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def parseFile(self, file): """Parse a document from a file object, returning the document node.""" parser = self.getParser() first_buffer = True try: while 1: buffer = file.read(16*1024) if not buffer: break parser.Parse(buffer, 0) if first_buffer and self.document.documentElement: self._setup_subset(buffer) first_buffer = False parser.Parse("", True) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
Parse a document from a file object, returning the document node.
parseFile
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT