path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/third_party/python/Lib/operator.py
""" Operator Interface This module exports a set of functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special methods; variants without leading and trailing '__' are also provided for convenience. This is the pure Python implementation of the module. """ __all__ = ['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf', 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand', 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul', 'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift', 'is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le', 'length_hint', 'lshift', 'lt', 'matmul', 'methodcaller', 'mod', 'mul', 'ne', 'neg', 'not_', 'or_', 'pos', 'pow', 'rshift', 'setitem', 'sub', 'truediv', 'truth', 'xor'] from builtins import abs as _abs # Comparison Operations *******************************************************# def lt(a, b): "Same as a < b." return a < b def le(a, b): "Same as a <= b." return a <= b def eq(a, b): "Same as a == b." return a == b def ne(a, b): "Same as a != b." return a != b def ge(a, b): "Same as a >= b." return a >= b def gt(a, b): "Same as a > b." return a > b # Logical Operations **********************************************************# def not_(a): "Same as not a." return not a def truth(a): "Return True if a is true, False otherwise." return True if a else False def is_(a, b): "Same as a is b." return a is b def is_not(a, b): "Same as a is not b." return a is not b # Mathematical/Bitwise Operations *********************************************# def abs(a): "Same as abs(a)." return _abs(a) def add(a, b): "Same as a + b." return a + b def and_(a, b): "Same as a & b." return a & b def floordiv(a, b): "Same as a // b." return a // b def index(a): "Same as a.__index__()." return a.__index__() def inv(a): "Same as ~a." return ~a invert = inv def lshift(a, b): "Same as a << b." return a << b def mod(a, b): "Same as a % b." return a % b def mul(a, b): "Same as a * b." return a * b def matmul(a, b): "Same as a @ b." return a @ b def neg(a): "Same as -a." return -a def or_(a, b): "Same as a | b." return a | b def pos(a): "Same as +a." return +a def pow(a, b): "Same as a ** b." return a ** b def rshift(a, b): "Same as a >> b." return a >> b def sub(a, b): "Same as a - b." return a - b def truediv(a, b): "Same as a / b." return a / b def xor(a, b): "Same as a ^ b." return a ^ b # Sequence Operations *********************************************************# def concat(a, b): "Same as a + b, for a and b sequences." if not hasattr(a, '__getitem__'): msg = "'%s' object can't be concatenated" % type(a).__name__ raise TypeError(msg) return a + b def contains(a, b): "Same as b in a (note reversed operands)." return b in a def countOf(a, b): "Return the number of times b occurs in a." count = 0 for i in a: if i == b: count += 1 return count def delitem(a, b): "Same as del a[b]." del a[b] def getitem(a, b): "Same as a[b]." return a[b] def indexOf(a, b): "Return the first index of b in a." for i, j in enumerate(a): if j == b: return i else: raise ValueError('sequence.index(x): x not in sequence') def setitem(a, b, c): "Same as a[b] = c." a[b] = c def length_hint(obj, default=0): """ Return an estimate of the number of items in obj. This is useful for presizing containers when building from an iterable. If the object supports len(), the result will be exact. Otherwise, it may over- or under-estimate by an arbitrary amount. The result will be an integer >= 0. """ if not isinstance(default, int): msg = ("'%s' object cannot be interpreted as an integer" % type(default).__name__) raise TypeError(msg) try: return len(obj) except TypeError: pass try: hint = type(obj).__length_hint__ except AttributeError: return default try: val = hint(obj) except TypeError: return default if val is NotImplemented: return default if not isinstance(val, int): msg = ('__length_hint__ must be integer, not %s' % type(val).__name__) raise TypeError(msg) if val < 0: msg = '__length_hint__() should return >= 0' raise ValueError(msg) return val # Generalized Lookup Objects **************************************************# class attrgetter: """ Return a callable object that fetches the given attribute(s) from its operand. After f = attrgetter('name'), the call f(r) returns r.name. After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). After h = attrgetter('name.first', 'name.last'), the call h(r) returns (r.name.first, r.name.last). """ __slots__ = ('_attrs', '_call') def __init__(self, attr, *attrs): if not attrs: if not isinstance(attr, str): raise TypeError('attribute name must be a string') self._attrs = (attr,) names = attr.split('.') def func(obj): for name in names: obj = getattr(obj, name) return obj self._call = func else: self._attrs = (attr,) + attrs getters = tuple(map(attrgetter, self._attrs)) def func(obj): return tuple(getter(obj) for getter in getters) self._call = func def __call__(self, obj): return self._call(obj) def __repr__(self): return '%s.%s(%s)' % (self.__class__.__module__, self.__class__.__qualname__, ', '.join(map(repr, self._attrs))) def __reduce__(self): return self.__class__, self._attrs class itemgetter: """ Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]) """ __slots__ = ('_items', '_call') def __init__(self, item, *items): if not items: self._items = (item,) def func(obj): return obj[item] self._call = func else: self._items = items = (item,) + items def func(obj): return tuple(obj[i] for i in items) self._call = func def __call__(self, obj): return self._call(obj) def __repr__(self): return '%s.%s(%s)' % (self.__class__.__module__, self.__class__.__name__, ', '.join(map(repr, self._items))) def __reduce__(self): return self.__class__, self._items class methodcaller: """ Return a callable object that calls the given method on its operand. After f = methodcaller('name'), the call f(r) returns r.name(). After g = methodcaller('name', 'date', foo=1), the call g(r) returns r.name('date', foo=1). """ __slots__ = ('_name', '_args', '_kwargs') def __init__(*args, **kwargs): if len(args) < 2: msg = "methodcaller needs at least one argument, the method name" raise TypeError(msg) self = args[0] self._name = args[1] if not isinstance(self._name, str): raise TypeError('method name must be a string') self._args = args[2:] self._kwargs = kwargs def __call__(self, obj): return getattr(obj, self._name)(*self._args, **self._kwargs) def __repr__(self): args = [repr(self._name)] args.extend(map(repr, self._args)) args.extend('%s=%r' % (k, v) for k, v in self._kwargs.items()) return '%s.%s(%s)' % (self.__class__.__module__, self.__class__.__name__, ', '.join(args)) def __reduce__(self): if not self._kwargs: return self.__class__, (self._name,) + self._args else: from functools import partial return partial(self.__class__, self._name, **self._kwargs), self._args # In-place Operations *********************************************************# def iadd(a, b): "Same as a += b." a += b return a def iand(a, b): "Same as a &= b." a &= b return a def iconcat(a, b): "Same as a += b, for a and b sequences." if not hasattr(a, '__getitem__'): msg = "'%s' object can't be concatenated" % type(a).__name__ raise TypeError(msg) a += b return a def ifloordiv(a, b): "Same as a //= b." a //= b return a def ilshift(a, b): "Same as a <<= b." a <<= b return a def imod(a, b): "Same as a %= b." a %= b return a def imul(a, b): "Same as a *= b." a *= b return a def imatmul(a, b): "Same as a @= b." a @= b return a def ior(a, b): "Same as a |= b." a |= b return a def ipow(a, b): "Same as a **= b." a **=b return a def irshift(a, b): "Same as a >>= b." a >>= b return a def isub(a, b): "Same as a -= b." a -= b return a def itruediv(a, b): "Same as a /= b." a /= b return a def ixor(a, b): "Same as a ^= b." a ^= b return a try: from _operator import * except ImportError: pass else: try: from _operator import __doc__ except ImportError: pass if __name__ == 'PYOBJ.COM': import _operator # All of these "__func__ = func" assignments have to happen after importing # from _operator to make sure they're set to the right function __lt__ = lt __le__ = le __eq__ = eq __ne__ = ne __ge__ = ge __gt__ = gt __not__ = not_ __abs__ = abs __add__ = add __and__ = and_ __floordiv__ = floordiv __index__ = index __inv__ = inv __invert__ = invert __lshift__ = lshift __mod__ = mod __mul__ = mul __matmul__ = matmul __neg__ = neg __or__ = or_ __pos__ = pos __pow__ = pow __rshift__ = rshift __sub__ = sub __truediv__ = truediv __xor__ = xor __concat__ = concat __contains__ = contains __delitem__ = delitem __getitem__ = getitem __setitem__ = setitem __iadd__ = iadd __iand__ = iand __iconcat__ = iconcat __ifloordiv__ = ifloordiv __ilshift__ = ilshift __imod__ = imod __imul__ = imul __imatmul__ = imatmul __ior__ = ior __ipow__ = ipow __irshift__ = irshift __isub__ = isub __itruediv__ = itruediv __ixor__ = ixor
10,963
471
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/sre_constants.py
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support module for sre""" # update when constants are added or removed MAGIC = 20140917 from _sre import MAXREPEAT, MAXGROUPS # SRE standard exception (access as sre.error) # should this really be here? class error(Exception): """Exception raised for invalid regular expressions. Attributes: msg: The unformatted error message pattern: The regular expression pattern pos: The index in the pattern where compilation failed (may be None) lineno: The line corresponding to pos (may be None) colno: The column corresponding to pos (may be None) """ def __init__(self, msg, pattern=None, pos=None): self.msg = msg self.pattern = pattern self.pos = pos if pattern is not None and pos is not None: msg = '%s at position %d' % (msg, pos) if isinstance(pattern, str): newline = '\n' else: newline = b'\n' self.lineno = pattern.count(newline, 0, pos) + 1 self.colno = pos - pattern.rfind(newline, 0, pos) if newline in pattern: msg = '%s (line %d, column %d)' % (msg, self.lineno, self.colno) else: self.lineno = self.colno = None super().__init__(msg) class _NamedIntConstant(int): def __new__(cls, value, name): self = super(_NamedIntConstant, cls).__new__(cls, value) self.name = name return self def __str__(self): return self.name __repr__ = __str__ MAXREPEAT = _NamedIntConstant(MAXREPEAT, 'MAXREPEAT') def _makecodes(names): names = names.strip().split() items = [_NamedIntConstant(i, name) for i, name in enumerate(names)] globals().update({item.name: item for item in items}) return items # operators # failure=0 success=1 (just because it looks better that way :-) OPCODES = _makecodes(""" FAILURE SUCCESS ANY ANY_ALL ASSERT ASSERT_NOT AT BRANCH CALL CATEGORY CHARSET BIGCHARSET GROUPREF GROUPREF_EXISTS GROUPREF_IGNORE IN IN_IGNORE INFO JUMP LITERAL LITERAL_IGNORE MARK MAX_UNTIL MIN_UNTIL NOT_LITERAL NOT_LITERAL_IGNORE NEGATE RANGE REPEAT REPEAT_ONE SUBPATTERN MIN_REPEAT_ONE RANGE_IGNORE MIN_REPEAT MAX_REPEAT """) del OPCODES[-2:] # remove MIN_REPEAT and MAX_REPEAT # positions ATCODES = _makecodes(""" AT_BEGINNING AT_BEGINNING_LINE AT_BEGINNING_STRING AT_BOUNDARY AT_NON_BOUNDARY AT_END AT_END_LINE AT_END_STRING AT_LOC_BOUNDARY AT_LOC_NON_BOUNDARY AT_UNI_BOUNDARY AT_UNI_NON_BOUNDARY """) # categories CHCODES = _makecodes(""" CATEGORY_DIGIT CATEGORY_NOT_DIGIT CATEGORY_SPACE CATEGORY_NOT_SPACE CATEGORY_WORD CATEGORY_NOT_WORD CATEGORY_LINEBREAK CATEGORY_NOT_LINEBREAK CATEGORY_LOC_WORD CATEGORY_LOC_NOT_WORD CATEGORY_UNI_DIGIT CATEGORY_UNI_NOT_DIGIT CATEGORY_UNI_SPACE CATEGORY_UNI_NOT_SPACE CATEGORY_UNI_WORD CATEGORY_UNI_NOT_WORD CATEGORY_UNI_LINEBREAK CATEGORY_UNI_NOT_LINEBREAK """) # replacement operations for "ignore case" mode OP_IGNORE = { GROUPREF: GROUPREF_IGNORE, IN: IN_IGNORE, LITERAL: LITERAL_IGNORE, NOT_LITERAL: NOT_LITERAL_IGNORE, RANGE: RANGE_IGNORE, } AT_MULTILINE = { AT_BEGINNING: AT_BEGINNING_LINE, AT_END: AT_END_LINE } AT_LOCALE = { AT_BOUNDARY: AT_LOC_BOUNDARY, AT_NON_BOUNDARY: AT_LOC_NON_BOUNDARY } AT_UNICODE = { AT_BOUNDARY: AT_UNI_BOUNDARY, AT_NON_BOUNDARY: AT_UNI_NON_BOUNDARY } CH_LOCALE = { CATEGORY_DIGIT: CATEGORY_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_SPACE, CATEGORY_NOT_SPACE: CATEGORY_NOT_SPACE, CATEGORY_WORD: CATEGORY_LOC_WORD, CATEGORY_NOT_WORD: CATEGORY_LOC_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_NOT_LINEBREAK } CH_UNICODE = { CATEGORY_DIGIT: CATEGORY_UNI_DIGIT, CATEGORY_NOT_DIGIT: CATEGORY_UNI_NOT_DIGIT, CATEGORY_SPACE: CATEGORY_UNI_SPACE, CATEGORY_NOT_SPACE: CATEGORY_UNI_NOT_SPACE, CATEGORY_WORD: CATEGORY_UNI_WORD, CATEGORY_NOT_WORD: CATEGORY_UNI_NOT_WORD, CATEGORY_LINEBREAK: CATEGORY_UNI_LINEBREAK, CATEGORY_NOT_LINEBREAK: CATEGORY_UNI_NOT_LINEBREAK } # flags SRE_FLAG_TEMPLATE = 1 # template mode (disable backtracking) SRE_FLAG_IGNORECASE = 2 # case insensitive SRE_FLAG_LOCALE = 4 # honour system locale SRE_FLAG_MULTILINE = 8 # treat target as multiline string SRE_FLAG_DOTALL = 16 # treat target as a single string SRE_FLAG_UNICODE = 32 # use unicode "locale" SRE_FLAG_VERBOSE = 64 # ignore whitespace and comments SRE_FLAG_DEBUG = 128 # debugging SRE_FLAG_ASCII = 256 # use ascii "locale" # flags for INFO primitive SRE_INFO_PREFIX = 1 # has prefix SRE_INFO_LITERAL = 2 # entire pattern is literal (given by prefix) SRE_INFO_CHARSET = 4 # pattern starts with character from given set if __name__ == "__main__": def dump(f, d, prefix): items = sorted(d) for item in items: f.write("#define %s_%s %d\n" % (prefix, item, item)) with open("sre_constants.h", "w") as f: f.write("""\ /* * Secret Labs' Regular Expression Engine * * regular expression matching engine * * NOTE: This file is generated by sre_constants.py. If you need * to change anything in here, edit sre_constants.py and run it. * * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. * * See the _sre.c file for information on usage and redistribution. */ """) f.write("#define SRE_MAGIC %d\n" % MAGIC) dump(f, OPCODES, "SRE_OP") dump(f, ATCODES, "SRE") dump(f, CHCODES, "SRE") f.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE) f.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE) f.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE) f.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE) f.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL) f.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE) f.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE) f.write("#define SRE_FLAG_DEBUG %d\n" % SRE_FLAG_DEBUG) f.write("#define SRE_FLAG_ASCII %d\n" % SRE_FLAG_ASCII) f.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX) f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL) f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) print("done") if __name__ == 'PYOBJ.COM': ANY = 0 ANY_ALL = 0 ASSERT = 0 ASSERT_NOT = 0 AT = 0 AT_BEGINNING = 0 AT_BEGINNING_LINE = 0 AT_BEGINNING_STRING = 0 AT_BOUNDARY = 0 AT_END = 0 AT_END_LINE = 0 AT_END_STRING = 0 AT_LOC_BOUNDARY = 0 AT_LOC_NON_BOUNDARY = 0 AT_NON_BOUNDARY = 0 AT_UNI_BOUNDARY = 0 AT_UNI_NON_BOUNDARY = 0 BIGCHARSET = 0 BRANCH = 0 CALL = 0 CATEGORY = 0 CATEGORY_DIGIT = 0 CATEGORY_LINEBREAK = 0 CATEGORY_LOC_NOT_WORD = 0 CATEGORY_LOC_WORD = 0 CATEGORY_NOT_DIGIT = 0 CATEGORY_NOT_LINEBREAK = 0 CATEGORY_NOT_SPACE = 0 CATEGORY_NOT_WORD = 0 CATEGORY_SPACE = 0 CATEGORY_UNI_DIGIT = 0 CATEGORY_UNI_LINEBREAK = 0 CATEGORY_UNI_NOT_DIGIT = 0 CATEGORY_UNI_NOT_LINEBREAK = 0 CATEGORY_UNI_NOT_SPACE = 0 CATEGORY_UNI_NOT_WORD = 0 CATEGORY_UNI_SPACE = 0 CATEGORY_UNI_WORD = 0 CATEGORY_WORD = 0 CHARSET = 0 FAILURE = 0 GROUPREF = 0 GROUPREF_EXISTS = 0 GROUPREF_IGNORE = 0 IN = 0 INFO = 0 IN_IGNORE = 0 JUMP = 0 LITERAL = 0 LITERAL_IGNORE = 0 MARK = 0 MAX_REPEAT = 0 MAX_UNTIL = 0 MIN_REPEAT = 0 MIN_REPEAT_ONE = 0 MIN_UNTIL = 0 NEGATE = 0 NOT_LITERAL = 0 NOT_LITERAL_IGNORE = 0 RANGE = 0 RANGE_IGNORE = 0 REPEAT = 0 REPEAT_ONE = 0 SUBPATTERN = 0 SUCCESS = 0
8,227
294
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/lzma.py
"""Interface to the liblzma compression library. This module provides a class for reading and writing compressed files, classes for incremental (de)compression, and convenience functions for one-shot (de)compression. These classes and functions support both the XZ and legacy LZMA container formats, as well as raw compressed data streams. """ __all__ = [ "CHECK_NONE", "CHECK_CRC32", "CHECK_CRC64", "CHECK_SHA256", "CHECK_ID_MAX", "CHECK_UNKNOWN", "FILTER_LZMA1", "FILTER_LZMA2", "FILTER_DELTA", "FILTER_X86", "FILTER_IA64", "FILTER_ARM", "FILTER_ARMTHUMB", "FILTER_POWERPC", "FILTER_SPARC", "FORMAT_AUTO", "FORMAT_XZ", "FORMAT_ALONE", "FORMAT_RAW", "MF_HC3", "MF_HC4", "MF_BT2", "MF_BT3", "MF_BT4", "MODE_FAST", "MODE_NORMAL", "PRESET_DEFAULT", "PRESET_EXTREME", "LZMACompressor", "LZMADecompressor", "LZMAFile", "LZMAError", "open", "compress", "decompress", "is_check_supported", ] import builtins import io import os from _lzma import * from _lzma import _encode_filter_properties, _decode_filter_properties import _compression _MODE_CLOSED = 0 _MODE_READ = 1 # Value 2 no longer used _MODE_WRITE = 3 class LZMAFile(_compression.BaseStream): """A file object providing transparent LZMA (de)compression. An LZMAFile can act as a wrapper for an existing file object, or refer directly to a named file on disk. Note that LZMAFile provides a *binary* file interface - data read is returned as bytes, and data to be written must be given as bytes. """ def __init__(self, filename=None, mode="r", *, format=None, check=-1, preset=None, filters=None): """Open an LZMA-compressed file in binary mode. filename can be either an actual file name (given as a str, bytes, or PathLike object), in which case the named file is opened, or it can be an existing file object to read from or write to. mode can be "r" for reading (default), "w" for (over)writing, "x" for creating exclusively, or "a" for appending. These can equivalently be given as "rb", "wb", "xb" and "ab" respectively. format specifies the container format to use for the file. If mode is "r", this defaults to FORMAT_AUTO. Otherwise, the default is FORMAT_XZ. check specifies the integrity check to use. This argument can only be used when opening a file for writing. For FORMAT_XZ, the default is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not support integrity checks - for these formats, check must be omitted, or be CHECK_NONE. When opening a file for reading, the *preset* argument is not meaningful, and should be omitted. The *filters* argument should also be omitted, except when format is FORMAT_RAW (in which case it is required). When opening a file for writing, the settings used by the compressor can be specified either as a preset compression level (with the *preset* argument), or in detail as a custom filter chain (with the *filters* argument). For FORMAT_XZ and FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset level. For FORMAT_RAW, the caller must always specify a filter chain; the raw compressor does not support preset compression levels. preset (if provided) should be an integer in the range 0-9, optionally OR-ed with the constant PRESET_EXTREME. filters (if provided) should be a sequence of dicts. Each dict should have an entry for "id" indicating ID of the filter, plus additional entries for options to the filter. """ self._fp = None self._closefp = False self._mode = _MODE_CLOSED if mode in ("r", "rb"): if check != -1: raise ValueError("Cannot specify an integrity check " "when opening a file for reading") if preset is not None: raise ValueError("Cannot specify a preset compression " "level when opening a file for reading") if format is None: format = FORMAT_AUTO mode_code = _MODE_READ elif mode in ("w", "wb", "a", "ab", "x", "xb"): if format is None: format = FORMAT_XZ mode_code = _MODE_WRITE self._compressor = LZMACompressor(format=format, check=check, preset=preset, filters=filters) self._pos = 0 else: raise ValueError("Invalid mode: {!r}".format(mode)) if isinstance(filename, (str, bytes, os.PathLike)): if "b" not in mode: mode += "b" self._fp = builtins.open(filename, mode) self._closefp = True self._mode = mode_code elif hasattr(filename, "read") or hasattr(filename, "write"): self._fp = filename self._mode = mode_code else: raise TypeError("filename must be a str, bytes, file or PathLike object") if self._mode == _MODE_READ: raw = _compression.DecompressReader(self._fp, LZMADecompressor, trailing_error=LZMAError, format=format, filters=filters) self._buffer = io.BufferedReader(raw) def close(self): """Flush and close the file. May be called more than once without error. Once the file is closed, any other operation on it will raise a ValueError. """ if self._mode == _MODE_CLOSED: return try: if self._mode == _MODE_READ: self._buffer.close() self._buffer = None elif self._mode == _MODE_WRITE: self._fp.write(self._compressor.flush()) self._compressor = None finally: try: if self._closefp: self._fp.close() finally: self._fp = None self._closefp = False self._mode = _MODE_CLOSED @property def closed(self): """True if this file is closed.""" return self._mode == _MODE_CLOSED def fileno(self): """Return the file descriptor for the underlying file.""" self._check_not_closed() return self._fp.fileno() def seekable(self): """Return whether the file supports seeking.""" return self.readable() and self._buffer.seekable() def readable(self): """Return whether the file was opened for reading.""" self._check_not_closed() return self._mode == _MODE_READ def writable(self): """Return whether the file was opened for writing.""" self._check_not_closed() return self._mode == _MODE_WRITE def peek(self, size=-1): """Return buffered data without advancing the file position. Always returns at least one byte of data, unless at EOF. The exact number of bytes returned is unspecified. """ self._check_can_read() # Relies on the undocumented fact that BufferedReader.peek() always # returns at least one byte (except at EOF) return self._buffer.peek(size) def read(self, size=-1): """Read up to size uncompressed bytes from the file. If size is negative or omitted, read until EOF is reached. Returns b"" if the file is already at EOF. """ self._check_can_read() return self._buffer.read(size) def read1(self, size=-1): """Read up to size uncompressed bytes, while trying to avoid making multiple reads from the underlying stream. Reads up to a buffer's worth of data if size is negative. Returns b"" if the file is at EOF. """ self._check_can_read() if size < 0: size = io.DEFAULT_BUFFER_SIZE return self._buffer.read1(size) def readline(self, size=-1): """Read a line of uncompressed bytes from the file. The terminating newline (if present) is retained. If size is non-negative, no more than size bytes will be read (in which case the line may be incomplete). Returns b'' if already at EOF. """ self._check_can_read() return self._buffer.readline(size) def write(self, data): """Write a bytes object to the file. Returns the number of uncompressed bytes written, which is always len(data). Note that due to buffering, the file on disk may not reflect the data written until close() is called. """ self._check_can_write() compressed = self._compressor.compress(data) self._fp.write(compressed) self._pos += len(data) return len(data) def seek(self, offset, whence=io.SEEK_SET): """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: 0: start of stream (default): offset must not be negative 1: current stream position 2: end of stream; offset must not be positive Returns the new file position. Note that seeking is emulated, so depending on the parameters, this operation may be extremely slow. """ self._check_can_seek() return self._buffer.seek(offset, whence) def tell(self): """Return the current file position.""" self._check_not_closed() if self._mode == _MODE_READ: return self._buffer.tell() return self._pos def open(filename, mode="rb", *, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None): """Open an LZMA-compressed file in binary or text mode. filename can be either an actual file name (given as a str, bytes, or PathLike object), in which case the named file is opened, or it can be an existing file object to read from or write to. The mode argument can be "r", "rb" (default), "w", "wb", "x", "xb", "a", or "ab" for binary mode, or "rt", "wt", "xt", or "at" for text mode. The format, check, preset and filters arguments specify the compression settings, as for LZMACompressor, LZMADecompressor and LZMAFile. For binary mode, this function is equivalent to the LZMAFile constructor: LZMAFile(filename, mode, ...). In this case, the encoding, errors and newline arguments must not be provided. For text mode, an LZMAFile object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s). """ if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if errors is not None: raise ValueError("Argument 'errors' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") lz_mode = mode.replace("t", "") binary_file = LZMAFile(filename, lz_mode, format=format, check=check, preset=preset, filters=filters) if "t" in mode: return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None): """Compress a block of data. Refer to LZMACompressor's docstring for a description of the optional arguments *format*, *check*, *preset* and *filters*. For incremental compression, use an LZMACompressor instead. """ comp = LZMACompressor(format, check, preset, filters) return comp.compress(data) + comp.flush() def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None): """Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. For incremental decompression, use an LZMADecompressor instead. """ results = [] while True: decomp = LZMADecompressor(format, memlimit, filters) try: res = decomp.decompress(data) except LZMAError: if results: break # Leftover data is not a valid LZMA/XZ stream; ignore it. else: raise # Error on the first iteration; bail out. results.append(res) if not decomp.eof: raise LZMAError("Compressed data ended before the " "end-of-stream marker was reached") data = decomp.unused_data if not data: break return b"".join(results)
12,983
348
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/enum.py
import sys from types import MappingProxyType, DynamicClassAttribute from functools import reduce from operator import or_ as _or_ # try _collections first to reduce startup cost try: from _collections import OrderedDict except ImportError: from collections import OrderedDict __all__ = [ 'EnumMeta', 'Enum', 'IntEnum', 'Flag', 'IntFlag', 'auto', 'unique', ] def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise.""" return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')) def _is_dunder(name): """Returns True if a __dunder__ name, False otherwise.""" return (name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2] != '_' and len(name) > 4) def _is_sunder(name): """Returns True if a _sunder_ name, False otherwise.""" return (name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_' and len(name) > 2) def _make_class_unpicklable(cls): """Make the given class un-picklable.""" def _break_on_call_reduce(self, proto): raise TypeError('%r cannot be pickled' % self) cls.__reduce_ex__ = _break_on_call_reduce cls.__module__ = '<unknown>' _auto_null = object() class auto: """ Instances are replaced with an appropriate value in Enum class suites. """ value = _auto_null class _EnumDict(dict): """Track enum member order and ensure member names are not reused. EnumMeta will use the names found in self._member_names as the enumeration member names. """ def __init__(self): super().__init__() self._member_names = [] self._last_values = [] def __setitem__(self, key, value): """Changes anything not dundered or not a descriptor. If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single underscore (sunder) names are reserved. """ if _is_sunder(key): if key not in ( '_order_', '_create_pseudo_member_', '_generate_next_value_', '_missing_', ): raise ValueError('_names_ are reserved for future Enum use') if key == '_generate_next_value_': setattr(self, '_generate_next_value', value) elif _is_dunder(key): if key == '__order__': key = '_order_' elif key in self._member_names: # descriptor overwriting an enum? raise TypeError('Attempted to reuse key: %r' % key) elif not _is_descriptor(value): if key in self: # enum overwriting a descriptor? raise TypeError('%r already defined as: %r' % (key, self[key])) if isinstance(value, auto): if value.value == _auto_null: value.value = self._generate_next_value(key, 1, len(self._member_names), self._last_values[:]) value = value.value self._member_names.append(key) self._last_values.append(value) super().__setitem__(key, value) # Dummy value for Enum as EnumMeta explicitly checks for it, but of course # until EnumMeta finishes running the first time the Enum class doesn't exist. # This is also why there are checks in EnumMeta like `if Enum is not None` Enum = None class EnumMeta(type): """Metaclass for Enum""" @classmethod def __prepare__(metacls, cls, bases): # create the namespace dict enum_dict = _EnumDict() # inherit previous flags and _generate_next_value_ function member_type, first_enum = metacls._get_mixins_(bases) if first_enum is not None: enum_dict['_generate_next_value_'] = getattr(first_enum, '_generate_next_value_', None) return enum_dict def __new__(metacls, cls, bases, classdict): # an Enum class is final once enumeration items have been defined; it # cannot be mixed with other types (int, float, etc.) if it has an # inherited __new__ unless a new __new__ is defined (or the resulting # class will fail). member_type, first_enum = metacls._get_mixins_(bases) __new__, save_new, use_args = metacls._find_new_(classdict, member_type, first_enum) # save enum items into separate mapping so they don't get baked into # the new class enum_members = {k: classdict[k] for k in classdict._member_names} for name in classdict._member_names: del classdict[name] # adjust the sunders _order_ = classdict.pop('_order_', None) # check for illegal enum names (any others?) invalid_names = set(enum_members) & {'mro', } if invalid_names: raise ValueError('Invalid enum member name: {0}'.format( ','.join(invalid_names))) # create a default docstring if one has not been provided if '__doc__' not in classdict: classdict['__doc__'] = 'An enumeration.' # create our new Enum type enum_class = super().__new__(metacls, cls, bases, classdict) enum_class._member_names_ = [] # names in definition order enum_class._member_map_ = OrderedDict() # name->value map enum_class._member_type_ = member_type # save DynamicClassAttribute attributes from super classes so we know # if we can take the shortcut of storing members in the class dict dynamic_attributes = {k for c in enum_class.mro() for k, v in c.__dict__.items() if isinstance(v, DynamicClassAttribute)} # Reverse value->name map for hashable values. enum_class._value2member_map_ = {} # If a custom type is mixed into the Enum, and it does not know how # to pickle itself, pickle.dumps will succeed but pickle.loads will # fail. Rather than have the error show up later and possibly far # from the source, sabotage the pickle protocol for this class so # that pickle.dumps also fails. # # However, if the new class implements its own __reduce_ex__, do not # sabotage -- it's on them to make sure it works correctly. We use # __reduce_ex__ instead of any of the others as it is preferred by # pickle over __reduce__, and it handles all pickle protocols. if '__reduce_ex__' not in classdict: if member_type is not object: methods = ('__getnewargs_ex__', '__getnewargs__', '__reduce_ex__', '__reduce__') if not any(m in member_type.__dict__ for m in methods): _make_class_unpicklable(enum_class) # instantiate them, checking for duplicates as we go # we instantiate first instead of checking for duplicates first in case # a custom __new__ is doing something funky with the values -- such as # auto-numbering ;) for member_name in classdict._member_names: value = enum_members[member_name] if not isinstance(value, tuple): args = (value, ) else: args = value if member_type is tuple: # special case for tuple enums args = (args, ) # wrap it one more time if not use_args: enum_member = __new__(enum_class) if not hasattr(enum_member, '_value_'): enum_member._value_ = value else: enum_member = __new__(enum_class, *args) if not hasattr(enum_member, '_value_'): if member_type is object: enum_member._value_ = value else: enum_member._value_ = member_type(*args) value = enum_member._value_ enum_member._name_ = member_name enum_member.__objclass__ = enum_class enum_member.__init__(*args) # If another member with the same value was already defined, the # new member becomes an alias to the existing one. for name, canonical_member in enum_class._member_map_.items(): if canonical_member._value_ == enum_member._value_: enum_member = canonical_member break else: # Aliases don't appear in member names (only in __members__). enum_class._member_names_.append(member_name) # performance boost for any member that would not shadow # a DynamicClassAttribute if member_name not in dynamic_attributes: setattr(enum_class, member_name, enum_member) # now add to _member_map_ enum_class._member_map_[member_name] = enum_member try: # This may fail if value is not hashable. We can't add the value # to the map, and by-value lookups for this value will be # linear. enum_class._value2member_map_[value] = enum_member except TypeError: pass # double check that repr and friends are not the mixin's or various # things break (such as pickle) for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): class_method = getattr(enum_class, name) obj_method = getattr(member_type, name, None) enum_method = getattr(first_enum, name, None) if obj_method is not None and obj_method is class_method: setattr(enum_class, name, enum_method) # replace any other __new__ with our own (as long as Enum is not None, # anyway) -- again, this is to support pickle if Enum is not None: # if the user defined their own __new__, save it before it gets # clobbered in case they subclass later if save_new: enum_class.__new_member__ = __new__ enum_class.__new__ = Enum.__new__ # py3 support for definition order (helps keep py2/py3 code in sync) if _order_ is not None: if isinstance(_order_, str): _order_ = _order_.replace(',', ' ').split() if _order_ != enum_class._member_names_: raise TypeError('member order does not match _order_') return enum_class def __bool__(self): """ classes/types should always be True. """ return True def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1): """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='RED GREEN BLUE')). When used for the functional API: `value` will be the name of the new class. `names` should be either a string of white-space/comma delimited names (values will start at `start`), or an iterator/mapping of name, value pairs. `module` should be set to the module this class is being created in; if it is not set, an attempt to find that module will be made, but if it fails the class will not be picklable. `qualname` should be set to the actual location this class can be found at in its module; by default it is set to the global scope. If this is not correct, unpickling will fail in some circumstances. `type`, if set, will be mixed in as the first base class. """ if names is None: # simple value lookup return cls.__new__(cls, value) # otherwise, functional API: we're creating a new Enum type return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start) def __contains__(cls, member): return isinstance(member, cls) and member._name_ in cls._member_map_ def __delattr__(cls, attr): # nicer error message when someone tries to delete an attribute # (see issue19025). if attr in cls._member_map_: raise AttributeError( "%s: cannot delete Enum member." % cls.__name__) super().__delattr__(attr) def __dir__(self): return (['__class__', '__doc__', '__members__', '__module__'] + self._member_names_) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """ if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name) from None def __getitem__(cls, name): return cls._member_map_[name] def __iter__(cls): return (cls._member_map_[name] for name in cls._member_names_) def __len__(cls): return len(cls._member_names_) @property def __members__(cls): """Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a read-only view of the internal mapping. """ return MappingProxyType(cls._member_map_) def __repr__(cls): return "<enum %r>" % cls.__name__ def __reversed__(cls): return (cls._member_map_[name] for name in reversed(cls._member_names_)) def __setattr__(cls, name, value): """Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration. """ member_map = cls.__dict__.get('_member_map_', {}) if name in member_map: raise AttributeError('Cannot reassign members.') super().__setattr__(name, value) def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1): """Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are incremented by 1 from `start`. * An iterable of member names. Values are incremented by 1 from `start`. * An iterable of (member name, value) pairs. * A mapping of member name -> value pairs. """ metacls = cls.__class__ bases = (cls, ) if type is None else (type, cls) _, first_enum = cls._get_mixins_(bases) classdict = metacls.__prepare__(class_name, bases) # special processing needed for names? if isinstance(names, str): names = names.replace(',', ' ').split() if isinstance(names, (tuple, list)) and names and isinstance(names[0], str): original_names, names = names, [] last_values = [] for count, name in enumerate(original_names): value = first_enum._generate_next_value_(name, start, count, last_values[:]) last_values.append(value) names.append((name, value)) # Here, names is either an iterable of (name, value) or a mapping. for item in names: if isinstance(item, str): member_name, member_value = item, names[item] else: member_name, member_value = item classdict[member_name] = member_value enum_class = metacls.__new__(metacls, class_name, bases, classdict) # TODO: replace the frame hack if a blessed way to know the calling # module is ever developed if module is None: try: module = sys._getframe(2).f_globals['__name__'] except (AttributeError, ValueError) as exc: pass if module is None: _make_class_unpicklable(enum_class) else: enum_class.__module__ = module if qualname is not None: enum_class.__qualname__ = qualname return enum_class @staticmethod def _get_mixins_(bases): """Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__ """ if not bases: return object, Enum # double check that we are not subclassing a class with existing # enumeration members; while we're at it, see if any other data # type has been mixed in so we can use the correct __new__ member_type = first_enum = None for base in bases: if (base is not Enum and issubclass(base, Enum) and base._member_names_): raise TypeError("Cannot extend enumerations") # base is now the last base in bases if not issubclass(base, Enum): raise TypeError("new enumerations must be created as " "`ClassName([mixin_type,] enum_type)`") # get correct mix-in type (either mix-in type of Enum subclass, or # first base if last base is Enum) if not issubclass(bases[0], Enum): member_type = bases[0] # first data type first_enum = bases[-1] # enum type else: for base in bases[0].__mro__: # most common: (IntEnum, int, Enum, object) # possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>, # <class 'int'>, <Enum 'Enum'>, # <class 'object'>) if issubclass(base, Enum): if first_enum is None: first_enum = base else: if member_type is None: member_type = base return member_type, first_enum @staticmethod def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members. classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__ """ # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __new_member__ __new__ = classdict.get('__new__', None) # should __new__ be saved as __new_member__ later? save_new = __new__ is not None if __new__ is None: # check all possibles for __new_member__ before falling back to # __new__ for method in ('__new_member__', '__new__'): for possible in (member_type, first_enum): target = getattr(possible, method, None) if target not in { None, None.__new__, object.__new__, Enum.__new__, }: __new__ = target break if __new__ is not None: break else: __new__ = object.__new__ # if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ if __new__ is object.__new__: use_args = False else: use_args = True return __new__, save_new, use_args class Enum(metaclass=EnumMeta): """Generic enumeration. Derive from this class to define new enumerations. """ def __new__(cls, value): # all enum instances are actually created during class construction # without calling this method; this method is called by the metaclass' # __call__ (i.e. Color(3) ), and by pickle if type(value) is cls: # For lookups like Color(Color.RED) return value # by-value search for a matching enum member # see if it's in the reverse mapping (for hashable values) try: if value in cls._value2member_map_: return cls._value2member_map_[value] except TypeError: # not there, now do long search -- O(n) behavior for member in cls._member_map_.values(): if member._value_ == value: return member # still not found -- try _missing_ hook return cls._missing_(value) def _generate_next_value_(name, start, count, last_values): for last_value in reversed(last_values): try: return last_value + 1 except TypeError: pass else: return start @classmethod def _missing_(cls, value): raise ValueError("%r is not a valid %s" % (value, cls.__name__)) def __repr__(self): return "<%s.%s: %r>" % ( self.__class__.__name__, self._name_, self._value_) def __str__(self): return "%s.%s" % (self.__class__.__name__, self._name_) def __dir__(self): added_behavior = [ m for cls in self.__class__.mro() for m in cls.__dict__ if m[0] != '_' and m not in self._member_map_ ] return (['__class__', '__doc__', '__module__'] + added_behavior) def __format__(self, format_spec): # mixed-in Enums should use the mixed-in type's __format__, otherwise # we can get strange results with the Enum name showing up instead of # the value # pure Enum branch if self._member_type_ is object: cls = str val = str(self) # mix-in branch else: cls = self._member_type_ val = self._value_ return cls.__format__(val, format_spec) def __hash__(self): return hash(self._name_) def __reduce_ex__(self, proto): return self.__class__, (self._value_, ) # DynamicClassAttribute is used to provide access to the `name` and # `value` properties of enum members while keeping some measure of # protection from modification, while still allowing for an enumeration # to have members named `name` and `value`. This works because enumeration # members are not set directly on the enum class -- __getattr__ is # used to look them up. @DynamicClassAttribute def name(self): """The name of the Enum member.""" return self._name_ @DynamicClassAttribute def value(self): """The value of the Enum member.""" return self._value_ @classmethod def _convert(cls, name, module, filter, source=None): """ Create a new Enum subclass that replaces a collection of global constants """ # convert all constants from source (or module) that pass filter() to # a new Enum called name, and export the enum and its members back to # module; # also, replace the __reduce_ex__ method so unpickling works in # previous Python versions module_globals = vars(sys.modules[module]) if source: source = vars(source) else: source = module_globals # We use an OrderedDict of sorted source keys so that the # _value2member_map is populated in the same order every time # for a consistent reverse mapping of number to name when there # are multiple names for the same number rather than varying # between runs due to hash randomization of the module dictionary. members = [ (name, source[name]) for name in source.keys() if filter(name)] try: # sort by value members.sort(key=lambda t: (t[1], t[0])) except TypeError: # unless some values aren't comparable, in which case sort by name members.sort(key=lambda t: t[0]) cls = cls(name, members, module=module) cls.__reduce_ex__ = _reduce_ex_by_name module_globals.update(cls.__members__) module_globals[name] = cls return cls class IntEnum(int, Enum): """Enum where members are also (and must be) ints""" def _reduce_ex_by_name(self, proto): return self.name class Flag(Enum): """Support for flags""" def _generate_next_value_(name, start, count, last_values): """ Generate the next value when not given. name: the name of the member start: the initital start value or None count: the number of existing members last_value: the last value assigned or None """ if not count: return start if start is not None else 1 for last_value in reversed(last_values): try: high_bit = _high_bit(last_value) break except Exception: raise TypeError('Invalid Flag value: %r' % last_value) from None return 2 ** (high_bit+1) @classmethod def _missing_(cls, value): original_value = value if value < 0: value = ~value possible_member = cls._create_pseudo_member_(value) if original_value < 0: possible_member = ~possible_member return possible_member @classmethod def _create_pseudo_member_(cls, value): """ Create a composite member iff value contains only members. """ pseudo_member = cls._value2member_map_.get(value, None) if pseudo_member is None: # verify all bits are accounted for _, extra_flags = _decompose(cls, value) if extra_flags: raise ValueError("%r is not a valid %s" % (value, cls.__name__)) # construct a singleton enum pseudo-member pseudo_member = object.__new__(cls) pseudo_member._name_ = None pseudo_member._value_ = value # use setdefault in case another thread already created a composite # with this value pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member) return pseudo_member def __contains__(self, other): if not isinstance(other, self.__class__): return NotImplemented return other._value_ & self._value_ == other._value_ def __repr__(self): cls = self.__class__ if self._name_ is not None: return '<%s.%s: %r>' % (cls.__name__, self._name_, self._value_) members, uncovered = _decompose(cls, self._value_) return '<%s.%s: %r>' % ( cls.__name__, '|'.join([str(m._name_ or m._value_) for m in members]), self._value_, ) def __str__(self): cls = self.__class__ if self._name_ is not None: return '%s.%s' % (cls.__name__, self._name_) members, uncovered = _decompose(cls, self._value_) if len(members) == 1 and members[0]._name_ is None: return '%s.%r' % (cls.__name__, members[0]._value_) else: return '%s.%s' % ( cls.__name__, '|'.join([str(m._name_ or m._value_) for m in members]), ) def __bool__(self): return bool(self._value_) def __or__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.__class__(self._value_ | other._value_) def __and__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.__class__(self._value_ & other._value_) def __xor__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.__class__(self._value_ ^ other._value_) def __invert__(self): members, uncovered = _decompose(self.__class__, self._value_) inverted_members = [ m for m in self.__class__ if m not in members and not m._value_ & self._value_ ] inverted = reduce(_or_, inverted_members, self.__class__(0)) return self.__class__(inverted) class IntFlag(int, Flag): """Support for integer-based Flags""" @classmethod def _missing_(cls, value): if not isinstance(value, int): raise ValueError("%r is not a valid %s" % (value, cls.__name__)) new_member = cls._create_pseudo_member_(value) return new_member @classmethod def _create_pseudo_member_(cls, value): pseudo_member = cls._value2member_map_.get(value, None) if pseudo_member is None: need_to_create = [value] # get unaccounted for bits _, extra_flags = _decompose(cls, value) # timer = 10 while extra_flags: # timer -= 1 bit = _high_bit(extra_flags) flag_value = 2 ** bit if (flag_value not in cls._value2member_map_ and flag_value not in need_to_create ): need_to_create.append(flag_value) if extra_flags == -flag_value: extra_flags = 0 else: extra_flags ^= flag_value for value in reversed(need_to_create): # construct singleton pseudo-members pseudo_member = int.__new__(cls, value) pseudo_member._name_ = None pseudo_member._value_ = value # use setdefault in case another thread already created a composite # with this value pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member) return pseudo_member def __or__(self, other): if not isinstance(other, (self.__class__, int)): return NotImplemented result = self.__class__(self._value_ | self.__class__(other)._value_) return result def __and__(self, other): if not isinstance(other, (self.__class__, int)): return NotImplemented return self.__class__(self._value_ & self.__class__(other)._value_) def __xor__(self, other): if not isinstance(other, (self.__class__, int)): return NotImplemented return self.__class__(self._value_ ^ self.__class__(other)._value_) __ror__ = __or__ __rand__ = __and__ __rxor__ = __xor__ def __invert__(self): result = self.__class__(~self._value_) return result def _high_bit(value): """returns index of highest bit, or -1 if value is zero or negative""" return value.bit_length() - 1 def unique(enumeration): """Class decorator for enumerations ensuring unique member values.""" duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: alias_details = ', '.join( ["%s -> %s" % (alias, name) for (alias, name) in duplicates]) raise ValueError('duplicate values found in %r: %s' % (enumeration, alias_details)) return enumeration def _decompose(flag, value): """Extract all members from the value.""" # _decompose is only called if the value is not named not_covered = value negative = value < 0 # issue29167: wrap accesses to _value2member_map_ in a list to avoid race # conditions between iterating over it and having more psuedo- # members added to it if negative: # only check for named flags flags_to_check = [ (m, v) for v, m in list(flag._value2member_map_.items()) if m.name is not None ] else: # check for named flags and powers-of-two flags flags_to_check = [ (m, v) for v, m in list(flag._value2member_map_.items()) if m.name is not None or _power_of_two(v) ] members = [] for member, member_value in flags_to_check: if member_value and member_value & value == member_value: members.append(member) not_covered &= ~member_value if not members and value in flag._value2member_map_: members.append(flag._value2member_map_[value]) members.sort(key=lambda m: m._value_, reverse=True) if len(members) > 1 and members[0].value == value: # we have the breakdown, don't need the value member itself members.pop(0) return members, not_covered def _power_of_two(value): if value < 1: return False return value == 2 ** _high_bit(value)
33,606
878
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/ntpath.py
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames """Common pathname manipulations, WindowsNT/95 version. Instead of importing this module directly, import os and refer to this module as os.path. """ # strings representing various path-related bits and pieces # These are primarily for export; internally, they are hardcoded. # Should be set before imports for resolving cyclic dependency. curdir = '.' pardir = '..' extsep = '.' sep = '\\' pathsep = ';' altsep = '/' defpath = '.;C:\\bin' devnull = 'nul' import os import sys import stat import posix import genericpath from genericpath import * __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", "getatime","getctime", "islink","exists","lexists","isdir","isfile", "ismount", "expanduser","expandvars","normpath","abspath", "splitunc","curdir","pardir","sep","pathsep","defpath","altsep", "extsep","devnull","realpath","supports_unicode_filenames","relpath", "samefile", "sameopenfile", "samestat", "commonpath"] def _get_bothseps(path): if isinstance(path, bytes): return b'\\/' else: return '\\/' # Normalize the case of a pathname and map slashes to backslashes. # Other normalizations (such as optimizing '../' away) are not done # (this is done by normpath). def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.""" s = os.fspath(s) try: if isinstance(s, bytes): return s.replace(b'/', b'\\').lower() else: return s.replace('/', '\\').lower() except (TypeError, AttributeError): if not isinstance(s, (bytes, str)): raise TypeError("normcase() argument must be str or bytes, " "not %r" % s.__class__.__name__) from None raise # Return whether a path is absolute. # Trivial in Posix, harder on Windows. # For Windows it is absolute if it starts with a slash or backslash (current # volume), or if a pathname after the volume-letter-and-colon or UNC-resource # starts with a slash or backslash. def isabs(s): """Test whether a path is absolute""" s = os.fspath(s) s = splitdrive(s)[1] return len(s) > 0 and s[0] in _get_bothseps(s) # Join two (or more) paths. def join(path, *paths): path = os.fspath(path) if isinstance(path, bytes): sep = b'\\' seps = b'\\/' colon = b':' else: sep = '\\' seps = '\\/' colon = ':' try: if not paths: path[:0] + sep #23780: Ensure compatible data type even if p is null. result_drive, result_path = splitdrive(path) for p in map(os.fspath, paths): p_drive, p_path = splitdrive(p) if p_path and p_path[0] in seps: # Second path is absolute if p_drive or not result_drive: result_drive = p_drive result_path = p_path continue elif p_drive and p_drive != result_drive: if p_drive.lower() != result_drive.lower(): # Different drives => ignore the first path entirely result_drive = p_drive result_path = p_path continue # Same drive in different case result_drive = p_drive # Second path is relative to the first if result_path and result_path[-1] not in seps: result_path = result_path + sep result_path = result_path + p_path ## add separator between UNC and non-absolute path if (result_path and result_path[0] not in seps and result_drive and result_drive[-1:] != colon): return result_drive + sep + result_path return result_drive + result_path except (TypeError, AttributeError, BytesWarning): genericpath._check_arg_types('join', path, *paths) raise # Split a path in a drive specification (a drive letter followed by a # colon) and the path specification. # It is always true that drivespec + pathspec == p def splitdrive(p): """Split a pathname into drive/UNC sharepoint and relative path specifiers. Returns a 2-tuple (drive_or_unc, path); either part may be empty. If you assign result = splitdrive(p) It is always true that: result[0] + result[1] == p If the path contained a drive letter, drive_or_unc will contain everything up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") If the path contained a UNC path, the drive_or_unc will contain the host name and share up to but not including the fourth directory separator character. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") Paths cannot contain both a drive letter and a UNC path. """ p = os.fspath(p) if len(p) >= 2: if isinstance(p, bytes): sep = b'\\' altsep = b'/' colon = b':' else: sep = '\\' altsep = '/' colon = ':' normp = p.replace(altsep, sep) if (normp[0:2] == sep*2) and (normp[2:3] != sep): # is a UNC path: # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path # \\machine\mountpoint\directory\etc\... # directory ^^^^^^^^^^^^^^^ index = normp.find(sep, 2) if index == -1: return p[:0], p index2 = normp.find(sep, index + 1) # a UNC path can't have two slashes in a row # (after the initial two) if index2 == index + 1: return p[:0], p if index2 == -1: index2 = len(p) return p[:index2], p[index2:] if normp[1:2] == colon: return p[:2], p[2:] return p[:0], p # Parse UNC paths def splitunc(p): """Deprecated since Python 3.1. Please use splitdrive() instead; it now handles UNC paths. Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have a UNC part. """ import warnings warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead", DeprecationWarning, 2) drive, path = splitdrive(p) if len(drive) == 2: # Drive letter present return p[:0], p return drive, path # Split a path in head (everything up to the last '/') and tail (the # rest). After the trailing '/' is stripped, the invariant # join(head, tail) == p holds. # The resulting head won't end in '/' unless it is the root. def split(p): """Split a pathname. Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty.""" p = os.fspath(p) seps = _get_bothseps(p) d, p = splitdrive(p) # set i to index beyond p's last slash i = len(p) while i and p[i-1] not in seps: i -= 1 head, tail = p[:i], p[i:] # now tail has no slashes # remove trailing slashes from head, unless it's all slashes head = head.rstrip(seps) or head return d + head, tail # Split a path in root and extension. # The extension is everything starting at the last dot in the last # pathname component; the root is everything before that. # It is always true that root + ext == p. def splitext(p): p = os.fspath(p) if isinstance(p, bytes): return genericpath._splitext(p, b'\\', b'/', b'.') else: return genericpath._splitext(p, '\\', '/', '.') splitext.__doc__ = genericpath._splitext.__doc__ # Return the tail (basename) part of a path. def basename(p): """Returns the final component of a pathname""" return split(p)[1] # Return the head (dirname) part of a path. def dirname(p): """Returns the directory component of a pathname""" return split(p)[0] # Is a path a symbolic link? # This will always return false on systems where os.lstat doesn't exist. def islink(path): """Test whether a path is a symbolic link. This will always return false for Windows prior to 6.0. """ try: st = os.lstat(path) except (OSError, AttributeError): return False return stat.S_ISLNK(st.st_mode) # Being true for dangling symbolic links is also useful. def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: st = os.lstat(path) except OSError: return False return True # Is a path a mount point? # Any drive letter root (eg c:\) # Any share UNC (eg \\server\share) # Any volume mounted on a filesystem folder # # No one method detects all three situations. Historically we've lexically # detected drive letter roots and share UNCs. The canonical approach to # detecting mounted volumes (querying the reparse tag) fails for the most # common case: drive letter roots. The alternative which uses GetVolumePathName # fails if the drive letter is the result of a SUBST. try: _getvolumepathname = posix._getvolumepathname except AttributeError: _getvolumepathname = None def ismount(path): """Test whether a path is a mount point (a drive root, the root of a share, or a mounted volume)""" path = os.fspath(path) seps = _get_bothseps(path) path = abspath(path) root, rest = splitdrive(path) if root and root[0] in seps: return (not rest) or (rest in seps) if rest in seps: return True if _getvolumepathname: return path.rstrip(seps) == _getvolumepathname(path).rstrip(seps) else: return False # Expand paths beginning with '~' or '~user'. # '~' means $HOME; '~user' means that user's home directory. # If the path doesn't begin with '~', or if the user or $HOME is unknown, # the path is returned unchanged (leaving error reporting to whatever # function is called with the expanded path as argument). # See also module 'glob' for expansion of *, ? and [...] in pathnames. # (A function should also be defined to do full *sh-style environment # variable expansion.) def expanduser(path): """Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.""" path = os.fspath(path) if isinstance(path, bytes): tilde = b'~' else: tilde = '~' if not path.startswith(tilde): return path i, n = 1, len(path) while i < n and path[i] not in _get_bothseps(path): i += 1 if 'HOME' in os.environ: userhome = os.environ['HOME'] elif 'USERPROFILE' in os.environ: userhome = os.environ['USERPROFILE'] elif not 'HOMEPATH' in os.environ: return path else: try: drive = os.environ['HOMEDRIVE'] except KeyError: drive = '' userhome = join(drive, os.environ['HOMEPATH']) if isinstance(path, bytes): userhome = os.fsencode(userhome) if i != 1: #~user userhome = join(dirname(userhome), path[1:i]) return userhome + path[i:] # Expand paths containing shell variable substitutions. # The following rules apply: # - no expansion within single quotes # - '$$' is translated into '$' # - '%%' is translated into '%' if '%%' are not seen in %var1%%var2% # - ${varname} is accepted. # - $varname is accepted. # - %varname% is accepted. # - varnames can be made out of letters, digits and the characters '_-' # (though is not verified in the ${varname} and %varname% cases) # XXX With COMMAND.COM you can use any characters in a variable name, # XXX except '^|<>='. def expandvars(path): """Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" path = os.fspath(path) if isinstance(path, bytes): if b'$' not in path and b'%' not in path: return path import string varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii') quote = b'\'' percent = b'%' brace = b'{' rbrace = b'}' dollar = b'$' environ = getattr(os, 'environb', None) else: if '$' not in path and '%' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' quote = '\'' percent = '%' brace = '{' rbrace = '}' dollar = '$' environ = os.environ res = path[:0] index = 0 pathlen = len(path) while index < pathlen: c = path[index:index+1] if c == quote: # no expansion within single quotes path = path[index + 1:] pathlen = len(path) try: index = path.index(c) res += c + path[:index + 1] except ValueError: res += c + path index = pathlen - 1 elif c == percent: # variable or '%' if path[index + 1:index + 2] == percent: res += c index += 1 else: path = path[index+1:] pathlen = len(path) try: index = path.index(percent) except ValueError: res += percent + path index = pathlen - 1 else: var = path[:index] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(var)]) else: value = environ[var] except KeyError: value = percent + var + percent res += value elif c == dollar: # variable or '$$' if path[index + 1:index + 2] == dollar: res += c index += 1 elif path[index + 1:index + 2] == brace: path = path[index+2:] pathlen = len(path) try: index = path.index(rbrace) except ValueError: res += dollar + brace + path index = pathlen - 1 else: var = path[:index] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(var)]) else: value = environ[var] except KeyError: value = dollar + brace + var + rbrace res += value else: var = path[:0] index += 1 c = path[index:index + 1] while c and c in varchars: var += c index += 1 c = path[index:index + 1] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(var)]) else: value = environ[var] except KeyError: value = dollar + var res += value if c: index -= 1 else: res += c index += 1 return res # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B. # Previously, this function also truncated pathnames to 8+3 format, # but as this module is called "ntpath", that's obviously wrong! def normpath(path): """Normalize path, eliminating double slashes, etc.""" path = os.fspath(path) if isinstance(path, bytes): sep = b'\\' altsep = b'/' curdir = b'.' pardir = b'..' special_prefixes = (b'\\\\.\\', b'\\\\?\\') else: sep = '\\' altsep = '/' curdir = '.' pardir = '..' special_prefixes = ('\\\\.\\', '\\\\?\\') if path.startswith(special_prefixes): # in the case of paths with these prefixes: # \\.\ -> device names # \\?\ -> literal paths # do not do any normalization, but return the path unchanged return path path = path.replace(altsep, sep) prefix, path = splitdrive(path) # collapse initial backslashes if path.startswith(sep): prefix += sep path = path.lstrip(sep) comps = path.split(sep) i = 0 while i < len(comps): if not comps[i] or comps[i] == curdir: del comps[i] elif comps[i] == pardir: if i > 0 and comps[i-1] != pardir: del comps[i-1:i+1] i -= 1 elif i == 0 and prefix.endswith(sep): del comps[i] else: i += 1 else: i += 1 # If the path is now empty, substitute '.' if not prefix and not comps: comps.append(curdir) return prefix + sep.join(comps) def _abspath_fallback(path): """Return the absolute version of a path as a fallback function in case `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for more. """ path = os.fspath(path) if not isabs(path): if isinstance(path, bytes): cwd = os.getcwdb() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path) # Return an absolute path. try: _getfullpathname = posix._getfullpathname except AttributeError: # not running on Windows - mock up something sensible abspath = _abspath_fallback else: # use native Windows method on Windows def abspath(path): """Return the absolute version of a path.""" try: return normpath(_getfullpathname(path)) except (OSError, ValueError): return _abspath_fallback(path) # realpath is a no-op on systems without islink support realpath = abspath supports_unicode_filenames = True def relpath(path, start=None): """Return a relative version of a path""" path = os.fspath(path) if isinstance(path, bytes): sep = b'\\' curdir = b'.' pardir = b'..' else: sep = '\\' curdir = '.' pardir = '..' if start is None: start = curdir if not path: raise ValueError("no path specified") start = os.fspath(start) try: start_abs = abspath(normpath(start)) path_abs = abspath(normpath(path)) start_drive, start_rest = splitdrive(start_abs) path_drive, path_rest = splitdrive(path_abs) if normcase(start_drive) != normcase(path_drive): raise ValueError("path is on mount %r, start on mount %r" % ( path_drive, start_drive)) start_list = [x for x in start_rest.split(sep) if x] path_list = [x for x in path_rest.split(sep) if x] # Work out how much of the filepath is shared by start and path. i = 0 for e1, e2 in zip(start_list, path_list): if normcase(e1) != normcase(e2): break i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) except (TypeError, ValueError, AttributeError, BytesWarning, DeprecationWarning): genericpath._check_arg_types('relpath', path, start) raise # Return the longest common sub-path of the sequence of paths given as input. # The function is case-insensitive and 'separator-insensitive', i.e. if the # only difference between two paths is the use of '\' versus '/' as separator, # they are deemed to be equal. # # However, the returned path will have the standard '\' separator (even if the # given paths had the alternative '/' separator) and will have the case of the # first path given in the sequence. Additionally, any trailing separator is # stripped from the returned path. def commonpath(paths): """Given a sequence of path names, returns the longest common sub-path.""" if not paths: raise ValueError('commonpath() arg is an empty sequence') paths = tuple(map(os.fspath, paths)) if isinstance(paths[0], bytes): sep = b'\\' altsep = b'/' curdir = b'.' else: sep = '\\' altsep = '/' curdir = '.' try: drivesplits = [splitdrive(p.replace(altsep, sep).lower()) for p in paths] split_paths = [p.split(sep) for d, p in drivesplits] try: isabs, = set(p[:1] == sep for d, p in drivesplits) except ValueError: raise ValueError("Can't mix absolute and relative paths") from None # Check that all drive letters or UNC paths match. The check is made only # now otherwise type errors for mixing strings and bytes would not be # caught. if len(set(d for d, p in drivesplits)) != 1: raise ValueError("Paths don't have the same drive") drive, path = splitdrive(paths[0].replace(altsep, sep)) common = path.split(sep) common = [c for c in common if c and c != curdir] split_paths = [[c for c in s if c and c != curdir] for s in split_paths] s1 = min(split_paths) s2 = max(split_paths) for i, c in enumerate(s1): if c != s2[i]: common = common[:i] break else: common = common[:len(s1)] prefix = drive + sep if isabs else drive return prefix + sep.join(common) except (TypeError, AttributeError): genericpath._check_arg_types('commonpath', *paths) raise # determine if two files are in fact the same file try: # GetFinalPathNameByHandle is available starting with Windows 6.0. # Windows XP and non-Windows OS'es will mock _getfinalpathname. if sys.getwindowsversion()[:2] >= (6, 0): _getfinalpathname = posix._getfinalpathname else: raise ImportError except (AttributeError, ImportError, OSError): # On Windows XP and earlier, two files are the same if their absolute # pathnames are the same. # Non-Windows operating systems fake this method with an XP # approximation. def _getfinalpathname(f): return normcase(abspath(f)) try: # The genericpath.isdir implementation uses os.stat and checks the mode # attribute to tell whether or not the path is a directory. # This is overkill on Windows - just pass the path to GetFileAttributes # and check the attribute from there. isdir = posix._isdir except AttributeError: # Use genericpath.isdir as imported above. pass
22,988
689
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/io.py
"""The io module provides the Python interfaces to stream handling. The builtin open function is defined in this module. At the top of the I/O hierarchy is the abstract base class IOBase. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise an OSError if they do not support a given operation. Extending IOBase is RawIOBase which deals simply with the reading and writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide an interface to OS files. BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer streams that are readable, writable, and both respectively. BufferedRandom provides a buffered interface to random access streams. BytesIO is a simple stream of in-memory bytes. Another IOBase subclass, TextIOBase, deals with the encoding and decoding of streams into text. TextIOWrapper, which extends it, is a buffered text interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO is an in-memory stream for text. Argument names are not part of the specification, and only the arguments of open() are intended to be used as keyword arguments. data: DEFAULT_BUFFER_SIZE An int containing the default buffer size used by the module's buffered I/O classes. open() uses the file's blksize (as obtained by os.stat) if possible. """ # New I/O library conforming to PEP 3116. __author__ = ("Guido van Rossum <[email protected]>, " "Mike Verdone <[email protected]>, " "Mark Russell <[email protected]>, " "Antoine Pitrou <[email protected]>, " "Amaury Forgeot d'Arc <[email protected]>, " "Benjamin Peterson <[email protected]>") __all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO", "BytesIO", "StringIO", "BufferedIOBase", "BufferedReader", "BufferedWriter", "BufferedRWPair", "BufferedRandom", "TextIOBase", "TextIOWrapper", "UnsupportedOperation", "SEEK_SET", "SEEK_CUR", "SEEK_END"] import _io import abc from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError, UnsupportedOperation, open, FileIO, BytesIO, StringIO, BufferedReader, BufferedWriter, BufferedRWPair, BufferedRandom, IncrementalNewlineDecoder, TextIOWrapper) OpenWrapper = _io.open # for compatibility with _pyio # Pretend this exception was created here. UnsupportedOperation.__module__ = "io" # for seek() SEEK_SET = 0 SEEK_CUR = 1 SEEK_END = 2 # Declaring ABCs in C is tricky so we do it here. # Method descriptions and default implementations are inherited from the C # version however. class IOBase(_io._IOBase, metaclass=abc.ABCMeta): __doc__ = _io._IOBase.__doc__ class RawIOBase(_io._RawIOBase, IOBase): __doc__ = _io._RawIOBase.__doc__ class BufferedIOBase(_io._BufferedIOBase, IOBase): __doc__ = _io._BufferedIOBase.__doc__ class TextIOBase(_io._TextIOBase, IOBase): __doc__ = _io._TextIOBase.__doc__ RawIOBase.register(FileIO) for klass in (BytesIO, BufferedReader, BufferedWriter, BufferedRandom, BufferedRWPair): BufferedIOBase.register(klass) for klass in (StringIO, TextIOWrapper): TextIOBase.register(klass) del klass try: RawIOBase.register(_io._WindowsConsoleIO) except AttributeError: pass
3,480
98
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/smtpd.py
#! /usr/bin/env python3 """An RFC 5321 smtp proxy with optional RFC 1870 and RFC 6531 extensions. Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]] Options: --nosetuid -n This program generally tries to setuid `nobody', unless this flag is set. The setuid call will fail if this program is not run as root (in which case, use this flag). --version -V Print the version number and exit. --class classname -c classname Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by default. --size limit -s limit Restrict the total size of the incoming message to "limit" number of bytes via the RFC 1870 SIZE extension. Defaults to 33554432 bytes. --smtputf8 -u Enable the SMTPUTF8 extension and behave as an RFC 6531 smtp proxy. --debug -d Turn on debugging prints. --help -h Print this message and exit. Version: %(__version__)s If localhost is not given then `localhost' is used, and if localport is not given then 8025 is used. If remotehost is not given then `localhost' is used, and if remoteport is not given, then 25 is used. """ # Overview: # # This file implements the minimal SMTP protocol as defined in RFC 5321. It # has a hierarchy of classes which implement the backend functionality for the # smtpd. A number of classes are provided: # # SMTPServer - the base class for the backend. Raises NotImplementedError # if you try to use it. # # DebuggingServer - simply prints each message it receives on stdout. # # PureProxy - Proxies all messages to a real smtpd which does final # delivery. One known problem with this class is that it doesn't handle # SMTP errors from the backend server at all. This should be fixed # (contributions are welcome!). # # MailmanProxy - An experimental hack to work with GNU Mailman # <www.list.org>. Using this server as your real incoming smtpd, your # mailhost will automatically recognize and accept mail destined to Mailman # lists when those lists are created. Every message not destined for a list # gets forwarded to a real backend smtpd, as with PureProxy. Again, errors # are not handled correctly yet. # # # Author: Barry Warsaw <[email protected]> # # TODO: # # - support mailbox delivery # - alias files # - Handle more ESMTP extensions # - handle error codes from the backend smtpd import sys import os import errno import getopt import time import socket import asyncore import asynchat import collections from warnings import warn from email._header_value_parser import get_addr_spec, get_angle_addr __all__ = [ "SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy", "MailmanProxy", ] program = sys.argv[0] __version__ = 'Python SMTP proxy version 0.3' class Devnull: def write(self, msg): pass def flush(self): pass DEBUGSTREAM = Devnull() NEWLINE = '\n' COMMASPACE = ', ' DATA_SIZE_DEFAULT = 33554432 def usage(code, msg=''): print(__doc__ % globals(), file=sys.stderr) if msg: print(msg, file=sys.stderr) sys.exit(code) class SMTPChannel(asynchat.async_chat): COMMAND = 0 DATA = 1 command_size_limit = 512 command_size_limits = collections.defaultdict(lambda x=command_size_limit: x) @property def max_command_size_limit(self): try: return max(self.command_size_limits.values()) except ValueError: return self.command_size_limit def __init__(self, server, conn, addr, data_size_limit=DATA_SIZE_DEFAULT, map=None, enable_SMTPUTF8=False, decode_data=False): asynchat.async_chat.__init__(self, conn, map=map) self.smtp_server = server self.conn = conn self.addr = addr self.data_size_limit = data_size_limit self.enable_SMTPUTF8 = enable_SMTPUTF8 self._decode_data = decode_data if enable_SMTPUTF8 and decode_data: raise ValueError("decode_data and enable_SMTPUTF8 cannot" " be set to True at the same time") if decode_data: self._emptystring = '' self._linesep = '\r\n' self._dotsep = '.' self._newline = NEWLINE else: self._emptystring = b'' self._linesep = b'\r\n' self._dotsep = ord(b'.') self._newline = b'\n' self._set_rset_state() self.seen_greeting = '' self.extended_smtp = False self.command_size_limits.clear() self.fqdn = socket.getfqdn() try: self.peer = conn.getpeername() except OSError as err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err.args[0] != errno.ENOTCONN: raise return print('Peer:', repr(self.peer), file=DEBUGSTREAM) self.push('220 %s %s' % (self.fqdn, __version__)) def _set_post_data_state(self): """Reset state variables to their post-DATA state.""" self.smtp_state = self.COMMAND self.mailfrom = None self.rcpttos = [] self.require_SMTPUTF8 = False self.num_bytes = 0 self.set_terminator(b'\r\n') def _set_rset_state(self): """Reset all state variables except the greeting.""" self._set_post_data_state() self.received_data = '' self.received_lines = [] # properties for backwards-compatibility @property def __server(self): warn("Access to __server attribute on SMTPChannel is deprecated, " "use 'smtp_server' instead", DeprecationWarning, 2) return self.smtp_server @__server.setter def __server(self, value): warn("Setting __server attribute on SMTPChannel is deprecated, " "set 'smtp_server' instead", DeprecationWarning, 2) self.smtp_server = value @property def __line(self): warn("Access to __line attribute on SMTPChannel is deprecated, " "use 'received_lines' instead", DeprecationWarning, 2) return self.received_lines @__line.setter def __line(self, value): warn("Setting __line attribute on SMTPChannel is deprecated, " "set 'received_lines' instead", DeprecationWarning, 2) self.received_lines = value @property def __state(self): warn("Access to __state attribute on SMTPChannel is deprecated, " "use 'smtp_state' instead", DeprecationWarning, 2) return self.smtp_state @__state.setter def __state(self, value): warn("Setting __state attribute on SMTPChannel is deprecated, " "set 'smtp_state' instead", DeprecationWarning, 2) self.smtp_state = value @property def __greeting(self): warn("Access to __greeting attribute on SMTPChannel is deprecated, " "use 'seen_greeting' instead", DeprecationWarning, 2) return self.seen_greeting @__greeting.setter def __greeting(self, value): warn("Setting __greeting attribute on SMTPChannel is deprecated, " "set 'seen_greeting' instead", DeprecationWarning, 2) self.seen_greeting = value @property def __mailfrom(self): warn("Access to __mailfrom attribute on SMTPChannel is deprecated, " "use 'mailfrom' instead", DeprecationWarning, 2) return self.mailfrom @__mailfrom.setter def __mailfrom(self, value): warn("Setting __mailfrom attribute on SMTPChannel is deprecated, " "set 'mailfrom' instead", DeprecationWarning, 2) self.mailfrom = value @property def __rcpttos(self): warn("Access to __rcpttos attribute on SMTPChannel is deprecated, " "use 'rcpttos' instead", DeprecationWarning, 2) return self.rcpttos @__rcpttos.setter def __rcpttos(self, value): warn("Setting __rcpttos attribute on SMTPChannel is deprecated, " "set 'rcpttos' instead", DeprecationWarning, 2) self.rcpttos = value @property def __data(self): warn("Access to __data attribute on SMTPChannel is deprecated, " "use 'received_data' instead", DeprecationWarning, 2) return self.received_data @__data.setter def __data(self, value): warn("Setting __data attribute on SMTPChannel is deprecated, " "set 'received_data' instead", DeprecationWarning, 2) self.received_data = value @property def __fqdn(self): warn("Access to __fqdn attribute on SMTPChannel is deprecated, " "use 'fqdn' instead", DeprecationWarning, 2) return self.fqdn @__fqdn.setter def __fqdn(self, value): warn("Setting __fqdn attribute on SMTPChannel is deprecated, " "set 'fqdn' instead", DeprecationWarning, 2) self.fqdn = value @property def __peer(self): warn("Access to __peer attribute on SMTPChannel is deprecated, " "use 'peer' instead", DeprecationWarning, 2) return self.peer @__peer.setter def __peer(self, value): warn("Setting __peer attribute on SMTPChannel is deprecated, " "set 'peer' instead", DeprecationWarning, 2) self.peer = value @property def __conn(self): warn("Access to __conn attribute on SMTPChannel is deprecated, " "use 'conn' instead", DeprecationWarning, 2) return self.conn @__conn.setter def __conn(self, value): warn("Setting __conn attribute on SMTPChannel is deprecated, " "set 'conn' instead", DeprecationWarning, 2) self.conn = value @property def __addr(self): warn("Access to __addr attribute on SMTPChannel is deprecated, " "use 'addr' instead", DeprecationWarning, 2) return self.addr @__addr.setter def __addr(self, value): warn("Setting __addr attribute on SMTPChannel is deprecated, " "set 'addr' instead", DeprecationWarning, 2) self.addr = value # Overrides base class for convenience. def push(self, msg): asynchat.async_chat.push(self, bytes( msg + '\r\n', 'utf-8' if self.require_SMTPUTF8 else 'ascii')) # Implementation of base class abstract method def collect_incoming_data(self, data): limit = None if self.smtp_state == self.COMMAND: limit = self.max_command_size_limit elif self.smtp_state == self.DATA: limit = self.data_size_limit if limit and self.num_bytes > limit: return elif limit: self.num_bytes += len(data) if self._decode_data: self.received_lines.append(str(data, 'utf-8')) else: self.received_lines.append(data) # Implementation of base class abstract method def found_terminator(self): line = self._emptystring.join(self.received_lines) print('Data:', repr(line), file=DEBUGSTREAM) self.received_lines = [] if self.smtp_state == self.COMMAND: sz, self.num_bytes = self.num_bytes, 0 if not line: self.push('500 Error: bad syntax') return if not self._decode_data: line = str(line, 'utf-8') i = line.find(' ') if i < 0: command = line.upper() arg = None else: command = line[:i].upper() arg = line[i+1:].strip() max_sz = (self.command_size_limits[command] if self.extended_smtp else self.command_size_limit) if sz > max_sz: self.push('500 Error: line too long') return method = getattr(self, 'smtp_' + command, None) if not method: self.push('500 Error: command "%s" not recognized' % command) return method(arg) return else: if self.smtp_state != self.DATA: self.push('451 Internal confusion') self.num_bytes = 0 return if self.data_size_limit and self.num_bytes > self.data_size_limit: self.push('552 Error: Too much mail data') self.num_bytes = 0 return # Remove extraneous carriage returns and de-transparency according # to RFC 5321, Section 4.5.2. data = [] for text in line.split(self._linesep): if text and text[0] == self._dotsep: data.append(text[1:]) else: data.append(text) self.received_data = self._newline.join(data) args = (self.peer, self.mailfrom, self.rcpttos, self.received_data) kwargs = {} if not self._decode_data: kwargs = { 'mail_options': self.mail_options, 'rcpt_options': self.rcpt_options, } status = self.smtp_server.process_message(*args, **kwargs) self._set_post_data_state() if not status: self.push('250 OK') else: self.push(status) # SMTP and ESMTP commands def smtp_HELO(self, arg): if not arg: self.push('501 Syntax: HELO hostname') return # See issue #21783 for a discussion of this behavior. if self.seen_greeting: self.push('503 Duplicate HELO/EHLO') return self._set_rset_state() self.seen_greeting = arg self.push('250 %s' % self.fqdn) def smtp_EHLO(self, arg): if not arg: self.push('501 Syntax: EHLO hostname') return # See issue #21783 for a discussion of this behavior. if self.seen_greeting: self.push('503 Duplicate HELO/EHLO') return self._set_rset_state() self.seen_greeting = arg self.extended_smtp = True self.push('250-%s' % self.fqdn) if self.data_size_limit: self.push('250-SIZE %s' % self.data_size_limit) self.command_size_limits['MAIL'] += 26 if not self._decode_data: self.push('250-8BITMIME') if self.enable_SMTPUTF8: self.push('250-SMTPUTF8') self.command_size_limits['MAIL'] += 10 self.push('250 HELP') def smtp_NOOP(self, arg): if arg: self.push('501 Syntax: NOOP') else: self.push('250 OK') def smtp_QUIT(self, arg): # args is ignored self.push('221 Bye') self.close_when_done() def _strip_command_keyword(self, keyword, arg): keylen = len(keyword) if arg[:keylen].upper() == keyword: return arg[keylen:].strip() return '' def _getaddr(self, arg): if not arg: return '', '' if arg.lstrip().startswith('<'): address, rest = get_angle_addr(arg) else: address, rest = get_addr_spec(arg) if not address: return address, rest return address.addr_spec, rest def _getparams(self, params): # Return params as dictionary. Return None if not all parameters # appear to be syntactically valid according to RFC 1869. result = {} for param in params: param, eq, value = param.partition('=') if not param.isalnum() or eq and not value: return None result[param] = value if eq else True return result def smtp_HELP(self, arg): if arg: extended = ' [SP <mail-parameters>]' lc_arg = arg.upper() if lc_arg == 'EHLO': self.push('250 Syntax: EHLO hostname') elif lc_arg == 'HELO': self.push('250 Syntax: HELO hostname') elif lc_arg == 'MAIL': msg = '250 Syntax: MAIL FROM: <address>' if self.extended_smtp: msg += extended self.push(msg) elif lc_arg == 'RCPT': msg = '250 Syntax: RCPT TO: <address>' if self.extended_smtp: msg += extended self.push(msg) elif lc_arg == 'DATA': self.push('250 Syntax: DATA') elif lc_arg == 'RSET': self.push('250 Syntax: RSET') elif lc_arg == 'NOOP': self.push('250 Syntax: NOOP') elif lc_arg == 'QUIT': self.push('250 Syntax: QUIT') elif lc_arg == 'VRFY': self.push('250 Syntax: VRFY <address>') else: self.push('501 Supported commands: EHLO HELO MAIL RCPT ' 'DATA RSET NOOP QUIT VRFY') else: self.push('250 Supported commands: EHLO HELO MAIL RCPT DATA ' 'RSET NOOP QUIT VRFY') def smtp_VRFY(self, arg): if arg: address, params = self._getaddr(arg) if address: self.push('252 Cannot VRFY user, but will accept message ' 'and attempt delivery') else: self.push('502 Could not VRFY %s' % arg) else: self.push('501 Syntax: VRFY <address>') def smtp_MAIL(self, arg): if not self.seen_greeting: self.push('503 Error: send HELO first') return print('===> MAIL', arg, file=DEBUGSTREAM) syntaxerr = '501 Syntax: MAIL FROM: <address>' if self.extended_smtp: syntaxerr += ' [SP <mail-parameters>]' if arg is None: self.push(syntaxerr) return arg = self._strip_command_keyword('FROM:', arg) address, params = self._getaddr(arg) if not address: self.push(syntaxerr) return if not self.extended_smtp and params: self.push(syntaxerr) return if self.mailfrom: self.push('503 Error: nested MAIL command') return self.mail_options = params.upper().split() params = self._getparams(self.mail_options) if params is None: self.push(syntaxerr) return if not self._decode_data: body = params.pop('BODY', '7BIT') if body not in ['7BIT', '8BITMIME']: self.push('501 Error: BODY can only be one of 7BIT, 8BITMIME') return if self.enable_SMTPUTF8: smtputf8 = params.pop('SMTPUTF8', False) if smtputf8 is True: self.require_SMTPUTF8 = True elif smtputf8 is not False: self.push('501 Error: SMTPUTF8 takes no arguments') return size = params.pop('SIZE', None) if size: if not size.isdigit(): self.push(syntaxerr) return elif self.data_size_limit and int(size) > self.data_size_limit: self.push('552 Error: message size exceeds fixed maximum message size') return if len(params.keys()) > 0: self.push('555 MAIL FROM parameters not recognized or not implemented') return self.mailfrom = address print('sender:', self.mailfrom, file=DEBUGSTREAM) self.push('250 OK') def smtp_RCPT(self, arg): if not self.seen_greeting: self.push('503 Error: send HELO first'); return print('===> RCPT', arg, file=DEBUGSTREAM) if not self.mailfrom: self.push('503 Error: need MAIL command') return syntaxerr = '501 Syntax: RCPT TO: <address>' if self.extended_smtp: syntaxerr += ' [SP <mail-parameters>]' if arg is None: self.push(syntaxerr) return arg = self._strip_command_keyword('TO:', arg) address, params = self._getaddr(arg) if not address: self.push(syntaxerr) return if not self.extended_smtp and params: self.push(syntaxerr) return self.rcpt_options = params.upper().split() params = self._getparams(self.rcpt_options) if params is None: self.push(syntaxerr) return # XXX currently there are no options we recognize. if len(params.keys()) > 0: self.push('555 RCPT TO parameters not recognized or not implemented') return self.rcpttos.append(address) print('recips:', self.rcpttos, file=DEBUGSTREAM) self.push('250 OK') def smtp_RSET(self, arg): if arg: self.push('501 Syntax: RSET') return self._set_rset_state() self.push('250 OK') def smtp_DATA(self, arg): if not self.seen_greeting: self.push('503 Error: send HELO first'); return if not self.rcpttos: self.push('503 Error: need RCPT command') return if arg: self.push('501 Syntax: DATA') return self.smtp_state = self.DATA self.set_terminator(b'\r\n.\r\n') self.push('354 End data with <CR><LF>.<CR><LF>') # Commands that have not been implemented def smtp_EXPN(self, arg): self.push('502 EXPN not implemented') class SMTPServer(asyncore.dispatcher): # SMTPChannel class to use for managing client connections channel_class = SMTPChannel def __init__(self, localaddr, remoteaddr, data_size_limit=DATA_SIZE_DEFAULT, map=None, enable_SMTPUTF8=False, decode_data=False): self._localaddr = localaddr self._remoteaddr = remoteaddr self.data_size_limit = data_size_limit self.enable_SMTPUTF8 = enable_SMTPUTF8 self._decode_data = decode_data if enable_SMTPUTF8 and decode_data: raise ValueError("decode_data and enable_SMTPUTF8 cannot" " be set to True at the same time") asyncore.dispatcher.__init__(self, map=map) try: gai_results = socket.getaddrinfo(*localaddr, type=socket.SOCK_STREAM) self.create_socket(gai_results[0][0], gai_results[0][1]) # try to re-use a server port if possible self.set_reuse_addr() self.bind(localaddr) self.listen(5) except: self.close() raise else: print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), localaddr, remoteaddr), file=DEBUGSTREAM) def handle_accepted(self, conn, addr): print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM) channel = self.channel_class(self, conn, addr, self.data_size_limit, self._map, self.enable_SMTPUTF8, self._decode_data) # API for "doing something useful with the message" def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): """Override this abstract method to handle messages from the client. peer is a tuple containing (ipaddr, port) of the client that made the socket connection to our smtp port. mailfrom is the raw address the client claims the message is coming from. rcpttos is a list of raw addresses the client wishes to deliver the message to. data is a string containing the entire full text of the message, headers (if supplied) and all. It has been `de-transparencied' according to RFC 821, Section 4.5.2. In other words, a line containing a `.' followed by other text has had the leading dot removed. kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as init parameter, otherwise it will contain the following keys: 'mail_options': list of parameters to the mail command. All elements are uppercase strings. Example: ['BODY=8BITMIME', 'SMTPUTF8']. 'rcpt_options': same, for the rcpt command. This function should return None for a normal `250 Ok' response; otherwise, it should return the desired response string in RFC 821 format. """ raise NotImplementedError class DebuggingServer(SMTPServer): def _print_message_content(self, peer, data): inheaders = 1 lines = data.splitlines() for line in lines: # headers first if inheaders and not line: peerheader = 'X-Peer: ' + peer[0] if not isinstance(data, str): # decoded_data=false; make header match other binary output peerheader = repr(peerheader.encode('utf-8')) print(peerheader) inheaders = 0 if not isinstance(data, str): # Avoid spurious 'str on bytes instance' warning. line = repr(line) print(line) def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): print('---------- MESSAGE FOLLOWS ----------') if kwargs: if kwargs.get('mail_options'): print('mail options: %s' % kwargs['mail_options']) if kwargs.get('rcpt_options'): print('rcpt options: %s\n' % kwargs['rcpt_options']) self._print_message_content(peer, data) print('------------ END MESSAGE ------------') class PureProxy(SMTPServer): def __init__(self, *args, **kwargs): if 'enable_SMTPUTF8' in kwargs and kwargs['enable_SMTPUTF8']: raise ValueError("PureProxy does not support SMTPUTF8.") super(PureProxy, self).__init__(*args, **kwargs) def process_message(self, peer, mailfrom, rcpttos, data): lines = data.split('\n') # Look for the last header i = 0 for line in lines: if not line: break i += 1 lines.insert(i, 'X-Peer: %s' % peer[0]) data = NEWLINE.join(lines) refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? print('we got some refusals:', refused, file=DEBUGSTREAM) def _deliver(self, mailfrom, rcpttos, data): import smtplib refused = {} try: s = smtplib.SMTP() s.connect(self._remoteaddr[0], self._remoteaddr[1]) try: refused = s.sendmail(mailfrom, rcpttos, data) finally: s.quit() except smtplib.SMTPRecipientsRefused as e: print('got SMTPRecipientsRefused', file=DEBUGSTREAM) refused = e.recipients except (OSError, smtplib.SMTPException) as e: print('got', e.__class__, file=DEBUGSTREAM) # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering # exception code. errcode = getattr(e, 'smtp_code', -1) errmsg = getattr(e, 'smtp_error', 'ignore') for r in rcpttos: refused[r] = (errcode, errmsg) return refused class MailmanProxy(PureProxy): def __init__(self, *args, **kwargs): if 'enable_SMTPUTF8' in kwargs and kwargs['enable_SMTPUTF8']: raise ValueError("MailmanProxy does not support SMTPUTF8.") super(PureProxy, self).__init__(*args, **kwargs) def process_message(self, peer, mailfrom, rcpttos, data): from io import StringIO # from Mailman import Utils # from Mailman import Message # from Mailman import MailList # If the message is to a Mailman mailing list, then we'll invoke the # Mailman script directly, without going through the real smtpd. # Otherwise we'll forward it to the local proxy for disposition. listnames = [] for rcpt in rcpttos: local = rcpt.lower().split('@')[0] # We allow the following variations on the theme # listname # listname-admin # listname-owner # listname-request # listname-join # listname-leave parts = local.split('-') if len(parts) > 2: continue listname = parts[0] if len(parts) == 2: command = parts[1] else: command = '' if not Utils.list_exists(listname) or command not in ( '', 'admin', 'owner', 'request', 'join', 'leave'): continue listnames.append((rcpt, listname, command)) # Remove all list recipients from rcpttos and forward what we're not # going to take care of ourselves. Linear removal should be fine # since we don't expect a large number of recipients. for rcpt, listname, command in listnames: rcpttos.remove(rcpt) # If there's any non-list destined recipients left, print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM) if rcpttos: refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? print('we got refusals:', refused, file=DEBUGSTREAM) # Now deliver directly to the list commands mlists = {} s = StringIO(data) msg = Message.Message(s) # These headers are required for the proper execution of Mailman. All # MTAs in existence seem to add these if the original message doesn't # have them. if not msg.get('from'): msg['From'] = mailfrom if not msg.get('date'): msg['Date'] = time.ctime(time.time()) for rcpt, listname, command in listnames: print('sending message to', rcpt, file=DEBUGSTREAM) mlist = mlists.get(listname) if not mlist: mlist = MailList.MailList(listname, lock=0) mlists[listname] = mlist # dispatch on the type of command if command == '': # post msg.Enqueue(mlist, tolist=1) elif command == 'admin': msg.Enqueue(mlist, toadmin=1) elif command == 'owner': msg.Enqueue(mlist, toowner=1) elif command == 'request': msg.Enqueue(mlist, torequest=1) elif command in ('join', 'leave'): # TBD: this is a hack! if command == 'join': msg['Subject'] = 'subscribe' else: msg['Subject'] = 'unsubscribe' msg.Enqueue(mlist, torequest=1) class Options: setuid = True classname = 'PureProxy' size_limit = None enable_SMTPUTF8 = False def parseargs(): global DEBUGSTREAM try: opts, args = getopt.getopt( sys.argv[1:], 'nVhc:s:du', ['class=', 'nosetuid', 'version', 'help', 'size=', 'debug', 'smtputf8']) except getopt.error as e: usage(1, e) options = Options() for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): print(__version__) sys.exit(0) elif opt in ('-n', '--nosetuid'): options.setuid = False elif opt in ('-c', '--class'): options.classname = arg elif opt in ('-d', '--debug'): DEBUGSTREAM = sys.stderr elif opt in ('-u', '--smtputf8'): options.enable_SMTPUTF8 = True elif opt in ('-s', '--size'): try: int_size = int(arg) options.size_limit = int_size except: print('Invalid size: ' + arg, file=sys.stderr) sys.exit(1) # parse the rest of the arguments if len(args) < 1: localspec = 'localhost:8025' remotespec = 'localhost:25' elif len(args) < 2: localspec = args[0] remotespec = 'localhost:25' elif len(args) < 3: localspec = args[0] remotespec = args[1] else: usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) # split into host/port pairs i = localspec.find(':') if i < 0: usage(1, 'Bad local spec: %s' % localspec) options.localhost = localspec[:i] try: options.localport = int(localspec[i+1:]) except ValueError: usage(1, 'Bad local port: %s' % localspec) i = remotespec.find(':') if i < 0: usage(1, 'Bad remote spec: %s' % remotespec) options.remotehost = remotespec[:i] try: options.remoteport = int(remotespec[i+1:]) except ValueError: usage(1, 'Bad remote port: %s' % remotespec) return options if __name__ == '__main__': options = parseargs() # Become nobody classname = options.classname if "." in classname: lastdot = classname.rfind(".") mod = __import__(classname[:lastdot], globals(), locals(), [""]) classname = classname[lastdot+1:] else: import __main__ as mod class_ = getattr(mod, classname) proxy = class_((options.localhost, options.localport), (options.remotehost, options.remoteport), options.size_limit, enable_SMTPUTF8=options.enable_SMTPUTF8) if options.setuid: try: import pwd except ImportError: print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) sys.exit(1) nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) except PermissionError: print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) sys.exit(1) try: asyncore.loop() except KeyboardInterrupt: pass
34,717
966
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/_weakrefset.py
# Access WeakSet through the weakref module. # This code is separated-out because it is needed # by abc.py to load everything else at startup. from _weakref import ref __all__ = ['WeakSet'] class _IterationGuard: # This context manager registers itself in the current iterators of the # weak container, such as to delay all removals until the context manager # exits. # This technique should be relatively thread-safe (since sets are). def __init__(self, weakcontainer): # Don't create cycles self.weakcontainer = ref(weakcontainer) def __enter__(self): w = self.weakcontainer() if w is not None: w._iterating.add(self) return self def __exit__(self, e, t, b): w = self.weakcontainer() if w is not None: s = w._iterating s.remove(self) if not s: w._commit_removals() class WeakSet: def __init__(self, data=None): self.data = set() def _remove(item, selfref=ref(self)): self = selfref() if self is not None: if self._iterating: self._pending_removals.append(item) else: self.data.discard(item) self._remove = _remove # A list of keys to be removed self._pending_removals = [] self._iterating = set() if data is not None: self.update(data) def _commit_removals(self): l = self._pending_removals discard = self.data.discard while l: discard(l.pop()) def __iter__(self): with _IterationGuard(self): for itemref in self.data: item = itemref() if item is not None: # Caveat: the iterator will keep a strong reference to # `item` until it is resumed or closed. yield item def __len__(self): return len(self.data) - len(self._pending_removals) def __contains__(self, item): try: wr = ref(item) except TypeError: return False return wr in self.data def __reduce__(self): return (self.__class__, (list(self),), getattr(self, '__dict__', None)) def add(self, item): if self._pending_removals: self._commit_removals() self.data.add(ref(item, self._remove)) def clear(self): if self._pending_removals: self._commit_removals() self.data.clear() def copy(self): return self.__class__(self) def pop(self): if self._pending_removals: self._commit_removals() while True: try: itemref = self.data.pop() except KeyError: raise KeyError('pop from empty WeakSet') item = itemref() if item is not None: return item def remove(self, item): if self._pending_removals: self._commit_removals() self.data.remove(ref(item)) def discard(self, item): if self._pending_removals: self._commit_removals() self.data.discard(ref(item)) def update(self, other): if self._pending_removals: self._commit_removals() for element in other: self.add(element) def __ior__(self, other): self.update(other) return self def difference(self, other): newset = self.copy() newset.difference_update(other) return newset __sub__ = difference def difference_update(self, other): self.__isub__(other) def __isub__(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.difference_update(ref(item) for item in other) return self def intersection(self, other): return self.__class__(item for item in other if item in self) __and__ = intersection def intersection_update(self, other): self.__iand__(other) def __iand__(self, other): if self._pending_removals: self._commit_removals() self.data.intersection_update(ref(item) for item in other) return self def issubset(self, other): return self.data.issubset(ref(item) for item in other) __le__ = issubset def __lt__(self, other): return self.data < set(ref(item) for item in other) def issuperset(self, other): return self.data.issuperset(ref(item) for item in other) __ge__ = issuperset def __gt__(self, other): return self.data > set(ref(item) for item in other) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.data == set(ref(item) for item in other) def symmetric_difference(self, other): newset = self.copy() newset.symmetric_difference_update(other) return newset __xor__ = symmetric_difference def symmetric_difference_update(self, other): self.__ixor__(other) def __ixor__(self, other): if self._pending_removals: self._commit_removals() if self is other: self.data.clear() else: self.data.symmetric_difference_update(ref(item, self._remove) for item in other) return self def union(self, other): return self.__class__(e for s in (self, other) for e in s) __or__ = union def isdisjoint(self, other): return len(self.intersection(other)) == 0
5,705
197
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/socketserver.py
"""Generic socket server classes. This module tries to capture the various aspects of defining a server: For socket-based servers: - address family: - AF_INET{,6}: IP (Internet Protocol) sockets (default) - AF_UNIX: Unix domain sockets - others, e.g. AF_DECNET are conceivable (see <socket.h> - socket type: - SOCK_STREAM (reliable stream, e.g. TCP) - SOCK_DGRAM (datagrams, e.g. UDP) For request-based servers (including socket-based): - client address verification before further looking at the request (This is actually a hook for any processing that needs to look at the request before anything else, e.g. logging) - how to handle multiple requests: - synchronous (one request is handled at a time) - forking (each request is handled by a new process) - threading (each request is handled by a new thread) The classes in this module favor the server type that is simplest to write: a synchronous TCP/IP server. This is bad class design, but save some typing. (There's also the issue that a deep class hierarchy slows down method lookups.) There are five classes in an inheritance diagram, four of which represent synchronous servers of four types: +------------+ | BaseServer | +------------+ | v +-----------+ +------------------+ | TCPServer |------->| UnixStreamServer | +-----------+ +------------------+ | v +-----------+ +--------------------+ | UDPServer |------->| UnixDatagramServer | +-----------+ +--------------------+ Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer -- the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both unix server classes. Forking and threading versions of each type of server can be created using the ForkingMixIn and ThreadingMixIn mix-in classes. For instance, a threading UDP server class is created as follows: class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass The Mix-in class must come first, since it overrides a method defined in UDPServer! Setting the various member variables also changes the behavior of the underlying server mechanism. To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the request handler subclasses StreamRequestHandler or DatagramRequestHandler. Of course, you still have to use your head! For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by requests (since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child). In this case, you can use a threading server, but you will probably have to use locks to avoid two requests that come in nearly simultaneous to apply conflicting changes to the server state. On the other hand, if you are building e.g. an HTTP server, where all data is stored externally (e.g. in the file system), a synchronous class will essentially render the service "deaf" while one request is being handled -- which may be for a very long time if a client is slow to read all the data it has requested. Here a threading or forking server is appropriate. In some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method. Another approach to handling multiple simultaneous requests in an environment that supports neither threads nor fork (or where these are too expensive or inappropriate for the service) is to maintain an explicit table of partially finished requests and to use a selector to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for a long time (if threads or subprocesses cannot be used). Future work: - Standard classes for Sun RPC (which uses either UDP or TCP) - Standard mix-in classes to implement various authentication and encryption schemes XXX Open problems: - What to do with out-of-band data? BaseServer: - split generic "request" functionality out into BaseServer class. Copyright (C) 2000 Luke Kenneth Casson Leighton <[email protected]> example: read entries from a SQL database (requires overriding get_request() to return a table entry from the database). entry is processed by a RequestHandlerClass. """ # Author of the BaseServer patch: Luke Kenneth Casson Leighton __version__ = "0.4" import socket import selectors import os import errno import sys try: import threading except ImportError: import dummy_threading as threading from io import BufferedIOBase from time import monotonic as time __all__ = ["BaseServer", "TCPServer", "UDPServer", "ThreadingUDPServer", "ThreadingTCPServer", "BaseRequestHandler", "StreamRequestHandler", "DatagramRequestHandler", "ThreadingMixIn"] if hasattr(os, "fork"): __all__.extend(["ForkingUDPServer","ForkingTCPServer", "ForkingMixIn"]) if hasattr(socket, "AF_UNIX"): __all__.extend(["UnixStreamServer","UnixDatagramServer", "ThreadingUnixStreamServer", "ThreadingUnixDatagramServer"]) # poll/select have the advantage of not requiring any extra file descriptor, # contrarily to epoll/kqueue (also, they require a single syscall). if hasattr(selectors, 'PollSelector'): _ServerSelector = selectors.PollSelector else: _ServerSelector = selectors.SelectSelector class BaseServer: """Base class for server classes. Methods for the caller: - __init__(server_address, RequestHandlerClass) - serve_forever(poll_interval=0.5) - shutdown() - handle_request() # if you do not use serve_forever() - fileno() -> int # for selector Methods that may be overridden: - server_bind() - server_activate() - get_request() -> request, client_address - handle_timeout() - verify_request(request, client_address) - server_close() - process_request(request, client_address) - shutdown_request(request) - close_request(request) - service_actions() - handle_error() Methods for derived classes: - finish_request(request, client_address) Class variables that may be overridden by derived classes or instances: - timeout - address_family - socket_type - allow_reuse_address Instance variables: - RequestHandlerClass - socket """ timeout = None def __init__(self, server_address, RequestHandlerClass): """Constructor. May be extended, do not override.""" self.server_address = server_address self.RequestHandlerClass = RequestHandlerClass self.__is_shut_down = threading.Event() self.__shutdown_request = False def server_activate(self): """Called by constructor to activate the server. May be overridden. """ pass def serve_forever(self, poll_interval=0.5): """Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ self.__is_shut_down.clear() try: # XXX: Consider using another file descriptor or connecting to the # socket to wake this up instead of polling. Polling reduces our # responsiveness to a shutdown request and wastes cpu at all other # times. with _ServerSelector() as selector: selector.register(self, selectors.EVENT_READ) while not self.__shutdown_request: ready = selector.select(poll_interval) # bpo-35017: shutdown() called during select(), exit immediately. if self.__shutdown_request: break if ready: self._handle_request_noblock() self.service_actions() finally: self.__shutdown_request = False self.__is_shut_down.set() def shutdown(self): """Stops the serve_forever loop. Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock. """ self.__shutdown_request = True self.__is_shut_down.wait() def service_actions(self): """Called by the serve_forever() loop. May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop. """ pass # The distinction between handling, getting, processing and finishing a # request is fairly arbitrary. Remember: # # - handle_request() is the top-level call. It calls selector.select(), # get_request(), verify_request() and process_request() # - get_request() is different for stream or datagram sockets # - process_request() is the place that may fork a new process or create a # new thread to finish the request # - finish_request() instantiates the request handler class; this # constructor will handle the request all by itself def handle_request(self): """Handle one request, possibly blocking. Respects self.timeout. """ # Support people who used socket.settimeout() to escape # handle_request before self.timeout was available. timeout = self.socket.gettimeout() if timeout is None: timeout = self.timeout elif self.timeout is not None: timeout = min(timeout, self.timeout) if timeout is not None: deadline = time() + timeout # Wait until a request arrives or the timeout expires - the loop is # necessary to accommodate early wakeups due to EINTR. with _ServerSelector() as selector: selector.register(self, selectors.EVENT_READ) while True: ready = selector.select(timeout) if ready: return self._handle_request_noblock() else: if timeout is not None: timeout = deadline - time() if timeout < 0: return self.handle_timeout() def _handle_request_noblock(self): """Handle one request, without blocking. I assume that selector.select() has returned that the socket is readable before this function was called, so there should be no risk of blocking in get_request(). """ try: request, client_address = self.get_request() except OSError: return if self.verify_request(request, client_address): try: self.process_request(request, client_address) except Exception: self.handle_error(request, client_address) self.shutdown_request(request) except: self.shutdown_request(request) raise else: self.shutdown_request(request) def handle_timeout(self): """Called if no new request arrives within self.timeout. Overridden by ForkingMixIn. """ pass def verify_request(self, request, client_address): """Verify the request. May be overridden. Return True if we should proceed with this request. """ return True def process_request(self, request, client_address): """Call finish_request. Overridden by ForkingMixIn and ThreadingMixIn. """ self.finish_request(request, client_address) self.shutdown_request(request) def server_close(self): """Called to clean-up the server. May be overridden. """ pass def finish_request(self, request, client_address): """Finish one request by instantiating RequestHandlerClass.""" self.RequestHandlerClass(request, client_address, self) def shutdown_request(self, request): """Called to shutdown and close an individual request.""" self.close_request(request) def close_request(self, request): """Called to clean up an individual request.""" pass def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden. The default is to print a traceback and continue. """ print('-'*40, file=sys.stderr) print('Exception happened during processing of request from', client_address, file=sys.stderr) import traceback traceback.print_exc() print('-'*40, file=sys.stderr) def __enter__(self): return self def __exit__(self, *args): self.server_close() class TCPServer(BaseServer): """Base class for various socket-based server classes. Defaults to synchronous IP stream (i.e., TCP). Methods for the caller: - __init__(server_address, RequestHandlerClass, bind_and_activate=True) - serve_forever(poll_interval=0.5) - shutdown() - handle_request() # if you don't use serve_forever() - fileno() -> int # for selector Methods that may be overridden: - server_bind() - server_activate() - get_request() -> request, client_address - handle_timeout() - verify_request(request, client_address) - process_request(request, client_address) - shutdown_request(request) - close_request(request) - handle_error() Methods for derived classes: - finish_request(request, client_address) Class variables that may be overridden by derived classes or instances: - timeout - address_family - socket_type - request_queue_size (only for stream sockets) - allow_reuse_address Instance variables: - server_address - RequestHandlerClass - socket """ address_family = socket.AF_INET socket_type = socket.SOCK_STREAM request_queue_size = 5 allow_reuse_address = False def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): """Constructor. May be extended, do not override.""" BaseServer.__init__(self, server_address, RequestHandlerClass) self.socket = socket.socket(self.address_family, self.socket_type) if bind_and_activate: try: self.server_bind() self.server_activate() except: self.server_close() raise def server_bind(self): """Called by constructor to bind the socket. May be overridden. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) self.server_address = self.socket.getsockname() def server_activate(self): """Called by constructor to activate the server. May be overridden. """ self.socket.listen(self.request_queue_size) def server_close(self): """Called to clean-up the server. May be overridden. """ self.socket.close() def fileno(self): """Return socket file number. Interface required by selector. """ return self.socket.fileno() def get_request(self): """Get the request and client address from the socket. May be overridden. """ return self.socket.accept() def shutdown_request(self, request): """Called to shutdown and close an individual request.""" try: #explicitly shutdown. socket.close() merely releases #the socket and waits for GC to perform the actual close. request.shutdown(socket.SHUT_WR) except OSError: pass #some platforms may raise ENOTCONN here self.close_request(request) def close_request(self, request): """Called to clean up an individual request.""" request.close() class UDPServer(TCPServer): """UDP server class.""" allow_reuse_address = False socket_type = socket.SOCK_DGRAM max_packet_size = 8192 def get_request(self): data, client_addr = self.socket.recvfrom(self.max_packet_size) return (data, self.socket), client_addr def server_activate(self): # No need to call listen() for UDP. pass def shutdown_request(self, request): # No need to shutdown anything. self.close_request(request) def close_request(self, request): # No need to close anything. pass if hasattr(os, "fork"): class ForkingMixIn: """Mix-in class to handle each request in a new process.""" timeout = 300 active_children = None max_children = 40 # If true, server_close() waits until all child processes complete. _block_on_close = False def collect_children(self, *, blocking=False): """Internal routine to wait for children that have exited.""" if self.active_children is None: return # If we're above the max number of children, wait and reap them until # we go back below threshold. Note that we use waitpid(-1) below to be # able to collect children in size(<defunct children>) syscalls instead # of size(<children>): the downside is that this might reap children # which we didn't spawn, which is why we only resort to this when we're # above max_children. while len(self.active_children) >= self.max_children: try: pid, _ = os.waitpid(-1, 0) self.active_children.discard(pid) except ChildProcessError: # we don't have any children, we're done self.active_children.clear() except OSError: break # Now reap all defunct children. for pid in self.active_children.copy(): try: flags = 0 if blocking else os.WNOHANG pid, _ = os.waitpid(pid, flags) # if the child hasn't exited yet, pid will be 0 and ignored by # discard() below self.active_children.discard(pid) except ChildProcessError: # someone else reaped it self.active_children.discard(pid) except OSError: pass def handle_timeout(self): """Wait for zombies after self.timeout seconds of inactivity. May be extended, do not override. """ self.collect_children() def service_actions(self): """Collect the zombie child processes regularly in the ForkingMixIn. service_actions is called in the BaseServer's serve_forver loop. """ self.collect_children() def process_request(self, request, client_address): """Fork a new subprocess to process the request.""" pid = os.fork() if pid: # Parent process if self.active_children is None: self.active_children = set() self.active_children.add(pid) self.close_request(request) return else: # Child process. # This must never return, hence os._exit()! status = 1 try: self.finish_request(request, client_address) status = 0 except Exception: self.handle_error(request, client_address) finally: try: self.shutdown_request(request) finally: os._exit(status) def server_close(self): super().server_close() self.collect_children(blocking=self._block_on_close) class ThreadingMixIn: """Mix-in class to handle each request in a new thread.""" # Decides how threads will act upon termination of the # main process daemon_threads = False # If true, server_close() waits until all non-daemonic threads terminate. _block_on_close = False # For non-daemonic threads, list of threading.Threading objects # used by server_close() to wait for all threads completion. _threads = None def process_request_thread(self, request, client_address): """Same as in BaseServer but as a thread. In addition, exception handling is done here. """ try: self.finish_request(request, client_address) except Exception: self.handle_error(request, client_address) finally: self.shutdown_request(request) def process_request(self, request, client_address): """Start a new thread to process the request.""" t = threading.Thread(target = self.process_request_thread, args = (request, client_address)) t.daemon = self.daemon_threads if not t.daemon and self._block_on_close: if self._threads is None: self._threads = [] self._threads.append(t) t.start() def server_close(self): super().server_close() if self._block_on_close: threads = self._threads self._threads = None if threads: for thread in threads: thread.join() if hasattr(os, "fork"): class ForkingUDPServer(ForkingMixIn, UDPServer): pass class ForkingTCPServer(ForkingMixIn, TCPServer): pass class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass if hasattr(socket, 'AF_UNIX'): class UnixStreamServer(TCPServer): address_family = socket.AF_UNIX class UnixDatagramServer(UDPServer): address_family = socket.AF_UNIX class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass class BaseRequestHandler: """Base class for request handler classes. This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address and server, and then calls the handle() method. To implement a specific service, all you need to do is to derive a class which defines a handle() method. The handle() method can find the request as self.request, the client address as self.client_address, and the server (in case it needs access to per-server information) as self.server. Since a separate instance is created for each request, the handle() method can define other arbitrary instance variables. """ def __init__(self, request, client_address, server): self.request = request self.client_address = client_address self.server = server self.setup() try: self.handle() finally: self.finish() def setup(self): pass def handle(self): pass def finish(self): pass # The following two classes make it possible to use the same service # class for stream or datagram servers. # Each class sets up these instance variables: # - rfile: a file object from which receives the request is read # - wfile: a file object to which the reply is written # When the handle() method returns, wfile is flushed properly class StreamRequestHandler(BaseRequestHandler): """Define self.rfile and self.wfile for stream sockets.""" # Default buffer sizes for rfile, wfile. # We default rfile to buffered because otherwise it could be # really slow for large data (a getc() call per byte); we make # wfile unbuffered because (a) often after a write() we want to # read and we need to flush the line; (b) big writes to unbuffered # files are typically optimized by stdio even when big reads # aren't. rbufsize = -1 wbufsize = 0 # A timeout to apply to the request socket, if not None. timeout = None # Disable nagle algorithm for this socket, if True. # Use only when wbufsize != 0, to avoid small packets. disable_nagle_algorithm = False def setup(self): self.connection = self.request if self.timeout is not None: self.connection.settimeout(self.timeout) if self.disable_nagle_algorithm: self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) self.rfile = self.connection.makefile('rb', self.rbufsize) if self.wbufsize == 0: self.wfile = _SocketWriter(self.connection) else: self.wfile = self.connection.makefile('wb', self.wbufsize) def finish(self): if not self.wfile.closed: try: self.wfile.flush() except socket.error: # A final socket error may have occurred here, such as # the local error ECONNABORTED. pass self.wfile.close() self.rfile.close() class _SocketWriter(BufferedIOBase): """Simple writable BufferedIOBase implementation for a socket Does not hold data in a buffer, avoiding any need to call flush().""" def __init__(self, sock): self._sock = sock def writable(self): return True def write(self, b): self._sock.sendall(b) with memoryview(b) as view: return view.nbytes def fileno(self): return self._sock.fileno() class DatagramRequestHandler(BaseRequestHandler): """Define self.rfile and self.wfile for datagram sockets.""" def setup(self): from io import BytesIO self.packet, self.socket = self.request self.rfile = BytesIO(self.packet) self.wfile = BytesIO() def finish(self): self.socket.sendto(self.wfile.getvalue(), self.client_address)
27,010
822
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/mailbox.py
"""Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes.""" # Notes for authors of new mailbox subclasses: # # Remember to fsync() changes to disk before closing a modified file # or returning from a flush() method. See functions _sync_flush() and # _sync_close(). import os import time import calendar import socket import errno import copy import warnings import email import email.message import email.generator import io import contextlib try: import fcntl except ImportError: fcntl = None __all__ = ['Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF', 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage', 'BabylMessage', 'MMDFMessage', 'Error', 'NoSuchMailboxError', 'NotEmptyError', 'ExternalClashError', 'FormatError'] linesep = os.linesep.encode('ascii') class Mailbox: """A group of messages in a particular place.""" def __init__(self, path, factory=None, create=True): """Initialize a Mailbox instance.""" self._path = os.path.abspath(os.path.expanduser(path)) self._factory = factory def add(self, message): """Add message and return assigned key.""" raise NotImplementedError('Method must be implemented by subclass') def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" raise NotImplementedError('Method must be implemented by subclass') def __delitem__(self, key): self.remove(key) def discard(self, key): """If the keyed message exists, remove it.""" try: self.remove(key) except KeyError: pass def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" raise NotImplementedError('Method must be implemented by subclass') def get(self, key, default=None): """Return the keyed message, or default if it doesn't exist.""" try: return self.__getitem__(key) except KeyError: return default def __getitem__(self, key): """Return the keyed message; raise KeyError if it doesn't exist.""" if not self._factory: return self.get_message(key) else: with contextlib.closing(self.get_file(key)) as file: return self._factory(file) def get_message(self, key): """Return a Message representation or raise a KeyError.""" raise NotImplementedError('Method must be implemented by subclass') def get_string(self, key): """Return a string representation or raise a KeyError. Uses email.message.Message to create a 7bit clean string representation of the message.""" return email.message_from_bytes(self.get_bytes(key)).as_string() def get_bytes(self, key): """Return a byte string representation or raise a KeyError.""" raise NotImplementedError('Method must be implemented by subclass') def get_file(self, key): """Return a file-like representation or raise a KeyError.""" raise NotImplementedError('Method must be implemented by subclass') def iterkeys(self): """Return an iterator over keys.""" raise NotImplementedError('Method must be implemented by subclass') def keys(self): """Return a list of keys.""" return list(self.iterkeys()) def itervalues(self): """Return an iterator over all messages.""" for key in self.iterkeys(): try: value = self[key] except KeyError: continue yield value def __iter__(self): return self.itervalues() def values(self): """Return a list of messages. Memory intensive.""" return list(self.itervalues()) def iteritems(self): """Return an iterator over (key, message) tuples.""" for key in self.iterkeys(): try: value = self[key] except KeyError: continue yield (key, value) def items(self): """Return a list of (key, message) tuples. Memory intensive.""" return list(self.iteritems()) def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" raise NotImplementedError('Method must be implemented by subclass') def __len__(self): """Return a count of messages in the mailbox.""" raise NotImplementedError('Method must be implemented by subclass') def clear(self): """Delete all messages.""" for key in self.keys(): self.discard(key) def pop(self, key, default=None): """Delete the keyed message and return it, or default.""" try: result = self[key] except KeyError: return default self.discard(key) return result def popitem(self): """Delete an arbitrary (key, message) pair and return it.""" for key in self.iterkeys(): return (key, self.pop(key)) # This is only run once. else: raise KeyError('No messages in mailbox') def update(self, arg=None): """Change the messages that correspond to certain keys.""" if hasattr(arg, 'iteritems'): source = arg.iteritems() elif hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False for key, message in source: try: self[key] = message except KeyError: bad_key = True if bad_key: raise KeyError('No message with key(s)') def flush(self): """Write any pending changes to the disk.""" raise NotImplementedError('Method must be implemented by subclass') def lock(self): """Lock the mailbox.""" raise NotImplementedError('Method must be implemented by subclass') def unlock(self): """Unlock the mailbox if it is locked.""" raise NotImplementedError('Method must be implemented by subclass') def close(self): """Flush and close the mailbox.""" raise NotImplementedError('Method must be implemented by subclass') def _string_to_bytes(self, message): # If a message is not 7bit clean, we refuse to handle it since it # likely came from reading invalid messages in text mode, and that way # lies mojibake. try: return message.encode('ascii') except UnicodeError: raise ValueError("String input must be ASCII-only; " "use bytes or a Message instead") # Whether each message must end in a newline _append_newline = False def _dump_message(self, message, target, mangle_from_=False): # This assumes the target file is open in binary mode. """Dump message contents to target file.""" if isinstance(message, email.message.Message): buffer = io.BytesIO() gen = email.generator.BytesGenerator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) data = buffer.read() data = data.replace(b'\n', linesep) target.write(data) if self._append_newline and not data.endswith(linesep): # Make sure the message ends with a newline target.write(linesep) elif isinstance(message, (str, bytes, io.StringIO)): if isinstance(message, io.StringIO): warnings.warn("Use of StringIO input is deprecated, " "use BytesIO instead", DeprecationWarning, 3) message = message.getvalue() if isinstance(message, str): message = self._string_to_bytes(message) if mangle_from_: message = message.replace(b'\nFrom ', b'\n>From ') message = message.replace(b'\n', linesep) target.write(message) if self._append_newline and not message.endswith(linesep): # Make sure the message ends with a newline target.write(linesep) elif hasattr(message, 'read'): if hasattr(message, 'buffer'): warnings.warn("Use of text mode files is deprecated, " "use a binary mode file instead", DeprecationWarning, 3) message = message.buffer lastline = None while True: line = message.readline() # Universal newline support. if line.endswith(b'\r\n'): line = line[:-2] + b'\n' elif line.endswith(b'\r'): line = line[:-1] + b'\n' if not line: break if mangle_from_ and line.startswith(b'From '): line = b'>From ' + line[5:] line = line.replace(b'\n', linesep) target.write(line) lastline = line if self._append_newline and lastline and not lastline.endswith(linesep): # Make sure the message ends with a newline target.write(linesep) else: raise TypeError('Invalid message type: %s' % type(message)) class Maildir(Mailbox): """A qmail-style Maildir mailbox.""" colon = ':' def __init__(self, dirname, factory=None, create=True): """Initialize a Maildir instance.""" Mailbox.__init__(self, dirname, factory, create) self._paths = { 'tmp': os.path.join(self._path, 'tmp'), 'new': os.path.join(self._path, 'new'), 'cur': os.path.join(self._path, 'cur'), } if not os.path.exists(self._path): if create: os.mkdir(self._path, 0o700) for path in self._paths.values(): os.mkdir(path, 0o700) else: raise NoSuchMailboxError(self._path) self._toc = {} self._toc_mtimes = {'cur': 0, 'new': 0} self._last_read = 0 # Records last time we read cur/new self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing def add(self, message): """Add message and return assigned key.""" tmp_file = self._create_tmp() try: self._dump_message(message, tmp_file) except BaseException: tmp_file.close() os.remove(tmp_file.name) raise _sync_close(tmp_file) if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = self.colon + message.get_info() if suffix == self.colon: suffix = '' else: subdir = 'new' suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, uniq + suffix) if isinstance(message, MaildirMessage): os.utime(tmp_file.name, (os.path.getatime(tmp_file.name), message.get_date())) # No file modification should be done after the file is moved to its # final position in order to prevent race conditions with changes # from other programs try: try: os.link(tmp_file.name, dest) except (AttributeError, PermissionError): os.rename(tmp_file.name, dest) else: os.remove(tmp_file.name) except OSError as e: os.remove(tmp_file.name) if e.errno == errno.EEXIST: raise ExternalClashError('Name clash with existing message: %s' % dest) else: raise return uniq def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" os.remove(os.path.join(self._path, self._lookup(key))) def discard(self, key): """If the keyed message exists, remove it.""" # This overrides an inapplicable implementation in the superclass. try: self.remove(key) except (KeyError, FileNotFoundError): pass def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" old_subpath = self._lookup(key) temp_key = self.add(message) temp_subpath = self._lookup(temp_key) if isinstance(message, MaildirMessage): # temp's subdir and suffix were specified by message. dominant_subpath = temp_subpath else: # temp's subdir and suffix were defaults from add(). dominant_subpath = old_subpath subdir = os.path.dirname(dominant_subpath) if self.colon in dominant_subpath: suffix = self.colon + dominant_subpath.split(self.colon)[-1] else: suffix = '' self.discard(key) tmp_path = os.path.join(self._path, temp_subpath) new_path = os.path.join(self._path, subdir, key + suffix) if isinstance(message, MaildirMessage): os.utime(tmp_path, (os.path.getatime(tmp_path), message.get_date())) # No file modification should be done after the file is moved to its # final position in order to prevent race conditions with changes # from other programs os.rename(tmp_path, new_path) def get_message(self, key): """Return a Message representation or raise a KeyError.""" subpath = self._lookup(key) with open(os.path.join(self._path, subpath), 'rb') as f: if self._factory: msg = self._factory(f) else: msg = MaildirMessage(f) subdir, name = os.path.split(subpath) msg.set_subdir(subdir) if self.colon in name: msg.set_info(name.split(self.colon)[-1]) msg.set_date(os.path.getmtime(os.path.join(self._path, subpath))) return msg def get_bytes(self, key): """Return a bytes representation or raise a KeyError.""" with open(os.path.join(self._path, self._lookup(key)), 'rb') as f: return f.read().replace(linesep, b'\n') def get_file(self, key): """Return a file-like representation or raise a KeyError.""" f = open(os.path.join(self._path, self._lookup(key)), 'rb') return _ProxyFile(f) def iterkeys(self): """Return an iterator over keys.""" self._refresh() for key in self._toc: try: self._lookup(key) except KeyError: continue yield key def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" self._refresh() return key in self._toc def __len__(self): """Return a count of messages in the mailbox.""" self._refresh() return len(self._toc) def flush(self): """Write any pending changes to disk.""" # Maildir changes are always written immediately, so there's nothing # to do. pass def lock(self): """Lock the mailbox.""" return def unlock(self): """Unlock the mailbox if it is locked.""" return def close(self): """Flush and close the mailbox.""" return def list_folders(self): """Return a list of folder names.""" result = [] for entry in os.listdir(self._path): if len(entry) > 1 and entry[0] == '.' and \ os.path.isdir(os.path.join(self._path, entry)): result.append(entry[1:]) return result def get_folder(self, folder): """Return a Maildir instance for the named folder.""" return Maildir(os.path.join(self._path, '.' + folder), factory=self._factory, create=False) def add_folder(self, folder): """Create a folder and return a Maildir instance representing it.""" path = os.path.join(self._path, '.' + folder) result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if not os.path.exists(maildirfolder_path): os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY, 0o666)) return result def remove_folder(self, folder): """Delete the named folder, which must be empty.""" path = os.path.join(self._path, '.' + folder) for entry in os.listdir(os.path.join(path, 'new')) + \ os.listdir(os.path.join(path, 'cur')): if len(entry) < 1 or entry[0] != '.': raise NotEmptyError('Folder contains message(s): %s' % folder) for entry in os.listdir(path): if entry != 'new' and entry != 'cur' and entry != 'tmp' and \ os.path.isdir(os.path.join(path, entry)): raise NotEmptyError("Folder contains subdirectory '%s': %s" % (folder, entry)) for root, dirs, files in os.walk(path, topdown=False): for entry in files: os.remove(os.path.join(root, entry)) for entry in dirs: os.rmdir(os.path.join(root, entry)) os.rmdir(path) def clean(self): """Delete old files in "tmp".""" now = time.time() for entry in os.listdir(os.path.join(self._path, 'tmp')): path = os.path.join(self._path, 'tmp', entry) if now - os.path.getatime(path) > 129600: # 60 * 60 * 36 os.remove(path) _count = 1 # This is used to generate unique file names. def _create_tmp(self): """Create a file in the tmp subdirectory and open and return it.""" now = time.time() hostname = socket.gethostname() if '/' in hostname: hostname = hostname.replace('/', r'\057') if ':' in hostname: hostname = hostname.replace(':', r'\072') uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(), Maildir._count, hostname) path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) except FileNotFoundError: Maildir._count += 1 try: return _create_carefully(path) except FileExistsError: pass # Fall through to here if stat succeeded or open raised EEXIST. raise ExternalClashError('Name clash prevented file creation: %s' % path) def _refresh(self): """Update table of contents mapping.""" # If it has been less than two seconds since the last _refresh() call, # we have to unconditionally re-read the mailbox just in case it has # been modified, because os.path.mtime() has a 2 sec resolution in the # most common worst case (FAT) and a 1 sec resolution typically. This # results in a few unnecessary re-reads when _refresh() is called # multiple times in that interval, but once the clock ticks over, we # will only re-read as needed. Because the filesystem might be being # served by an independent system with its own clock, we record and # compare with the mtimes from the filesystem. Because the other # system's clock might be skewing relative to our clock, we add an # extra delta to our wait. The default is one tenth second, but is an # instance variable and so can be adjusted if dealing with a # particularly skewed or irregular system. if time.time() - self._last_read > 2 + self._skewfactor: refresh = False for subdir in self._toc_mtimes: mtime = os.path.getmtime(self._paths[subdir]) if mtime > self._toc_mtimes[subdir]: refresh = True self._toc_mtimes[subdir] = mtime if not refresh: return # Refresh toc self._toc = {} for subdir in self._toc_mtimes: path = self._paths[subdir] for entry in os.listdir(path): p = os.path.join(path, entry) if os.path.isdir(p): continue uniq = entry.split(self.colon)[0] self._toc[uniq] = os.path.join(subdir, entry) self._last_read = time.time() def _lookup(self, key): """Use TOC to return subpath for given key, or raise a KeyError.""" try: if os.path.exists(os.path.join(self._path, self._toc[key])): return self._toc[key] except KeyError: pass self._refresh() try: return self._toc[key] except KeyError: raise KeyError('No message with key: %s' % key) # This method is for backward compatibility only. def next(self): """Return the next message in a one-time iteration.""" if not hasattr(self, '_onetime_keys'): self._onetime_keys = self.iterkeys() while True: try: return self[next(self._onetime_keys)] except StopIteration: return None except KeyError: continue class _singlefileMailbox(Mailbox): """A single-file mailbox.""" def __init__(self, path, factory=None, create=True): """Initialize a single-file mailbox.""" Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') except OSError as e: if e.errno == errno.ENOENT: if create: f = open(self._path, 'wb+') else: raise NoSuchMailboxError(self._path) elif e.errno in (errno.EACCES, errno.EROFS): f = open(self._path, 'rb') else: raise self._file = f self._toc = None self._next_key = 0 self._pending = False # No changes require rewriting the file. self._pending_sync = False # No need to sync the file self._locked = False self._file_length = None # Used to record mailbox size def add(self, message): """Add message and return assigned key.""" self._lookup() self._toc[self._next_key] = self._append_message(message) self._next_key += 1 # _append_message appends the message to the mailbox file. We # don't need a full rewrite + rename, sync is enough. self._pending_sync = True return self._next_key - 1 def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" self._lookup(key) del self._toc[key] self._pending = True def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" self._lookup(key) self._toc[key] = self._append_message(message) self._pending = True def iterkeys(self): """Return an iterator over keys.""" self._lookup() yield from self._toc.keys() def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" self._lookup() return key in self._toc def __len__(self): """Return a count of messages in the mailbox.""" self._lookup() return len(self._toc) def lock(self): """Lock the mailbox.""" if not self._locked: _lock_file(self._file) self._locked = True def unlock(self): """Unlock the mailbox if it is locked.""" if self._locked: _unlock_file(self._file) self._locked = False def flush(self): """Write any pending changes to disk.""" if not self._pending: if self._pending_sync: # Messages have only been added, so syncing the file # is enough. _sync_flush(self._file) self._pending_sync = False return # In order to be writing anything out at all, self._toc must # already have been generated (and presumably has been modified # by adding or deleting an item). assert self._toc is not None # Check length of self._file; if it's changed, some other process # has modified the mailbox since we scanned it. self._file.seek(0, 2) cur_len = self._file.tell() if cur_len != self._file_length: raise ExternalClashError('Size of mailbox file changed ' '(expected %i, found %i)' % (self._file_length, cur_len)) new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): start, stop = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_start = new_file.tell() while True: buffer = self._file.read(min(4096, stop - self._file.tell())) if not buffer: break new_file.write(buffer) new_toc[key] = (new_start, new_file.tell()) self._post_message_hook(new_file) self._file_length = new_file.tell() except: new_file.close() os.remove(new_file.name) raise _sync_close(new_file) # self._file is about to get replaced, so no need to sync. self._file.close() # Make sure the new file's mode is the same as the old file's mode = os.stat(self._path).st_mode os.chmod(new_file.name, mode) try: os.rename(new_file.name, self._path) except FileExistsError: os.remove(self._path) os.rename(new_file.name, self._path) self._file = open(self._path, 'rb+') self._toc = new_toc self._pending = False self._pending_sync = False if self._locked: _lock_file(self._file, dotlock=False) def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" return def _pre_message_hook(self, f): """Called before writing each message to file f.""" return def _post_message_hook(self, f): """Called after writing each message to file f.""" return def close(self): """Flush and close the mailbox.""" try: self.flush() finally: try: if self._locked: self.unlock() finally: self._file.close() # Sync has been done by self.flush() above. def _lookup(self, key=None): """Return (start, stop) or raise KeyError.""" if self._toc is None: self._generate_toc() if key is not None: try: return self._toc[key] except KeyError: raise KeyError('No message with key: %s' % key) def _append_message(self, message): """Append message to mailbox and return (start, stop) offsets.""" self._file.seek(0, 2) before = self._file.tell() if len(self._toc) == 0 and not self._pending: # This is the first message, and the _pre_mailbox_hook # hasn't yet been called. If self._pending is True, # messages have been removed, so _pre_mailbox_hook must # have been called already. self._pre_mailbox_hook(self._file) try: self._pre_message_hook(self._file) offsets = self._install_message(message) self._post_message_hook(self._file) except BaseException: self._file.truncate(before) raise self._file.flush() self._file_length = self._file.tell() # Record current length of mailbox return offsets class _mboxMMDF(_singlefileMailbox): """An mbox or MMDF mailbox.""" _mangle_from_ = True def get_message(self, key): """Return a Message representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) from_line = self._file.readline().replace(linesep, b'') string = self._file.read(stop - self._file.tell()) msg = self._message_factory(string.replace(linesep, b'\n')) msg.set_from(from_line[5:].decode('ascii')) return msg def get_string(self, key, from_=False): """Return a string representation or raise a KeyError.""" return email.message_from_bytes( self.get_bytes(key)).as_string(unixfrom=from_) def get_bytes(self, key, from_=False): """Return a string representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) if not from_: self._file.readline() string = self._file.read(stop - self._file.tell()) return string.replace(linesep, b'\n') def get_file(self, key, from_=False): """Return a file-like representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) if not from_: self._file.readline() return _PartialFile(self._file, self._file.tell(), stop) def _install_message(self, message): """Format a message and blindly write to self._file.""" from_line = None if isinstance(message, str): message = self._string_to_bytes(message) if isinstance(message, bytes) and message.startswith(b'From '): newline = message.find(b'\n') if newline != -1: from_line = message[:newline] message = message[newline + 1:] else: from_line = message message = b'' elif isinstance(message, _mboxMMDFMessage): author = message.get_from().encode('ascii') from_line = b'From ' + author elif isinstance(message, email.message.Message): from_line = message.get_unixfrom() # May be None. if from_line is not None: from_line = from_line.encode('ascii') if from_line is None: from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode() start = self._file.tell() self._file.write(from_line + linesep) self._dump_message(message, self._file, self._mangle_from_) stop = self._file.tell() return (start, stop) class mbox(_mboxMMDF): """A classic mbox mailbox.""" _mangle_from_ = True # All messages must end in a newline character, and # _post_message_hooks outputs an empty line between messages. _append_newline = True def __init__(self, path, factory=None, create=True): """Initialize an mbox mailbox.""" self._message_factory = mboxMessage _mboxMMDF.__init__(self, path, factory, create) def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(linesep) def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] last_was_empty = False self._file.seek(0) while True: line_pos = self._file.tell() line = self._file.readline() if line.startswith(b'From '): if len(stops) < len(starts): if last_was_empty: stops.append(line_pos - len(linesep)) else: # The last line before the "From " line wasn't # blank, but we consider it a start of a # message anyway. stops.append(line_pos) starts.append(line_pos) last_was_empty = False elif not line: if last_was_empty: stops.append(line_pos - len(linesep)) else: stops.append(line_pos) break elif line == linesep: last_was_empty = True else: last_was_empty = False self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file_length = self._file.tell() class MMDF(_mboxMMDF): """An MMDF mailbox.""" def __init__(self, path, factory=None, create=True): """Initialize an MMDF mailbox.""" self._message_factory = MMDFMessage _mboxMMDF.__init__(self, path, factory, create) def _pre_message_hook(self, f): """Called before writing each message to file f.""" f.write(b'\001\001\001\001' + linesep) def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(linesep + b'\001\001\001\001' + linesep) def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line.startswith(b'\001\001\001\001' + linesep): starts.append(next_pos) while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == b'\001\001\001\001' + linesep: stops.append(line_pos - len(linesep)) break elif not line: stops.append(line_pos) break elif not line: break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell() class MH(Mailbox): """An MH mailbox.""" def __init__(self, path, factory=None, create=True): """Initialize an MH instance.""" Mailbox.__init__(self, path, factory, create) if not os.path.exists(self._path): if create: os.mkdir(self._path, 0o700) os.close(os.open(os.path.join(self._path, '.mh_sequences'), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) else: raise NoSuchMailboxError(self._path) self._locked = False def add(self, message): """Add message and return assigned key.""" keys = self.keys() if len(keys) == 0: new_key = 1 else: new_key = max(keys) + 1 new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) closed = False try: if self._locked: _lock_file(f) try: try: self._dump_message(message, f) except BaseException: # Unlock and close so it can be deleted on Windows if self._locked: _unlock_file(f) _sync_close(f) closed = True os.remove(new_path) raise if isinstance(message, MHMessage): self._dump_sequences(message, new_key) finally: if self._locked: _unlock_file(f) finally: if not closed: _sync_close(f) return new_key def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except OSError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise else: f.close() os.remove(path) def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except OSError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise try: if self._locked: _lock_file(f) try: os.close(os.open(path, os.O_WRONLY | os.O_TRUNC)) self._dump_message(message, f) if isinstance(message, MHMessage): self._dump_sequences(message, key) finally: if self._locked: _unlock_file(f) finally: _sync_close(f) def get_message(self, key): """Return a Message representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'rb+') else: f = open(os.path.join(self._path, str(key)), 'rb') except OSError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise with f: if self._locked: _lock_file(f) try: msg = MHMessage(f) finally: if self._locked: _unlock_file(f) for name, key_list in self.get_sequences().items(): if key in key_list: msg.add_sequence(name) return msg def get_bytes(self, key): """Return a bytes representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'rb+') else: f = open(os.path.join(self._path, str(key)), 'rb') except OSError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise with f: if self._locked: _lock_file(f) try: return f.read().replace(linesep, b'\n') finally: if self._locked: _unlock_file(f) def get_file(self, key): """Return a file-like representation or raise a KeyError.""" try: f = open(os.path.join(self._path, str(key)), 'rb') except OSError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise return _ProxyFile(f) def iterkeys(self): """Return an iterator over keys.""" return iter(sorted(int(entry) for entry in os.listdir(self._path) if entry.isdigit())) def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" return os.path.exists(os.path.join(self._path, str(key))) def __len__(self): """Return a count of messages in the mailbox.""" return len(list(self.iterkeys())) def lock(self): """Lock the mailbox.""" if not self._locked: self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+') _lock_file(self._file) self._locked = True def unlock(self): """Unlock the mailbox if it is locked.""" if self._locked: _unlock_file(self._file) _sync_close(self._file) del self._file self._locked = False def flush(self): """Write any pending changes to the disk.""" return def close(self): """Flush and close the mailbox.""" if self._locked: self.unlock() def list_folders(self): """Return a list of folder names.""" result = [] for entry in os.listdir(self._path): if os.path.isdir(os.path.join(self._path, entry)): result.append(entry) return result def get_folder(self, folder): """Return an MH instance for the named folder.""" return MH(os.path.join(self._path, folder), factory=self._factory, create=False) def add_folder(self, folder): """Create a folder and return an MH instance representing it.""" return MH(os.path.join(self._path, folder), factory=self._factory) def remove_folder(self, folder): """Delete the named folder, which must be empty.""" path = os.path.join(self._path, folder) entries = os.listdir(path) if entries == ['.mh_sequences']: os.remove(os.path.join(path, '.mh_sequences')) elif entries == []: pass else: raise NotEmptyError('Folder not empty: %s' % self._path) os.rmdir(path) def get_sequences(self): """Return a name-to-key-list dictionary to define each sequence.""" results = {} with open(os.path.join(self._path, '.mh_sequences'), 'r', encoding='ASCII') as f: all_keys = set(self.keys()) for line in f: try: name, contents = line.split(':') keys = set() for spec in contents.split(): if spec.isdigit(): keys.add(int(spec)) else: start, stop = (int(x) for x in spec.split('-')) keys.update(range(start, stop + 1)) results[name] = [key for key in sorted(keys) \ if key in all_keys] if len(results[name]) == 0: del results[name] except ValueError: raise FormatError('Invalid sequence specification: %s' % line.rstrip()) return results def set_sequences(self, sequences): """Set sequences using the given name-to-key-list dictionary.""" f = open(os.path.join(self._path, '.mh_sequences'), 'r+', encoding='ASCII') try: os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) for name, keys in sequences.items(): if len(keys) == 0: continue f.write(name + ':') prev = None completing = False for key in sorted(set(keys)): if key - 1 == prev: if not completing: completing = True f.write('-') elif completing: completing = False f.write('%s %s' % (prev, key)) else: f.write(' %s' % key) prev = key if completing: f.write(str(prev) + '\n') else: f.write('\n') finally: _sync_close(f) def pack(self): """Re-name messages to eliminate numbering gaps. Invalidates keys.""" sequences = self.get_sequences() prev = 0 changes = [] for key in self.iterkeys(): if key - 1 != prev: changes.append((key, prev + 1)) try: os.link(os.path.join(self._path, str(key)), os.path.join(self._path, str(prev + 1))) except (AttributeError, PermissionError): os.rename(os.path.join(self._path, str(key)), os.path.join(self._path, str(prev + 1))) else: os.unlink(os.path.join(self._path, str(key))) prev += 1 self._next_key = prev + 1 if len(changes) == 0: return for name, key_list in sequences.items(): for old, new in changes: if old in key_list: key_list[key_list.index(old)] = new self.set_sequences(sequences) def _dump_sequences(self, message, key): """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() for name, key_list in all_sequences.items(): if name in pending_sequences: key_list.append(key) elif key in key_list: del key_list[key_list.index(key)] for sequence in pending_sequences: if sequence not in all_sequences: all_sequences[sequence] = [key] self.set_sequences(all_sequences) class Babyl(_singlefileMailbox): """An Rmail-style Babyl mailbox.""" _special_labels = frozenset({'unseen', 'deleted', 'filed', 'answered', 'forwarded', 'edited', 'resent'}) def __init__(self, path, factory=None, create=True): """Initialize a Babyl mailbox.""" _singlefileMailbox.__init__(self, path, factory, create) self._labels = {} def add(self, message): """Add message and return assigned key.""" key = _singlefileMailbox.add(self, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels() return key def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" _singlefileMailbox.remove(self, key) if key in self._labels: del self._labels[key] def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" _singlefileMailbox.__setitem__(self, key, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels() def get_message(self, key): """Return a Message representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) self._file.readline() # Skip b'1,' line specifying labels. original_headers = io.BytesIO() while True: line = self._file.readline() if line == b'*** EOOH ***' + linesep or not line: break original_headers.write(line.replace(linesep, b'\n')) visible_headers = io.BytesIO() while True: line = self._file.readline() if line == linesep or not line: break visible_headers.write(line.replace(linesep, b'\n')) # Read up to the stop, or to the end n = stop - self._file.tell() assert n >= 0 body = self._file.read(n) body = body.replace(linesep, b'\n') msg = BabylMessage(original_headers.getvalue() + body) msg.set_visible(visible_headers.getvalue()) if key in self._labels: msg.set_labels(self._labels[key]) return msg def get_bytes(self, key): """Return a string representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) self._file.readline() # Skip b'1,' line specifying labels. original_headers = io.BytesIO() while True: line = self._file.readline() if line == b'*** EOOH ***' + linesep or not line: break original_headers.write(line.replace(linesep, b'\n')) while True: line = self._file.readline() if line == linesep or not line: break headers = original_headers.getvalue() n = stop - self._file.tell() assert n >= 0 data = self._file.read(n) data = data.replace(linesep, b'\n') return headers + data def get_file(self, key): """Return a file-like representation or raise a KeyError.""" return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep)) def get_labels(self): """Return a list of user-defined labels in the mailbox.""" self._lookup() labels = set() for label_list in self._labels.values(): labels.update(label_list) labels.difference_update(self._special_labels) return list(labels) def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 label_lists = [] while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == b'\037\014' + linesep: if len(stops) < len(starts): stops.append(line_pos - len(linesep)) starts.append(next_pos) labels = [label.strip() for label in self._file.readline()[1:].split(b',') if label.strip()] label_lists.append(labels) elif line == b'\037' or line == b'\037' + linesep: if len(stops) < len(starts): stops.append(line_pos - len(linesep)) elif not line: stops.append(line_pos - len(linesep)) break self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell() def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" babyl = b'BABYL OPTIONS:' + linesep babyl += b'Version: 5' + linesep labels = self.get_labels() labels = (label.encode() for label in labels) babyl += b'Labels:' + b','.join(labels) + linesep babyl += b'\037' f.write(babyl) def _pre_message_hook(self, f): """Called before writing each message to file f.""" f.write(b'\014' + linesep) def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(linesep + b'\037') def _install_message(self, message): """Write message contents and return (start, stop).""" start = self._file.tell() if isinstance(message, BabylMessage): special_labels = [] labels = [] for label in message.get_labels(): if label in self._special_labels: special_labels.append(label) else: labels.append(label) self._file.write(b'1') for label in special_labels: self._file.write(b', ' + label.encode()) self._file.write(b',,') for label in labels: self._file.write(b' ' + label.encode() + b',') self._file.write(linesep) else: self._file.write(b'1,,' + linesep) if isinstance(message, email.message.Message): orig_buffer = io.BytesIO() orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0) orig_generator.flatten(message) orig_buffer.seek(0) while True: line = orig_buffer.readline() self._file.write(line.replace(b'\n', linesep)) if line == b'\n' or not line: break self._file.write(b'*** EOOH ***' + linesep) if isinstance(message, BabylMessage): vis_buffer = io.BytesIO() vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0) vis_generator.flatten(message.get_visible()) while True: line = vis_buffer.readline() self._file.write(line.replace(b'\n', linesep)) if line == b'\n' or not line: break else: orig_buffer.seek(0) while True: line = orig_buffer.readline() self._file.write(line.replace(b'\n', linesep)) if line == b'\n' or not line: break while True: buffer = orig_buffer.read(4096) # Buffer size is arbitrary. if not buffer: break self._file.write(buffer.replace(b'\n', linesep)) elif isinstance(message, (bytes, str, io.StringIO)): if isinstance(message, io.StringIO): warnings.warn("Use of StringIO input is deprecated, " "use BytesIO instead", DeprecationWarning, 3) message = message.getvalue() if isinstance(message, str): message = self._string_to_bytes(message) body_start = message.find(b'\n\n') + 2 if body_start - 2 != -1: self._file.write(message[:body_start].replace(b'\n', linesep)) self._file.write(b'*** EOOH ***' + linesep) self._file.write(message[:body_start].replace(b'\n', linesep)) self._file.write(message[body_start:].replace(b'\n', linesep)) else: self._file.write(b'*** EOOH ***' + linesep + linesep) self._file.write(message.replace(b'\n', linesep)) elif hasattr(message, 'readline'): if hasattr(message, 'buffer'): warnings.warn("Use of text mode files is deprecated, " "use a binary mode file instead", DeprecationWarning, 3) message = message.buffer original_pos = message.tell() first_pass = True while True: line = message.readline() # Universal newline support. if line.endswith(b'\r\n'): line = line[:-2] + b'\n' elif line.endswith(b'\r'): line = line[:-1] + b'\n' self._file.write(line.replace(b'\n', linesep)) if line == b'\n' or not line: if first_pass: first_pass = False self._file.write(b'*** EOOH ***' + linesep) message.seek(original_pos) else: break while True: line = message.readline() if not line: break # Universal newline support. if line.endswith(b'\r\n'): line = line[:-2] + linesep elif line.endswith(b'\r'): line = line[:-1] + linesep elif line.endswith(b'\n'): line = line[:-1] + linesep self._file.write(line) else: raise TypeError('Invalid message type: %s' % type(message)) stop = self._file.tell() return (start, stop) class Message(email.message.Message): """Message with mailbox-format-specific properties.""" def __init__(self, message=None): """Initialize a Message instance.""" if isinstance(message, email.message.Message): self._become_message(copy.deepcopy(message)) if isinstance(message, Message): message._explain_to(self) elif isinstance(message, bytes): self._become_message(email.message_from_bytes(message)) elif isinstance(message, str): self._become_message(email.message_from_string(message)) elif isinstance(message, io.TextIOWrapper): self._become_message(email.message_from_file(message)) elif hasattr(message, "read"): self._become_message(email.message_from_binary_file(message)) elif message is None: email.message.Message.__init__(self) else: raise TypeError('Invalid message type: %s' % type(message)) def _become_message(self, message): """Assume the non-format-specific state of message.""" type_specific = getattr(message, '_type_specific_attributes', []) for name in message.__dict__: if name not in type_specific: self.__dict__[name] = message.__dict__[name] def _explain_to(self, message): """Copy format-specific state to message insofar as possible.""" if isinstance(message, Message): return # There's nothing format-specific to explain. else: raise TypeError('Cannot convert to specified type') class MaildirMessage(Message): """Message with Maildir-specific properties.""" _type_specific_attributes = ['_subdir', '_info', '_date'] def __init__(self, message=None): """Initialize a MaildirMessage instance.""" self._subdir = 'new' self._info = '' self._date = time.time() Message.__init__(self, message) def get_subdir(self): """Return 'new' or 'cur'.""" return self._subdir def set_subdir(self, subdir): """Set subdir to 'new' or 'cur'.""" if subdir == 'new' or subdir == 'cur': self._subdir = subdir else: raise ValueError("subdir must be 'new' or 'cur': %s" % subdir) def get_flags(self): """Return as a string the flags that are set.""" if self._info.startswith('2,'): return self._info[2:] else: return '' def set_flags(self, flags): """Set the given flags and unset all others.""" self._info = '2,' + ''.join(sorted(flags)) def add_flag(self, flag): """Set the given flag(s) without changing others.""" self.set_flags(''.join(set(self.get_flags()) | set(flag))) def remove_flag(self, flag): """Unset the given string flag(s) without changing others.""" if self.get_flags(): self.set_flags(''.join(set(self.get_flags()) - set(flag))) def get_date(self): """Return delivery date of message, in seconds since the epoch.""" return self._date def set_date(self, date): """Set delivery date of message, in seconds since the epoch.""" try: self._date = float(date) except ValueError: raise TypeError("can't convert to float: %s" % date) def get_info(self): """Get the message's "info" as a string.""" return self._info def set_info(self, info): """Set the message's "info" string.""" if isinstance(info, str): self._info = info else: raise TypeError('info must be a string: %s' % type(info)) def _explain_to(self, message): """Copy Maildir-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): message.set_flags(self.get_flags()) message.set_subdir(self.get_subdir()) message.set_date(self.get_date()) elif isinstance(message, _mboxMMDFMessage): flags = set(self.get_flags()) if 'S' in flags: message.add_flag('R') if self.get_subdir() == 'cur': message.add_flag('O') if 'T' in flags: message.add_flag('D') if 'F' in flags: message.add_flag('F') if 'R' in flags: message.add_flag('A') message.set_from('MAILER-DAEMON', time.gmtime(self.get_date())) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if 'S' not in flags: message.add_sequence('unseen') if 'R' in flags: message.add_sequence('replied') if 'F' in flags: message.add_sequence('flagged') elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if 'S' not in flags: message.add_label('unseen') if 'T' in flags: message.add_label('deleted') if 'R' in flags: message.add_label('answered') if 'P' in flags: message.add_label('forwarded') elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message)) class _mboxMMDFMessage(Message): """Message with mbox- or MMDF-specific properties.""" _type_specific_attributes = ['_from'] def __init__(self, message=None): """Initialize an mboxMMDFMessage instance.""" self.set_from('MAILER-DAEMON', True) if isinstance(message, email.message.Message): unixfrom = message.get_unixfrom() if unixfrom is not None and unixfrom.startswith('From '): self.set_from(unixfrom[5:]) Message.__init__(self, message) def get_from(self): """Return contents of "From " line.""" return self._from def set_from(self, from_, time_=None): """Set "From " line, formatting and appending time_ if specified.""" if time_ is not None: if time_ is True: time_ = time.gmtime() from_ += ' ' + time.asctime(time_) self._from = from_ def get_flags(self): """Return as a string the flags that are set.""" return self.get('Status', '') + self.get('X-Status', '') def set_flags(self, flags): """Set the given flags and unset all others.""" flags = set(flags) status_flags, xstatus_flags = '', '' for flag in ('R', 'O'): if flag in flags: status_flags += flag flags.remove(flag) for flag in ('D', 'F', 'A'): if flag in flags: xstatus_flags += flag flags.remove(flag) xstatus_flags += ''.join(sorted(flags)) try: self.replace_header('Status', status_flags) except KeyError: self.add_header('Status', status_flags) try: self.replace_header('X-Status', xstatus_flags) except KeyError: self.add_header('X-Status', xstatus_flags) def add_flag(self, flag): """Set the given flag(s) without changing others.""" self.set_flags(''.join(set(self.get_flags()) | set(flag))) def remove_flag(self, flag): """Unset the given string flag(s) without changing others.""" if 'Status' in self or 'X-Status' in self: self.set_flags(''.join(set(self.get_flags()) - set(flag))) def _explain_to(self, message): """Copy mbox- or MMDF-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): flags = set(self.get_flags()) if 'O' in flags: message.set_subdir('cur') if 'F' in flags: message.add_flag('F') if 'A' in flags: message.add_flag('R') if 'R' in flags: message.add_flag('S') if 'D' in flags: message.add_flag('T') del message['status'] del message['x-status'] maybe_date = ' '.join(self.get_from().split()[-5:]) try: message.set_date(calendar.timegm(time.strptime(maybe_date, '%a %b %d %H:%M:%S %Y'))) except (ValueError, OverflowError): pass elif isinstance(message, _mboxMMDFMessage): message.set_flags(self.get_flags()) message.set_from(self.get_from()) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if 'R' not in flags: message.add_sequence('unseen') if 'A' in flags: message.add_sequence('replied') if 'F' in flags: message.add_sequence('flagged') del message['status'] del message['x-status'] elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if 'R' not in flags: message.add_label('unseen') if 'D' in flags: message.add_label('deleted') if 'A' in flags: message.add_label('answered') del message['status'] del message['x-status'] elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message)) class mboxMessage(_mboxMMDFMessage): """Message with mbox-specific properties.""" class MHMessage(Message): """Message with MH-specific properties.""" _type_specific_attributes = ['_sequences'] def __init__(self, message=None): """Initialize an MHMessage instance.""" self._sequences = [] Message.__init__(self, message) def get_sequences(self): """Return a list of sequences that include the message.""" return self._sequences[:] def set_sequences(self, sequences): """Set the list of sequences that include the message.""" self._sequences = list(sequences) def add_sequence(self, sequence): """Add sequence to list of sequences including the message.""" if isinstance(sequence, str): if not sequence in self._sequences: self._sequences.append(sequence) else: raise TypeError('sequence type must be str: %s' % type(sequence)) def remove_sequence(self, sequence): """Remove sequence from the list of sequences including the message.""" try: self._sequences.remove(sequence) except ValueError: pass def _explain_to(self, message): """Copy MH-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('R') elif isinstance(message, _mboxMMDFMessage): sequences = set(self.get_sequences()) if 'unseen' not in sequences: message.add_flag('RO') else: message.add_flag('O') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('A') elif isinstance(message, MHMessage): for sequence in self.get_sequences(): message.add_sequence(sequence) elif isinstance(message, BabylMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.add_label('unseen') if 'replied' in sequences: message.add_label('answered') elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message)) class BabylMessage(Message): """Message with Babyl-specific properties.""" _type_specific_attributes = ['_labels', '_visible'] def __init__(self, message=None): """Initialize a BabylMessage instance.""" self._labels = [] self._visible = Message() Message.__init__(self, message) def get_labels(self): """Return a list of labels on the message.""" return self._labels[:] def set_labels(self, labels): """Set the list of labels on the message.""" self._labels = list(labels) def add_label(self, label): """Add label to list of labels on the message.""" if isinstance(label, str): if label not in self._labels: self._labels.append(label) else: raise TypeError('label must be a string: %s' % type(label)) def remove_label(self, label): """Remove label from the list of labels on the message.""" try: self._labels.remove(label) except ValueError: pass def get_visible(self): """Return a Message representation of visible headers.""" return Message(self._visible) def set_visible(self, visible): """Set the Message representation of visible headers.""" self._visible = Message(visible) def update_visible(self): """Update and/or sensibly generate a set of visible headers.""" for header in self._visible.keys(): if header in self: self._visible.replace_header(header, self[header]) else: del self._visible[header] for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'): if header in self and header not in self._visible: self._visible[header] = self[header] def _explain_to(self, message): """Copy Babyl-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): labels = set(self.get_labels()) if 'unseen' in labels: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'forwarded' in labels or 'resent' in labels: message.add_flag('P') if 'answered' in labels: message.add_flag('R') if 'deleted' in labels: message.add_flag('T') elif isinstance(message, _mboxMMDFMessage): labels = set(self.get_labels()) if 'unseen' not in labels: message.add_flag('RO') else: message.add_flag('O') if 'deleted' in labels: message.add_flag('D') if 'answered' in labels: message.add_flag('A') elif isinstance(message, MHMessage): labels = set(self.get_labels()) if 'unseen' in labels: message.add_sequence('unseen') if 'answered' in labels: message.add_sequence('replied') elif isinstance(message, BabylMessage): message.set_visible(self.get_visible()) for label in self.get_labels(): message.add_label(label) elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message)) class MMDFMessage(_mboxMMDFMessage): """Message with MMDF-specific properties.""" class _ProxyFile: """A read-only wrapper of a file.""" def __init__(self, f, pos=None): """Initialize a _ProxyFile.""" self._file = f if pos is None: self._pos = f.tell() else: self._pos = pos def read(self, size=None): """Read bytes.""" return self._read(size, self._file.read) def read1(self, size=None): """Read bytes.""" return self._read(size, self._file.read1) def readline(self, size=None): """Read a line.""" return self._read(size, self._file.readline) def readlines(self, sizehint=None): """Read multiple lines.""" result = [] for line in self: result.append(line) if sizehint is not None: sizehint -= len(line) if sizehint <= 0: break return result def __iter__(self): """Iterate over lines.""" while True: line = self.readline() if not line: return yield line def tell(self): """Return the position.""" return self._pos def seek(self, offset, whence=0): """Change position.""" if whence == 1: self._file.seek(self._pos) self._file.seek(offset, whence) self._pos = self._file.tell() def close(self): """Close the file.""" if hasattr(self, '_file'): try: if hasattr(self._file, 'close'): self._file.close() finally: del self._file def _read(self, size, read_method): """Read size bytes using read_method.""" if size is None: size = -1 self._file.seek(self._pos) result = read_method(size) self._pos = self._file.tell() return result def __enter__(self): """Context management protocol support.""" return self def __exit__(self, *exc): self.close() def readable(self): return self._file.readable() def writable(self): return self._file.writable() def seekable(self): return self._file.seekable() def flush(self): return self._file.flush() @property def closed(self): if not hasattr(self, '_file'): return True if not hasattr(self._file, 'closed'): return False return self._file.closed class _PartialFile(_ProxyFile): """A read-only wrapper of part of a file.""" def __init__(self, f, start=None, stop=None): """Initialize a _PartialFile.""" _ProxyFile.__init__(self, f, start) self._start = start self._stop = stop def tell(self): """Return the position with respect to start.""" return _ProxyFile.tell(self) - self._start def seek(self, offset, whence=0): """Change position, possibly with respect to start or stop.""" if whence == 0: self._pos = self._start whence = 1 elif whence == 2: self._pos = self._stop whence = 1 _ProxyFile.seek(self, offset, whence) def _read(self, size, read_method): """Read size bytes using read_method, honoring start and stop.""" remaining = self._stop - self._pos if remaining <= 0: return b'' if size is None or size < 0 or size > remaining: size = remaining return _ProxyFile._read(self, size, read_method) def close(self): # do *not* close the underlying file object for partial files, # since it's global to the mailbox object if hasattr(self, '_file'): del self._file def _lock_file(f, dotlock=True): """Lock file f using lockf and dot locking.""" dotlock_done = False try: if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as e: if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS): raise ExternalClashError('lockf: lock unavailable: %s' % f.name) else: raise if dotlock: try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() except OSError as e: if e.errno in (errno.EACCES, errno.EROFS): return # Without write access, just skip dotlocking. else: raise try: try: os.link(pre_lock.name, f.name + '.lock') dotlock_done = True except (AttributeError, PermissionError): os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True else: os.unlink(pre_lock.name) except FileExistsError: os.remove(pre_lock.name) raise ExternalClashError('dot lock unavailable: %s' % f.name) except: if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) if dotlock_done: os.remove(f.name + '.lock') raise def _unlock_file(f): """Unlock file f using lockf and dot locking.""" if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) if os.path.exists(f.name + '.lock'): os.remove(f.name + '.lock') def _create_carefully(path): """Create a file if it doesn't exist and open for reading and writing.""" fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666) try: return open(path, 'rb+') finally: os.close(fd) def _create_temporary(path): """Create a temp file based on path and open for reading and writing.""" return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()), socket.gethostname(), os.getpid())) def _sync_flush(f): """Ensure changes to file f are physically on disk.""" f.flush() # TODO(jart): Why does this need fsync() lool? #if hasattr(os, 'fsync'): # os.fsync(f.fileno()) def _sync_close(f): """Close file f, ensuring all changes are physically on disk.""" _sync_flush(f) f.close() class Error(Exception): """Raised for module-specific errors.""" class NoSuchMailboxError(Error): """The specified mailbox does not exist and won't be created.""" class NotEmptyError(Error): """The specified mailbox is not empty and deletion was requested.""" class ExternalClashError(Error): """Another process caused an action to fail.""" class FormatError(Error): """A file appears to have an invalid format."""
78,677
2,148
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/base64.py
#! /usr/bin/env python3 """Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings""" # Modified 04-Oct-1995 by Jack Jansen to use binascii module # Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support # Modified 22-May-2007 by Guido van Rossum to use bytes everywhere import re import struct import binascii __all__ = [ # Legacy interface exports traditional RFC 2045 Base64 encodings 'encode', 'decode', 'encodebytes', 'decodebytes', # Generalized interface for other encodings 'b64encode', 'b64decode', 'b32encode', 'b32decode', 'b16encode', 'b16decode', # Base85 and Ascii85 encodings 'b85encode', 'b85decode', 'a85encode', 'a85decode', # Standard Base64 encoding 'standard_b64encode', 'standard_b64decode', # Some common Base64 alternatives. As referenced by RFC 3458, see thread # starting at: # # http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html 'urlsafe_b64encode', 'urlsafe_b64decode', ] bytes_types = (bytes, bytearray) # Types acceptable as binary data def _bytes_from_decode_data(s): if isinstance(s, str): try: return s.encode('ascii') except UnicodeEncodeError: raise ValueError('string argument should contain only ASCII characters') if isinstance(s, bytes_types): return s try: return memoryview(s).tobytes() except TypeError: raise TypeError("argument should be a bytes-like object or ASCII " "string, not %r" % s.__class__.__name__) from None # Base64 encoding/decoding uses binascii def b64encode(s, altchars=None): """Encode the bytes-like object s using Base64 and return a bytes object. Optional altchars should be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. """ encoded = binascii.b2a_base64(s, newline=False) if altchars is not None: assert len(altchars) == 2, repr(altchars) return encoded.translate(bytes.maketrans(b'+/', altchars)) return encoded def b64decode(s, altchars=None, validate=False): """Decode the Base64 encoded bytes-like object or ASCII string s. Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. The result is returned as a bytes object. A binascii.Error is raised if s is incorrectly padded. If validate is False (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is True, these non-alphabet characters in the input result in a binascii.Error. """ s = _bytes_from_decode_data(s) if altchars is not None: altchars = _bytes_from_decode_data(altchars) assert len(altchars) == 2, repr(altchars) s = s.translate(bytes.maketrans(altchars, b'+/')) if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s): raise binascii.Error('Non-base64 digit found') return binascii.a2b_base64(s) def standard_b64encode(s): """Encode bytes-like object s using the standard Base64 alphabet. The result is returned as a bytes object. """ return b64encode(s) def standard_b64decode(s): """Decode bytes encoded with the standard Base64 alphabet. Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input is incorrectly padded. Characters that are not in the standard alphabet are discarded prior to the padding check. """ return b64decode(s) _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_') _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/') def urlsafe_b64encode(s): """Encode bytes using the URL- and filesystem-safe Base64 alphabet. Argument s is a bytes-like object to encode. The result is returned as a bytes object. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ return b64encode(s).translate(_urlsafe_encode_translation) def urlsafe_b64decode(s): """Decode bytes using the URL- and filesystem-safe Base64 alphabet. Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input is incorrectly padded. Characters that are not in the URL-safe base-64 alphabet, and are not a plus '+' or slash '/', are discarded prior to the padding check. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ s = _bytes_from_decode_data(s) s = s.translate(_urlsafe_decode_translation) return b64decode(s) # Base32 encoding/decoding must be done in Python _b32alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' _b32tab2 = None _b32rev = None def b32encode(s): """Encode the bytes-like object s using Base32 and return a bytes object. """ global _b32tab2 # Delay the initialization of the table to not waste memory # if the function is never called if _b32tab2 is None: b32tab = [bytes((i,)) for i in _b32alphabet] _b32tab2 = [a + b for a in b32tab for b in b32tab] b32tab = None if not isinstance(s, bytes_types): s = memoryview(s).tobytes() leftover = len(s) % 5 # Pad the last quantum with zero bits if necessary if leftover: s = s + b'\0' * (5 - leftover) # Don't use += ! encoded = bytearray() from_bytes = int.from_bytes b32tab2 = _b32tab2 for i in range(0, len(s), 5): c = from_bytes(s[i: i + 5], 'big') encoded += (b32tab2[c >> 30] + # bits 1 - 10 b32tab2[(c >> 20) & 0x3ff] + # bits 11 - 20 b32tab2[(c >> 10) & 0x3ff] + # bits 21 - 30 b32tab2[c & 0x3ff] # bits 31 - 40 ) # Adjust for any leftover partial quanta if leftover == 1: encoded[-6:] = b'======' elif leftover == 2: encoded[-4:] = b'====' elif leftover == 3: encoded[-3:] = b'===' elif leftover == 4: encoded[-1:] = b'=' return bytes(encoded) def b32decode(s, casefold=False, map01=None): """Decode the Base32 encoded bytes-like object or ASCII string s. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. The result is returned as a bytes object. A binascii.Error is raised if the input is incorrectly padded or if there are non-alphabet characters present in the input. """ global _b32rev # Delay the initialization of the table to not waste memory # if the function is never called if _b32rev is None: _b32rev = {v: k for k, v in enumerate(_b32alphabet)} s = _bytes_from_decode_data(s) if len(s) % 8: raise binascii.Error('Incorrect padding') # Handle section 2.4 zero and one mapping. The flag map01 will be either # False, or the character to map the digit 1 (one) to. It should be # either L (el) or I (eye). if map01 is not None: map01 = _bytes_from_decode_data(map01) assert len(map01) == 1, repr(map01) s = s.translate(bytes.maketrans(b'01', b'O' + map01)) if casefold: s = s.upper() # Strip off pad characters from the right. We need to count the pad # characters because this will tell us how many null bytes to remove from # the end of the decoded string. l = len(s) s = s.rstrip(b'=') padchars = l - len(s) # Now decode the full quanta decoded = bytearray() b32rev = _b32rev for i in range(0, len(s), 8): quanta = s[i: i + 8] acc = 0 try: for c in quanta: acc = (acc << 5) + b32rev[c] except KeyError: raise binascii.Error('Non-base32 digit found') from None decoded += acc.to_bytes(5, 'big') # Process the last, partial quanta if l % 8 or padchars not in {0, 1, 3, 4, 6}: raise binascii.Error('Incorrect padding') if padchars and decoded: acc <<= 5 * padchars last = acc.to_bytes(5, 'big') leftover = (43 - 5 * padchars) // 8 # 1: 4, 3: 3, 4: 2, 6: 1 decoded[-5:] = last[:leftover] return bytes(decoded) # RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns # lowercase. The RFC also recommends against accepting input case # insensitively. def b16encode(s): """Encode the bytes-like object s using Base16 and return a bytes object. """ return binascii.hexlify(s).upper() def b16decode(s, casefold=False): """Decode the Base16 encoded bytes-like object or ASCII string s. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The result is returned as a bytes object. A binascii.Error is raised if s is incorrectly padded or if there are non-alphabet characters present in the input. """ s = _bytes_from_decode_data(s) if casefold: s = s.upper() if re.search(b'[^0-9A-F]', s): raise binascii.Error('Non-base16 digit found') return binascii.unhexlify(s) # # Ascii85 encoding/decoding # _a85chars = None _a85chars2 = None _A85START = b"<~" _A85END = b"~>" def _85encode(b, chars, chars2, pad=False, foldnuls=False, foldspaces=False): # Helper function for a85encode and b85encode if not isinstance(b, bytes_types): b = memoryview(b).tobytes() padding = (-len(b)) % 4 if padding: b = b + b'\0' * padding words = struct.Struct('!%dI' % (len(b) // 4)).unpack(b) chunks = [b'z' if foldnuls and not word else b'y' if foldspaces and word == 0x20202020 else (chars2[word // 614125] + chars2[word // 85 % 7225] + chars[word % 85]) for word in words] if padding and not pad: if chunks[-1] == b'z': chunks[-1] = chars[0] * 5 chunks[-1] = chunks[-1][:-padding] return b''.join(chunks) def a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False): """Encode bytes-like object b using Ascii85 and return a bytes object. foldspaces is an optional flag that uses the special short sequence 'y' instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This feature is not supported by the "standard" Adobe encoding. wrapcol controls whether the output should have newline (b'\\n') characters added to it. If this is non-zero, each output line will be at most this many characters long. pad controls whether the input is padded to a multiple of 4 before encoding. Note that the btoa implementation always pads. adobe controls whether the encoded byte sequence is framed with <~ and ~>, which is used by the Adobe implementation. """ global _a85chars, _a85chars2 # Delay the initialization of tables to not waste memory # if the function is never called if _a85chars is None: _a85chars = [bytes((i,)) for i in range(33, 118)] _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars] result = _85encode(b, _a85chars, _a85chars2, pad, True, foldspaces) if adobe: result = _A85START + result if wrapcol: wrapcol = max(2 if adobe else 1, wrapcol) chunks = [result[i: i + wrapcol] for i in range(0, len(result), wrapcol)] if adobe: if len(chunks[-1]) + 2 > wrapcol: chunks.append(b'') result = b'\n'.join(chunks) if adobe: result += _A85END return result def a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v'): """Decode the Ascii85 encoded bytes-like object or ASCII string b. foldspaces is a flag that specifies whether the 'y' short sequence should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is not supported by the "standard" Adobe encoding. adobe controls whether the input sequence is in Adobe Ascii85 format (i.e. is framed with <~ and ~>). ignorechars should be a byte string containing characters to ignore from the input. This should only contain whitespace characters, and by default contains all whitespace characters in ASCII. The result is returned as a bytes object. """ b = _bytes_from_decode_data(b) if adobe: if not b.endswith(_A85END): raise ValueError( "Ascii85 encoded byte sequences must end " "with {!r}".format(_A85END) ) if b.startswith(_A85START): b = b[2:-2] # Strip off start/end markers else: b = b[:-2] # # We have to go through this stepwise, so as to ignore spaces and handle # special short sequences # packI = struct.Struct('!I').pack decoded = [] decoded_append = decoded.append curr = [] curr_append = curr.append curr_clear = curr.clear for x in b + b'u' * 4: if b'!'[0] <= x <= b'u'[0]: curr_append(x) if len(curr) == 5: acc = 0 for x in curr: acc = 85 * acc + (x - 33) try: decoded_append(packI(acc)) except struct.error: raise ValueError('Ascii85 overflow') from None curr_clear() elif x == b'z'[0]: if curr: raise ValueError('z inside Ascii85 5-tuple') decoded_append(b'\0\0\0\0') elif foldspaces and x == b'y'[0]: if curr: raise ValueError('y inside Ascii85 5-tuple') decoded_append(b'\x20\x20\x20\x20') elif x in ignorechars: # Skip whitespace continue else: raise ValueError('Non-Ascii85 digit found: %c' % x) result = b''.join(decoded) padding = 4 - len(curr) if padding: # Throw away the extra padding result = result[:-padding] return result # The following code is originally taken (with permission) from Mercurial _b85alphabet = (b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" b"abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~") _b85chars = None _b85chars2 = None _b85dec = None def b85encode(b, pad=False): """Encode bytes-like object b in base85 format and return a bytes object. If pad is true, the input is padded with b'\\0' so its length is a multiple of 4 bytes before encoding. """ global _b85chars, _b85chars2 # Delay the initialization of tables to not waste memory # if the function is never called if _b85chars is None: _b85chars = [bytes((i,)) for i in _b85alphabet] _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars] return _85encode(b, _b85chars, _b85chars2, pad) def b85decode(b): """Decode the base85-encoded bytes-like object or ASCII string b The result is returned as a bytes object. """ global _b85dec # Delay the initialization of tables to not waste memory # if the function is never called if _b85dec is None: _b85dec = [None] * 256 for i, c in enumerate(_b85alphabet): _b85dec[c] = i b = _bytes_from_decode_data(b) padding = (-len(b)) % 5 b = b + b'~' * padding out = [] packI = struct.Struct('!I').pack for i in range(0, len(b), 5): chunk = b[i:i + 5] acc = 0 try: for c in chunk: acc = acc * 85 + _b85dec[c] except TypeError: for j, c in enumerate(chunk): if _b85dec[c] is None: raise ValueError('bad base85 character at position %d' % (i + j)) from None raise try: out.append(packI(acc)) except struct.error: raise ValueError('base85 overflow in hunk starting at byte %d' % i) from None result = b''.join(out) if padding: result = result[:-padding] return result # Legacy interface. This code could be cleaned up since I don't believe # binascii has any line length limitations. It just doesn't seem worth it # though. The files should be opened in binary mode. MAXLINESIZE = 76 # Excluding the CRLF MAXBINSIZE = (MAXLINESIZE//4)*3 def encode(input, output): """Encode a file; input and output are binary files.""" while True: s = input.read(MAXBINSIZE) if not s: break while len(s) < MAXBINSIZE: ns = input.read(MAXBINSIZE-len(s)) if not ns: break s += ns line = binascii.b2a_base64(s) output.write(line) def decode(input, output): """Decode a file; input and output are binary files.""" while True: line = input.readline() if not line: break s = binascii.a2b_base64(line) output.write(s) def _input_type_check(s): try: m = memoryview(s) except TypeError as err: msg = "expected bytes-like object, not %s" % s.__class__.__name__ raise TypeError(msg) from err if m.format not in ('c', 'b', 'B'): msg = ("expected single byte elements, not %r from %s" % (m.format, s.__class__.__name__)) raise TypeError(msg) if m.ndim != 1: msg = ("expected 1-D data, not %d-D data from %s" % (m.ndim, s.__class__.__name__)) raise TypeError(msg) def encodebytes(s): """Encode a bytestring into a bytes object containing multiple lines of base-64 data.""" _input_type_check(s) pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return b"".join(pieces) def encodestring(s): """Legacy alias of encodebytes().""" import warnings warnings.warn("encodestring() is a deprecated alias since 3.1, " "use encodebytes()", DeprecationWarning, 2) return encodebytes(s) def decodebytes(s): """Decode a bytestring of base-64 data into a bytes object.""" _input_type_check(s) return binascii.a2b_base64(s) def decodestring(s): """Legacy alias of decodebytes().""" import warnings warnings.warn("decodestring() is a deprecated alias since Python 3.1, " "use decodebytes()", DeprecationWarning, 2) return decodebytes(s) # Usable as a script... def main(): """Small main program""" import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error as msg: sys.stdout = sys.stderr print(msg) print("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) sys.exit(2) func = encode for o, a in opts: if o == '-e': func = encode if o == '-d': func = decode if o == '-u': func = decode if o == '-t': test(); return if args and args[0] != '-': with open(args[0], 'rb') as f: func(f, sys.stdout.buffer) else: func(sys.stdin.buffer, sys.stdout.buffer) def test(): s0 = b"Aladdin:open sesame" print(repr(s0)) s1 = encodebytes(s0) print(repr(s1)) s2 = decodebytes(s1) print(repr(s2)) assert s0 == s2 if __name__ == '__main__': main()
20,380
596
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/macurl2path.py
"""Macintosh-specific module for conversion between pathnames and URLs. Do not import directly; use urllib instead.""" import urllib.parse import os __all__ = ["url2pathname","pathname2url"] def url2pathname(pathname): """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.""" # # XXXX The .. handling should be fixed... # tp = urllib.parse.splittype(pathname)[0] if tp and tp != 'file': raise RuntimeError('Cannot convert non-local URL to pathname') # Turn starting /// into /, an empty hostname means current host if pathname[:3] == '///': pathname = pathname[2:] elif pathname[:2] == '//': raise RuntimeError('Cannot convert non-local URL to pathname') components = pathname.split('/') # Remove . and embedded .. i = 0 while i < len(components): if components[i] == '.': del components[i] elif components[i] == '..' and i > 0 and \ components[i-1] not in ('', '..'): del components[i-1:i+1] i = i-1 elif components[i] == '' and i > 0 and components[i-1] != '': del components[i] else: i = i+1 if not components[0]: # Absolute unix path, don't start with colon rv = ':'.join(components[1:]) else: # relative unix path, start with colon. First replace # leading .. by empty strings (giving ::file) i = 0 while i < len(components) and components[i] == '..': components[i] = '' i = i + 1 rv = ':' + ':'.join(components) # and finally unquote slashes and other funny characters return urllib.parse.unquote(rv) def pathname2url(pathname): """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.""" if '/' in pathname: raise RuntimeError("Cannot convert pathname containing slashes") components = pathname.split(':') # Remove empty first and/or last component if components[0] == '': del components[0] if components[-1] == '': del components[-1] # Replace empty string ('::') by .. (will result in '/../' later) for i in range(len(components)): if components[i] == '': components[i] = '..' # Truncate names longer than 31 bytes components = map(_pncomp2url, components) if os.path.isabs(pathname): return '/' + '/'.join(components) else: return '/'.join(components) def _pncomp2url(component): # We want to quote slashes return urllib.parse.quote(component[:31], safe='')
2,732
78
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/chunk.py
"""Simple class to read IFF chunks. An IFF chunk (used in formats such as AIFF, TIFF, RMFF (RealMedia File Format)) has the following structure: +----------------+ | ID (4 bytes) | +----------------+ | size (4 bytes) | +----------------+ | data | | ... | +----------------+ The ID is a 4-byte string which identifies the type of chunk. The size field (a 32-bit value, encoded using big-endian byte order) gives the size of the whole chunk, including the 8-byte header. Usually an IFF-type file consists of one or more chunks. The proposed usage of the Chunk class defined here is to instantiate an instance at the start of each chunk and read from the instance until it reaches the end, after which a new instance can be instantiated. At the end of the file, creating a new instance will fail with an EOFError exception. Usage: while True: try: chunk = Chunk(file) except EOFError: break chunktype = chunk.getname() while True: data = chunk.read(nbytes) if not data: pass # do something with data The interface is file-like. The implemented methods are: read, close, seek, tell, isatty. Extra methods are: skip() (called by close, skips to the end of the chunk), getname() (returns the name (ID) of the chunk) The __init__ method has one required argument, a file-like object (including a chunk instance), and one optional argument, a flag which specifies whether or not chunks are aligned on 2-byte boundaries. The default is 1, i.e. aligned. """ class Chunk: def __init__(self, file, align=True, bigendian=True, inclheader=False): import struct self.closed = False self.align = align # whether to align to word (2-byte) boundaries if bigendian: strflag = '>' else: strflag = '<' self.file = file self.chunkname = file.read(4) if len(self.chunkname) < 4: raise EOFError try: self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0] except struct.error: raise EOFError if inclheader: self.chunksize = self.chunksize - 8 # subtract header self.size_read = 0 try: self.offset = self.file.tell() except (AttributeError, OSError): self.seekable = False else: self.seekable = True def getname(self): """Return the name (ID) of the current chunk.""" return self.chunkname def getsize(self): """Return the size of the current chunk.""" return self.chunksize def close(self): if not self.closed: try: self.skip() finally: self.closed = True def isatty(self): if self.closed: raise ValueError("I/O operation on closed file") return False def seek(self, pos, whence=0): """Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error. """ if self.closed: raise ValueError("I/O operation on closed file") if not self.seekable: raise OSError("cannot seek") if whence == 1: pos = pos + self.size_read elif whence == 2: pos = pos + self.chunksize if pos < 0 or pos > self.chunksize: raise RuntimeError self.file.seek(self.offset + pos, 0) self.size_read = pos def tell(self): if self.closed: raise ValueError("I/O operation on closed file") return self.size_read def read(self, size=-1): """Read at most size bytes from the chunk. If size is omitted or negative, read until the end of the chunk. """ if self.closed: raise ValueError("I/O operation on closed file") if self.size_read >= self.chunksize: return b'' if size < 0: size = self.chunksize - self.size_read if size > self.chunksize - self.size_read: size = self.chunksize - self.size_read data = self.file.read(size) self.size_read = self.size_read + len(data) if self.size_read == self.chunksize and \ self.align and \ (self.chunksize & 1): dummy = self.file.read(1) self.size_read = self.size_read + len(dummy) return data def skip(self): """Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. """ if self.closed: raise ValueError("I/O operation on closed file") if self.seekable: try: n = self.chunksize - self.size_read # maybe fix alignment if self.align and (self.chunksize & 1): n = n + 1 self.file.seek(n, 1) self.size_read = self.size_read + n return except OSError: pass while self.size_read < self.chunksize: n = min(8192, self.chunksize - self.size_read) dummy = self.read(n) if not dummy: raise EOFError
5,425
170
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/webbrowser.py
#! /usr/bin/env python3 """Interfaces for launching and remotely controlling Web browsers.""" # Maintained by Georg Brandl. import os import shlex import shutil import sys import subprocess __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] class Error(Exception): pass _browsers = {} # Dictionary of available browser controllers _tryorder = [] # Preference order of available browsers def register(name, klass, instance=None, update_tryorder=1): """Register a browser connector and, optionally, connection.""" _browsers[name.lower()] = [klass, instance] if update_tryorder > 0: _tryorder.append(name) elif update_tryorder < 0: _tryorder.insert(0, name) def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using is not None: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if '%s' in browser: # User gave us a command line, split it into name and args browser = shlex.split(browser) if browser[-1] == '&': return BackgroundBrowser(browser[:-1]) else: return GenericBrowser(browser) else: # User gave us a browser name or path. try: command = _browsers[browser.lower()] except KeyError: command = _synthesize(browser) if command[1] is not None: return command[1] elif command[0] is not None: return command[0]() raise Error("could not locate runnable browser") # Please note: the following definition hides a builtin function. # It is recommended one does "import webbrowser" and uses webbrowser.open(url) # instead of "from webbrowser import *". def open(url, new=0, autoraise=True): for name in _tryorder: browser = get(name) if browser.open(url, new, autoraise): return True return False def open_new(url): return open(url, 1) def open_new_tab(url): return open(url, 2) def _synthesize(browser, update_tryorder=1): """Attempt to synthesize a controller base on existing controllers. This is useful to create a controller when a user specifies a path to an entry in the BROWSER environment variable -- we can copy a general controller to operate using a specific installation of the desired browser in this way. If we can't create a controller in this way, or if there is no executable for the requested browser, return [None, None]. """ cmd = browser.split()[0] if not shutil.which(cmd): return [None, None] name = os.path.basename(cmd) try: command = _browsers[name.lower()] except KeyError: return [None, None] # now attempt to clone to fit the new name: controller = command[1] if controller and name.lower() == controller.basename: import copy controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller, update_tryorder) return [None, controller] return [None, None] # General parent classes class BaseBrowser(object): """Parent class for all browsers. Do not use directly.""" args = ['%s'] def __init__(self, name=""): self.name = name self.basename = name def open(self, url, new=0, autoraise=True): raise NotImplementedError def open_new(self, url): return self.open(url, 1) def open_new_tab(self, url): return self.open(url, 2) class GenericBrowser(BaseBrowser): """Class for all browsers started with a command and without remote functionality.""" def __init__(self, name): if isinstance(name, str): self.name = name self.args = ["%s"] else: # name should be a list with arguments self.name = name[0] self.args = name[1:] self.basename = os.path.basename(self.name) def open(self, url, new=0, autoraise=True): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] try: if sys.platform[:3] == 'win': p = subprocess.Popen(cmdline) else: p = subprocess.Popen(cmdline, close_fds=True) return not p.wait() except OSError: return False class BackgroundBrowser(GenericBrowser): """Class for all browsers which are to be started in the background.""" def open(self, url, new=0, autoraise=True): cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] try: if sys.platform[:3] == 'win': p = subprocess.Popen(cmdline) else: p = subprocess.Popen(cmdline, close_fds=True, start_new_session=True) return (p.poll() is None) except OSError: return False class UnixBrowser(BaseBrowser): """Parent class for all Unix browsers with remote functionality.""" raise_opts = None background = False redirect_stdout = True # In remote_args, %s will be replaced with the requested URL. %action will # be replaced depending on the value of 'new' passed to open. # remote_action is used for new=0 (open). If newwin is not None, it is # used for new=1 (open_new). If newtab is not None, it is used for # new=3 (open_new_tab). After both substitutions are made, any empty # strings in the transformed remote_args list will be removed. remote_args = ['%action', '%s'] remote_action = None remote_action_newwin = None remote_action_newtab = None def _invoke(self, args, remote, autoraise): raise_opt = [] if remote and self.raise_opts: # use autoraise argument only for remote invocation autoraise = int(autoraise) opt = self.raise_opts[autoraise] if opt: raise_opt = [opt] cmdline = [self.name] + raise_opt + args if remote or self.background: inout = subprocess.DEVNULL else: # for TTY browsers, we need stdin/out inout = None p = subprocess.Popen(cmdline, close_fds=True, stdin=inout, stdout=(self.redirect_stdout and inout or None), stderr=inout, start_new_session=True) if remote: # wait at most five seconds. If the subprocess is not finished, the # remote invocation has (hopefully) started a new instance. try: rc = p.wait(5) # if remote call failed, open() will try direct invocation return not rc except subprocess.TimeoutExpired: return True elif self.background: if p.poll() is None: return True else: return False else: return not p.wait() def open(self, url, new=0, autoraise=True): if new == 0: action = self.remote_action elif new == 1: action = self.remote_action_newwin elif new == 2: if self.remote_action_newtab is None: action = self.remote_action_newwin else: action = self.remote_action_newtab else: raise Error("Bad 'new' parameter to open(); " + "expected 0, 1, or 2, got %s" % new) args = [arg.replace("%s", url).replace("%action", action) for arg in self.remote_args] args = [arg for arg in args if arg] success = self._invoke(args, True, autoraise) if not success: # remote invocation failed, try straight way args = [arg.replace("%s", url) for arg in self.args] return self._invoke(args, False, False) else: return True class Mozilla(UnixBrowser): """Launcher class for Mozilla browsers.""" remote_args = ['%action', '%s'] remote_action = "" remote_action_newwin = "-new-window" remote_action_newtab = "-new-tab" background = True class Netscape(UnixBrowser): """Launcher class for Netscape browser.""" raise_opts = ["-noraise", "-raise"] remote_args = ['-remote', 'openURL(%s%action)'] remote_action = "" remote_action_newwin = ",new-window" remote_action_newtab = ",new-tab" background = True class Galeon(UnixBrowser): """Launcher class for Galeon/Epiphany browsers.""" raise_opts = ["-noraise", ""] remote_args = ['%action', '%s'] remote_action = "-n" remote_action_newwin = "-w" background = True class Chrome(UnixBrowser): "Launcher class for Google Chrome browser." remote_args = ['%action', '%s'] remote_action = "" remote_action_newwin = "--new-window" remote_action_newtab = "" background = True Chromium = Chrome class Opera(UnixBrowser): "Launcher class for Opera browser." remote_args = ['%action', '%s'] remote_action = "" remote_action_newwin = "--new-window" remote_action_newtab = "" background = True class Elinks(UnixBrowser): "Launcher class for Elinks browsers." remote_args = ['-remote', 'openURL(%s%action)'] remote_action = "" remote_action_newwin = ",new-window" remote_action_newtab = ",new-tab" background = False # elinks doesn't like its stdout to be redirected - # it uses redirected stdout as a signal to do -dump redirect_stdout = False class Konqueror(BaseBrowser): """Controller for the KDE File Manager (kfm, or Konqueror). See the output of ``kfmclient --commands`` for more information on the Konqueror remote-control interface. """ def open(self, url, new=0, autoraise=True): # XXX Currently I know no way to prevent KFM from opening a new win. if new == 2: action = "newTab" else: action = "openURL" devnull = subprocess.DEVNULL try: p = subprocess.Popen(["kfmclient", action, url], close_fds=True, stdin=devnull, stdout=devnull, stderr=devnull) except OSError: # fall through to next variant pass else: p.wait() # kfmclient's return code unfortunately has no meaning as it seems return True try: p = subprocess.Popen(["konqueror", "--silent", url], close_fds=True, stdin=devnull, stdout=devnull, stderr=devnull, start_new_session=True) except OSError: # fall through to next variant pass else: if p.poll() is None: # Should be running now. return True try: p = subprocess.Popen(["kfm", "-d", url], close_fds=True, stdin=devnull, stdout=devnull, stderr=devnull, start_new_session=True) except OSError: return False else: return (p.poll() is None) class Grail(BaseBrowser): # There should be a way to maintain a connection to Grail, but the # Grail remote control protocol doesn't really allow that at this # point. It probably never will! def _find_grail_rc(self): import glob import pwd import socket import tempfile tempdir = os.path.join(tempfile.gettempdir(), ".grail-unix") user = pwd.getpwuid(os.getuid())[0] filename = os.path.join(tempdir, user + "-*") maybes = glob.glob(filename) if not maybes: return None s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for fn in maybes: # need to PING each one until we find one that's live try: s.connect(fn) except OSError: # no good; attempt to clean it out, but don't fail: try: os.unlink(fn) except OSError: pass else: return s def _remote(self, action): s = self._find_grail_rc() if not s: return 0 s.send(action) s.close() return 1 def open(self, url, new=0, autoraise=True): if new: ok = self._remote("LOADNEW " + url) else: ok = self._remote("LOAD " + url) return ok # # Platform support for Unix # # These are the right tests because all these Unix browsers require either # a console terminal or an X display to run. def register_X_browsers(): # use xdg-open if around if shutil.which("xdg-open"): register("xdg-open", None, BackgroundBrowser("xdg-open")) # The default GNOME3 browser if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gvfs-open"): register("gvfs-open", None, BackgroundBrowser("gvfs-open")) # The default GNOME browser if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gnome-open"): register("gnome-open", None, BackgroundBrowser("gnome-open")) # The default KDE browser if "KDE_FULL_SESSION" in os.environ and shutil.which("kfmclient"): register("kfmclient", Konqueror, Konqueror("kfmclient")) if shutil.which("x-www-browser"): register("x-www-browser", None, BackgroundBrowser("x-www-browser")) # The Mozilla browsers for browser in ("firefox", "iceweasel", "iceape", "seamonkey"): if shutil.which(browser): register(browser, None, Mozilla(browser)) # The Netscape and old Mozilla browsers for browser in ("mozilla-firefox", "mozilla-firebird", "firebird", "mozilla", "netscape"): if shutil.which(browser): register(browser, None, Netscape(browser)) # Konqueror/kfm, the KDE browser. if shutil.which("kfm"): register("kfm", Konqueror, Konqueror("kfm")) elif shutil.which("konqueror"): register("konqueror", Konqueror, Konqueror("konqueror")) # Gnome's Galeon and Epiphany for browser in ("galeon", "epiphany"): if shutil.which(browser): register(browser, None, Galeon(browser)) # Skipstone, another Gtk/Mozilla based browser if shutil.which("skipstone"): register("skipstone", None, BackgroundBrowser("skipstone")) # Google Chrome/Chromium browsers for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"): if shutil.which(browser): register(browser, None, Chrome(browser)) # Opera, quite popular if shutil.which("opera"): register("opera", None, Opera("opera")) # Next, Mosaic -- old but still in use. if shutil.which("mosaic"): register("mosaic", None, BackgroundBrowser("mosaic")) # Grail, the Python browser. Does anybody still use it? if shutil.which("grail"): register("grail", Grail, None) # Prefer X browsers if present if os.environ.get("DISPLAY"): register_X_browsers() # Also try console browsers if os.environ.get("TERM"): if shutil.which("www-browser"): register("www-browser", None, GenericBrowser("www-browser")) # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/> if shutil.which("links"): register("links", None, GenericBrowser("links")) if shutil.which("elinks"): register("elinks", None, Elinks("elinks")) # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/> if shutil.which("lynx"): register("lynx", None, GenericBrowser("lynx")) # The w3m browser <http://w3m.sourceforge.net/> if shutil.which("w3m"): register("w3m", None, GenericBrowser("w3m")) # # Platform support for Windows # if sys.platform[:3] == "win": class WindowsDefault(BaseBrowser): def open(self, url, new=0, autoraise=True): try: os.startfile(url) except OSError: # [Error 22] No application is associated with the specified # file for this operation: '<URL>' return False else: return True _tryorder = [] _browsers = {} # First try to use the default Windows browser register("windows-default", WindowsDefault) # Detect some common Windows browsers, fallback to IE iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"), "Internet Explorer\\IEXPLORE.EXE") for browser in ("firefox", "firebird", "seamonkey", "mozilla", "netscape", "opera", iexplore): if shutil.which(browser): register(browser, None, BackgroundBrowser(browser)) # # Platform support for MacOS # if sys.platform == 'darwin': # Adapted from patch submitted to SourceForge by Steven J. Burr class MacOSX(BaseBrowser): """Launcher class for Aqua browsers on Mac OS X Optionally specify a browser name on instantiation. Note that this will not work for Aqua browsers if the user has moved the application package after installation. If no browser is specified, the default browser, as specified in the Internet System Preferences panel, will be used. """ def __init__(self, name): self.name = name def open(self, url, new=0, autoraise=True): assert "'" not in url # hack for local urls if not ':' in url: url = 'file:'+url # new must be 0 or 1 new = int(bool(new)) if self.name == "default": # User called open, open_new or get without a browser parameter script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser else: # User called get and chose a browser if self.name == "OmniWeb": toWindow = "" else: # Include toWindow parameter of OpenURL command for browsers # that support it. 0 == new window; -1 == existing toWindow = "toWindow %d" % (new - 1) cmd = 'OpenURL "%s"' % url.replace('"', '%22') script = '''tell application "%s" activate %s %s end tell''' % (self.name, cmd, toWindow) # Open pipe to AppleScript through osascript command osapipe = os.popen("osascript", "w") if osapipe is None: return False # Write script to osascript's stdin osapipe.write(script) rc = osapipe.close() return not rc class MacOSXOSAScript(BaseBrowser): def __init__(self, name): self._name = name def open(self, url, new=0, autoraise=True): if self._name == 'default': script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser else: script = ''' tell application "%s" activate open location "%s" end '''%(self._name, url.replace('"', '%22')) osapipe = os.popen("osascript", "w") if osapipe is None: return False osapipe.write(script) rc = osapipe.close() return not rc # Don't clear _tryorder or _browsers since OS X can use above Unix support # (but we prefer using the OS X specific stuff) register("safari", None, MacOSXOSAScript('safari'), -1) register("firefox", None, MacOSXOSAScript('firefox'), -1) register("chrome", None, MacOSXOSAScript('chrome'), -1) register("MacOSX", None, MacOSXOSAScript('default'), -1) # OK, now that we know what the default preference orders for each # platform are, allow user to override them with the BROWSER variable. if "BROWSER" in os.environ: _userchoices = os.environ["BROWSER"].split(os.pathsep) _userchoices.reverse() # Treat choices in same way as if passed into get() but do register # and prepend to _tryorder for cmdline in _userchoices: if cmdline != '': cmd = _synthesize(cmdline, -1) if cmd[1] is None: register(cmdline, None, GenericBrowser(cmdline), -1) cmdline = None # to make del work if _userchoices was empty del cmdline del _userchoices # what to do if _tryorder is now empty? def main(): import getopt usage = """Usage: %s [-n | -t] url -n: open new window -t: open new tab""" % sys.argv[0] try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') except getopt.error as msg: print(msg, file=sys.stderr) print(usage, file=sys.stderr) sys.exit(1) new_win = 0 for o, a in opts: if o == '-n': new_win = 1 elif o == '-t': new_win = 2 if len(args) != 1: print(usage, file=sys.stderr) sys.exit(1) url = args[0] open(url, new_win) print("\a") if __name__ == "__main__": main()
21,759
664
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/crypt.py
"""Wrapper to the POSIX crypt library call and associated functionality.""" import _crypt import string as _string from random import SystemRandom as _SystemRandom from collections import namedtuple as _namedtuple _saltchars = _string.ascii_letters + _string.digits + './' _sr = _SystemRandom() class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')): """Class representing a salt method per the Modular Crypt Format or the legacy 2-character crypt method.""" def __repr__(self): return '<crypt.METHOD_{}>'.format(self.name) def mksalt(method=None): """Generate a salt for the specified method. If not specified, the strongest available method will be used. """ if method is None: method = methods[0] s = '${}$'.format(method.ident) if method.ident else '' s += ''.join(_sr.choice(_saltchars) for char in range(method.salt_chars)) return s def crypt(word, salt=None): """Return a string representing the one-way hash of a password, with a salt prepended. If ``salt`` is not specified or is ``None``, the strongest available method will be selected and a salt generated. Otherwise, ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as returned by ``crypt.mksalt()``. """ if salt is None or isinstance(salt, _Method): salt = mksalt(salt) return _crypt.crypt(word, salt) # available salting/crypto methods METHOD_CRYPT = _Method('CRYPT', None, 2, 13) METHOD_MD5 = _Method('MD5', '1', 8, 34) METHOD_SHA256 = _Method('SHA256', '5', 16, 63) METHOD_SHA512 = _Method('SHA512', '6', 16, 106) methods = [] for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5, METHOD_CRYPT): _result = crypt('', _method) if _result and len(_result) == _method.total_size: methods.append(_method) del _result, _method
1,864
62
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/subprocess.py
# subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # Copyright (c) 2003-2005 by Peter Astrand <[email protected]> # # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. r"""Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. For a complete description of this module see the Python documentation. Main API ======== run(...): Runs a command, waits for it to complete, then returns a CompletedProcess instance. Popen(...): A class for flexibly executing a command in a new process Constants --------- DEVNULL: Special value that indicates that os.devnull should be used PIPE: Special value that indicates a pipe should be created STDOUT: Special value that indicates that stderr should go to stdout Older API ========= call(...): Runs a command, waits for it to complete, then returns the return code. check_call(...): Same as call() but raises CalledProcessError() if return code is not 0 check_output(...): Same as check_call() but returns the contents of stdout instead of a return code getoutput(...): Runs a command in the shell, waits for it to complete, then returns the output getstatusoutput(...): Runs a command in the shell, waits for it to complete, then returns a (exitcode, output) tuple """ import sys _mswindows = (sys.platform == "win32") import io import os import time import signal import builtins import warnings import errno from time import monotonic as _time # Exception classes used by this module. class SubprocessError(Exception): pass class CalledProcessError(SubprocessError): """Raised when run() is called with check=True and the process returns a non-zero exit status. Attributes: cmd, returncode, stdout, stderr, output """ def __init__(self, returncode, cmd, output=None, stderr=None): self.returncode = returncode self.cmd = cmd self.output = output self.stderr = stderr def __str__(self): if self.returncode and self.returncode < 0: try: return "Command '%s' died with %r." % ( self.cmd, signal.Signals(-self.returncode)) except ValueError: return "Command '%s' died with unknown signal %d." % ( self.cmd, -self.returncode) else: return "Command '%s' returned non-zero exit status %d." % ( self.cmd, self.returncode) @property def stdout(self): """Alias for output attribute, to match stderr""" return self.output @stdout.setter def stdout(self, value): # There's no obvious reason to set this, but allow it anyway so # .stdout is a transparent alias for .output self.output = value class TimeoutExpired(SubprocessError): """This exception is raised when the timeout expires while waiting for a child process. Attributes: cmd, output, stdout, stderr, timeout """ def __init__(self, cmd, timeout, output=None, stderr=None): self.cmd = cmd self.timeout = timeout self.output = output self.stderr = stderr def __str__(self): return ("Command '%s' timed out after %s seconds" % (self.cmd, self.timeout)) @property def stdout(self): return self.output @stdout.setter def stdout(self, value): # There's no obvious reason to set this, but allow it anyway so # .stdout is a transparent alias for .output self.output = value if _mswindows: import threading import msvcrt import _winapi class STARTUPINFO: dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None wShowWindow = 0 else: import _posixsubprocess import select import selectors try: import threading except ImportError: import dummy_threading as threading # When select or poll has indicated that the file is writable, # we can write up to _PIPE_BUF bytes without risk of blocking. # POSIX defines PIPE_BUF as >= 512. _PIPE_BUF = getattr(select, 'PIPE_BUF', 512) # poll/select have the advantage of not requiring any extra file # descriptor, contrarily to epoll/kqueue (also, they require a single # syscall). if hasattr(selectors, 'PollSelector'): _PopenSelector = selectors.PollSelector else: _PopenSelector = selectors.SelectSelector __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput", "getoutput", "check_output", "run", "CalledProcessError", "DEVNULL", "SubprocessError", "TimeoutExpired", "CompletedProcess"] # NOTE: We intentionally exclude list2cmdline as it is # considered an internal implementation detail. issue10838. # if _mswindows: # from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, # STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, # STD_ERROR_HANDLE, SW_HIDE, # STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW) # __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP", # "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE", # "STD_ERROR_HANDLE", "SW_HIDE", # "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW", # "STARTUPINFO"]) # class Handle(int): # closed = False # def Close(self, CloseHandle=_winapi.CloseHandle): # if not self.closed: # self.closed = True # CloseHandle(self) # def Detach(self): # if not self.closed: # self.closed = True # return int(self) # raise ValueError("already closed") # def __repr__(self): # return "%s(%d)" % (self.__class__.__name__, int(self)) # __del__ = Close # __str__ = __repr__ # This lists holds Popen instances for which the underlying process had not # exited at the time its __del__ method got called: those processes are wait()ed # for synchronously from _cleanup() when a new Popen object is created, to avoid # zombie processes. _active = [] def _cleanup(): for inst in _active[:]: res = inst._internal_poll(_deadstate=sys.maxsize) if res is not None: try: _active.remove(inst) except ValueError: # This can happen if two threads create a new Popen instance. # It's harmless that it was already removed, so ignore. pass PIPE = -1 STDOUT = -2 DEVNULL = -3 # XXX This function is only used by multiprocessing and the test suite, # but it's here so that it can be imported when Python is compiled without # threads. def _optim_args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current optimization settings in sys.flags.""" args = [] value = sys.flags.optimize if value > 0: args.append('-' + 'O' * value) return args def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags, sys.warnoptions and sys._xoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'dont_write_bytecode': 'B', 'no_site': 'S', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', # -O is handled in _optim_args_from_interpreter_flags() } args = _optim_args_from_interpreter_flags() for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) if sys.flags.isolated: args.append('-I') else: if sys.flags.ignore_environment: args.append('-E') if sys.flags.no_user_site: args.append('-s') for opt in sys.warnoptions: args.append('-W' + opt) # -X options xoptions = getattr(sys, '_xoptions', {}) for opt in ('faulthandler', 'showalloccount', 'showrefcount', 'utf8'): if opt in xoptions: value = xoptions[opt] if value is True: arg = opt else: arg = '%s=%s' % (opt, value) args.extend(('-X', arg)) return args def call(*popenargs, timeout=None, **kwargs): """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: p.kill() p.wait() raise def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the call function. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0 def check_output(*popenargs, timeout=None, **kwargs): r"""Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) b'ls: non_existent_file: No such file or directory\n' There is an additional optional argument, "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it too will be used internally. Example: >>> check_output(["sed", "-e", "s/foo/bar/"], ... input=b"when in the course of fooman events\n") b'when in the course of barman events\n' If universal_newlines=True is passed, the "input" argument must be a string and the return value will be a string rather than bytes. """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') if 'input' in kwargs and kwargs['input'] is None: # Explicitly passing input=None was previously equivalent to passing an # empty string. That is maintained here for backwards compatibility. kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b'' return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, **kwargs).stdout class CompletedProcess(object): """A process that has finished running. This is returned by run(). Attributes: args: The list or str args passed to run(). returncode: The exit code of the process, negative for signals. stdout: The standard output (None if not captured). stderr: The standard error (None if not captured). """ def __init__(self, args, returncode, stdout=None, stderr=None): self.args = args self.returncode = returncode self.stdout = stdout self.stderr = stderr def __repr__(self): args = ['args={!r}'.format(self.args), 'returncode={!r}'.format(self.returncode)] if self.stdout is not None: args.append('stdout={!r}'.format(self.stdout)) if self.stderr is not None: args.append('stderr={!r}'.format(self.stderr)) return "{}({})".format(type(self).__name__, ', '.join(args)) def check_returncode(self): """Raise CalledProcessError if the exit code is non-zero.""" if self.returncode: raise CalledProcessError(self.returncode, self.args, self.stdout, self.stderr) def run(*popenargs, input=None, timeout=None, check=False, **kwargs): """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. If check is True and the exit code was non-zero, it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute, and output & stderr attributes if those streams were captured. If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised. There is an optional argument "input", allowing you to pass a string to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's "stdin" argument, as it will be used internally. The other arguments are the same as for the Popen constructor. If universal_newlines=True is passed, the "input" argument must be a string and stdout/stderr in the returned object will be strings rather than bytes. """ if input is not None: if 'stdin' in kwargs: raise ValueError('stdin and input arguments may not both be used.') kwargs['stdin'] = PIPE with Popen(*popenargs, **kwargs) as process: try: stdout, stderr = process.communicate(input, timeout=timeout) except TimeoutExpired: process.kill() stdout, stderr = process.communicate() raise TimeoutExpired(process.args, timeout, output=stdout, stderr=stderr) except: process.kill() process.wait() raise retcode = process.poll() if check and retcode: raise CalledProcessError(retcode, process.args, output=stdout, stderr=stderr) return CompletedProcess(process.args, retcode, stdout, stderr) def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. """ # See # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx # or search http://msdn.microsoft.com for # "Parsing C++ Command-Line Arguments" result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) or not arg if needquote: result.append('"') for c in arg: if c == '\\': # Don't know if we need to double yet. bs_buf.append(c) elif c == '"': # Double backslashes. result.append('\\' * len(bs_buf)*2) bs_buf = [] result.append('\\"') else: # Normal char if bs_buf: result.extend(bs_buf) bs_buf = [] result.append(c) # Add remaining backslashes, if any. if bs_buf: result.extend(bs_buf) if needquote: result.extend(bs_buf) result.append('"') return ''.join(result) # Various tools for executing commands and looking at their output and status. # def getstatusoutput(cmd): """Return (exitcode, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). The locale encoding is used to decode the output and process newlines. A trailing newline is stripped from the output. The exit status for the command can be interpreted according to the rules for the function 'wait'. Example: >>> import subprocess >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (127, 'sh: /bin/junk: not found') >>> subprocess.getstatusoutput('/bin/kill $$') (-15, '') """ try: data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT) exitcode = 0 except CalledProcessError as ex: data = ex.output exitcode = ex.returncode if data[-1:] == '\n': data = data[:-1] return exitcode, data def getoutput(cmd): """Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: >>> import subprocess >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' """ return getstatusoutput(cmd)[1] _PLATFORM_DEFAULT_CLOSE_FDS = object() class Popen(object): """ Execute a child program in a new process. For a complete description of the arguments see the Python documentation. Arguments: args: A string, or a sequence of program arguments. bufsize: supplied as the buffering argument to the open() function when creating the stdin/stdout/stderr pipe file objects executable: A replacement program to execute. stdin, stdout and stderr: These specify the executed programs' standard input, standard output and standard error file handles, respectively. preexec_fn: (POSIX only) An object to be called in the child process just before the child is executed. close_fds: Controls closing or inheriting of file descriptors. shell: If true, the command will be executed through the shell. cwd: Sets the current directory before the child is executed. env: Defines the environment variables for the new process. universal_newlines: If true, use universal line endings for file objects stdin, stdout and stderr. startupinfo and creationflags (Windows only) restore_signals (POSIX only) start_new_session (POSIX only) pass_fds (POSIX only) encoding and errors: Text mode encoding and error handling to use for file objects stdin, stdout and stderr. Attributes: stdin, stdout, stderr, pid, returncode """ _child_created = False # Set here since __del__ checks it def __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None): """Create new Popen instance.""" _cleanup() # Held while anything is calling waitpid before returncode has been # updated to prevent clobbering returncode if wait() or poll() are # called from multiple threads at once. After acquiring the lock, # code must re-check self.returncode to see if another thread just # finished a waitpid() call. self._waitpid_lock = threading.Lock() self._input = None self._communication_started = False if bufsize is None: bufsize = -1 # Restore default if not isinstance(bufsize, int): raise TypeError("bufsize must be an integer") if _mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") any_stdio_set = (stdin is not None or stdout is not None or stderr is not None) if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: if any_stdio_set: close_fds = False else: close_fds = True elif close_fds and any_stdio_set: raise ValueError( "close_fds is not supported on Windows platforms" " if you redirect stdin/stdout/stderr") else: # POSIX if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: close_fds = True if pass_fds and not close_fds: warnings.warn("pass_fds overriding close_fds.", RuntimeWarning) close_fds = True if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") self.args = args self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines self.encoding = encoding self.errors = errors # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are -1 when not using PIPEs. The child objects are -1 # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) # We wrap OS handles *before* launching the child, otherwise a # quickly terminating child could make our fds unwrappable # (see #8458). if _mswindows: if p2cwrite != -1: p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) if c2pread != -1: c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) if errread != -1: errread = msvcrt.open_osfhandle(errread.Detach(), 0) text_mode = encoding or errors or universal_newlines self._closed_child_pipe_fds = False try: if p2cwrite != -1: self.stdin = io.open(p2cwrite, 'wb', bufsize) if text_mode: self.stdin = io.TextIOWrapper(self.stdin, write_through=True, line_buffering=(bufsize == 1), encoding=encoding, errors=errors) if c2pread != -1: self.stdout = io.open(c2pread, 'rb', bufsize) if text_mode: self.stdout = io.TextIOWrapper(self.stdout, encoding=encoding, errors=errors) if errread != -1: self.stderr = io.open(errread, 'rb', bufsize) if text_mode: self.stderr = io.TextIOWrapper(self.stderr, encoding=encoding, errors=errors) self._execute_child(args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session) except: # Cleanup if the child failed starting. for f in filter(None, (self.stdin, self.stdout, self.stderr)): try: f.close() except OSError: pass # Ignore EBADF or other errors. if not self._closed_child_pipe_fds: to_close = [] if stdin == PIPE: to_close.append(p2cread) if stdout == PIPE: to_close.append(c2pwrite) if stderr == PIPE: to_close.append(errwrite) if hasattr(self, '_devnull'): to_close.append(self._devnull) for fd in to_close: try: if _mswindows and isinstance(fd, Handle): fd.Close() else: os.close(fd) except OSError: pass raise def _translate_newlines(self, data, encoding, errors): data = data.decode(encoding, errors) return data.replace("\r\n", "\n").replace("\r", "\n") def __enter__(self): return self def __exit__(self, type, value, traceback): if self.stdout: self.stdout.close() if self.stderr: self.stderr.close() try: # Flushing a BufferedWriter may raise an error if self.stdin: self.stdin.close() finally: # Wait for the process to terminate, to avoid zombies. self.wait() def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn): if not self._child_created: # We didn't get to successfully create a child process. return if self.returncode is None: # Not reading subprocess exit status creates a zombi process which # is only destroyed at the parent python process exit _warn("subprocess %s is still running" % self.pid, ResourceWarning, source=self) # In case the child hasn't been waited on, check if it's done. self._internal_poll(_deadstate=_maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) def _get_devnull(self): if not hasattr(self, '_devnull'): self._devnull = os.open(os.devnull, os.O_RDWR) return self._devnull def _stdin_write(self, input): if input: try: self.stdin.write(input) except BrokenPipeError: pass # communicate() must ignore broken pipe errors. except OSError as exc: if exc.errno == errno.EINVAL: # bpo-19612, bpo-30418: On Windows, stdin.write() fails # with EINVAL if the child process exited or if the child # process is still running but closed the pipe. pass else: raise try: self.stdin.close() except BrokenPipeError: pass # communicate() must ignore broken pipe errors. except OSError as exc: if exc.errno == errno.EINVAL: pass else: raise def communicate(self, input=None, timeout=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional "input" argument should be data to be sent to the child process (if self.universal_newlines is True, this should be a string; if it is False, "input" should be bytes), or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). These will be bytes or, if self.universal_newlines was True, a string. """ if self._communication_started and input: raise ValueError("Cannot send input after starting communication") # Optimization: If we are not worried about timeouts, we haven't # started communicating, and we have one or zero pipes, using select() # or threads is unnecessary. if (timeout is None and not self._communication_started and [self.stdin, self.stdout, self.stderr].count(None) >= 2): stdout = None stderr = None if self.stdin: self._stdin_write(input) elif self.stdout: stdout = self.stdout.read() self.stdout.close() elif self.stderr: stderr = self.stderr.read() self.stderr.close() self.wait() else: if timeout is not None: endtime = _time() + timeout else: endtime = None try: stdout, stderr = self._communicate(input, endtime, timeout) finally: self._communication_started = True sts = self.wait(timeout=self._remaining_time(endtime)) return (stdout, stderr) def poll(self): """Check if child process has terminated. Set and return returncode attribute.""" return self._internal_poll() def _remaining_time(self, endtime): """Convenience for _communicate when computing timeouts.""" if endtime is None: return None else: return endtime - _time() def _check_timeout(self, endtime, orig_timeout): """Convenience for checking if a timeout has expired.""" if endtime is None: return if _time() > endtime: raise TimeoutExpired(self.args, orig_timeout) if _mswindows: # # Windows methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (-1, -1, -1, -1, -1, -1) p2cread, p2cwrite = -1, -1 c2pread, c2pwrite = -1, -1 errread, errwrite = -1, -1 if stdin is None: p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE) if p2cread is None: p2cread, _ = _winapi.CreatePipe(None, 0) p2cread = Handle(p2cread) _winapi.CloseHandle(_) elif stdin == PIPE: p2cread, p2cwrite = _winapi.CreatePipe(None, 0) p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) elif stdin == DEVNULL: p2cread = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stdin, int): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout is None: c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE) if c2pwrite is None: _, c2pwrite = _winapi.CreatePipe(None, 0) c2pwrite = Handle(c2pwrite) _winapi.CloseHandle(_) elif stdout == PIPE: c2pread, c2pwrite = _winapi.CreatePipe(None, 0) c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) elif stdout == DEVNULL: c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stdout, int): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE) if errwrite is None: _, errwrite = _winapi.CreatePipe(None, 0) errwrite = Handle(errwrite) _winapi.CloseHandle(_) elif stderr == PIPE: errread, errwrite = _winapi.CreatePipe(None, 0) errread, errwrite = Handle(errread), Handle(errwrite) elif stderr == STDOUT: errwrite = c2pwrite elif stderr == DEVNULL: errwrite = msvcrt.get_osfhandle(self._get_devnull()) elif isinstance(stderr, int): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" h = _winapi.DuplicateHandle( _winapi.GetCurrentProcess(), handle, _winapi.GetCurrentProcess(), 0, 1, _winapi.DUPLICATE_SAME_ACCESS) return Handle(h) def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session): """Execute program (MS Windows version)""" assert not pass_fds, "pass_fds not supported on Windows." if not isinstance(args, str): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() if -1 not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW startupinfo.wShowWindow = _winapi.SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = '{} /c "{}"'.format (comspec, args) # Start the process try: hp, ht, pid, tid = _winapi.CreateProcess(executable, args, # no special security None, None, int(not close_fds), creationflags, env, os.fspath(cwd) if cwd is not None else None, startupinfo) finally: # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread != -1: p2cread.Close() if c2pwrite != -1: c2pwrite.Close() if errwrite != -1: errwrite.Close() if hasattr(self, '_devnull'): os.close(self._devnull) # Prevent a double close of these handles/fds from __init__ # on error. self._closed_child_pipe_fds = True # Retain the process handle, but close the thread handle self._child_created = True self._handle = Handle(hp) self.pid = pid _winapi.CloseHandle(ht) def _internal_poll(self, _deadstate=None, _WaitForSingleObject=_winapi.WaitForSingleObject, _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0, _GetExitCodeProcess=_winapi.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it can only refer to objects in its local scope. """ if self.returncode is None: if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: self.returncode = _GetExitCodeProcess(self._handle) return self.returncode def wait(self, timeout=None, endtime=None): """Wait for child process to terminate. Returns returncode attribute.""" if endtime is not None: warnings.warn( "'endtime' argument is deprecated; use 'timeout'.", DeprecationWarning, stacklevel=2) timeout = self._remaining_time(endtime) if timeout is None: timeout_millis = _winapi.INFINITE else: timeout_millis = int(timeout * 1000) if self.returncode is None: result = _winapi.WaitForSingleObject(self._handle, timeout_millis) if result == _winapi.WAIT_TIMEOUT: raise TimeoutExpired(self.args, timeout) self.returncode = _winapi.GetExitCodeProcess(self._handle) return self.returncode def _readerthread(self, fh, buffer): buffer.append(fh.read()) fh.close() def _communicate(self, input, endtime, orig_timeout): # Start reader threads feeding into a list hanging off of this # object, unless they've already been started. if self.stdout and not hasattr(self, "_stdout_buff"): self._stdout_buff = [] self.stdout_thread = \ threading.Thread(target=self._readerthread, args=(self.stdout, self._stdout_buff)) self.stdout_thread.daemon = True self.stdout_thread.start() if self.stderr and not hasattr(self, "_stderr_buff"): self._stderr_buff = [] self.stderr_thread = \ threading.Thread(target=self._readerthread, args=(self.stderr, self._stderr_buff)) self.stderr_thread.daemon = True self.stderr_thread.start() if self.stdin: self._stdin_write(input) # Wait for the reader threads, or time out. If we time out, the # threads remain reading and the fds left open in case the user # calls communicate again. if self.stdout is not None: self.stdout_thread.join(self._remaining_time(endtime)) if self.stdout_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) if self.stderr is not None: self.stderr_thread.join(self._remaining_time(endtime)) if self.stderr_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) # Collect the output from and close both pipes, now that we know # both have been read successfully. stdout = None stderr = None if self.stdout: stdout = self._stdout_buff self.stdout.close() if self.stderr: stderr = self._stderr_buff self.stderr.close() # All data exchanged. Translate lists into strings. if stdout is not None: stdout = stdout[0] if stderr is not None: stderr = stderr[0] return (stdout, stderr) def send_signal(self, sig): """Send a signal to the process.""" # Don't signal a process that we know has already died. if self.returncode is not None: return if sig == signal.SIGTERM: self.terminate() elif sig == signal.CTRL_C_EVENT: os.kill(self.pid, signal.CTRL_C_EVENT) elif sig == signal.CTRL_BREAK_EVENT: os.kill(self.pid, signal.CTRL_BREAK_EVENT) else: raise ValueError("Unsupported signal: {}".format(sig)) def terminate(self): """Terminates the process.""" # Don't terminate a process that we know has already died. if self.returncode is not None: return try: _winapi.TerminateProcess(self._handle, 1) except PermissionError: # ERROR_ACCESS_DENIED (winerror 5) is received when the # process already died. rc = _winapi.GetExitCodeProcess(self._handle) if rc == _winapi.STILL_ACTIVE: raise self.returncode = rc kill = terminate else: # # POSIX methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = -1, -1 c2pread, c2pwrite = -1, -1 errread, errwrite = -1, -1 if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() elif stdin == DEVNULL: p2cread = self._get_devnull() elif isinstance(stdin, int): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() elif stdout == DEVNULL: c2pwrite = self._get_devnull() elif isinstance(stdout, int): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = os.pipe() elif stderr == STDOUT: if c2pwrite != -1: errwrite = c2pwrite else: # child's stdout is not set, use parent's stdout errwrite = sys.__stdout__.fileno() elif stderr == DEVNULL: errwrite = self._get_devnull() elif isinstance(stderr, int): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session): """Execute program (POSIX version)""" if isinstance(args, (str, bytes)): args = [args] else: args = list(args) if shell: args = ["/bin/sh", "-c"] + args if executable: args[0] = executable if executable is None: executable = args[0] orig_executable = executable # For transferring possible exec failure from child to parent. # Data format: "exception name:hex errno:description" # Pickle is not used; it is complex and involves memory allocation. errpipe_read, errpipe_write = os.pipe() # errpipe_write must not be in the standard io 0, 1, or 2 fd range. low_fds_to_close = [] while errpipe_write < 3: low_fds_to_close.append(errpipe_write) errpipe_write = os.dup(errpipe_write) for low_fd in low_fds_to_close: os.close(low_fd) try: try: # We must avoid complex work that could involve # malloc or free in the child process to avoid # potential deadlocks, thus we do all this here. # and pass it to fork_exec() if env is not None: env_list = [] for k, v in env.items(): k = os.fsencode(k) if b'=' in k: raise ValueError("illegal environment variable name") env_list.append(k + b'=' + os.fsencode(v)) else: env_list = None # Use execv instead of execve. executable = os.fsencode(executable) if os.path.dirname(executable): executable_list = (executable,) else: # This matches the behavior of os._execvpe(). executable_list = tuple( os.path.join(os.fsencode(dir), executable) for dir in os.get_exec_path(env)) fds_to_keep = set(pass_fds) fds_to_keep.add(errpipe_write) self.pid = _posixsubprocess.fork_exec( args, executable_list, close_fds, tuple(sorted(map(int, fds_to_keep))), cwd, env_list, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, errpipe_read, errpipe_write, restore_signals, start_new_session, preexec_fn) self._child_created = True finally: # be sure the FD is closed no matter what os.close(errpipe_write) # self._devnull is not always defined. devnull_fd = getattr(self, '_devnull', None) if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd: os.close(p2cread) if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd: os.close(c2pwrite) if errwrite != -1 and errread != -1 and errwrite != devnull_fd: os.close(errwrite) if devnull_fd is not None: os.close(devnull_fd) # Prevent a double close of these fds from __init__ on error. self._closed_child_pipe_fds = True # Wait for exec to fail or succeed; possibly raising an # exception (limited in size) errpipe_data = bytearray() while True: part = os.read(errpipe_read, 50000) errpipe_data += part if not part or len(errpipe_data) > 50000: break finally: # be sure the FD is closed no matter what os.close(errpipe_read) if errpipe_data: try: pid, sts = os.waitpid(self.pid, 0) if pid == self.pid: self._handle_exitstatus(sts) else: self.returncode = sys.maxsize except ChildProcessError: pass try: exception_name, hex_errno, err_msg = ( errpipe_data.split(b':', 2)) # The encoding here should match the encoding # written in by the subprocess implementations # like _posixsubprocess err_msg = err_msg.decode() except ValueError: exception_name = b'SubprocessError' hex_errno = b'0' err_msg = 'Bad exception data from child: {!r}'.format( bytes(errpipe_data)) child_exception_type = getattr( builtins, exception_name.decode('ascii'), SubprocessError) if issubclass(child_exception_type, OSError) and hex_errno: errno_num = int(hex_errno, 16) child_exec_never_called = (err_msg == "noexec") if child_exec_never_called: err_msg = "" # The error must be from chdir(cwd). err_filename = cwd else: err_filename = orig_executable if errno_num != 0: err_msg = os.strerror(errno_num) if errno_num == errno.ENOENT: err_msg += ': ' + repr(err_filename) raise child_exception_type(errno_num, err_msg, err_filename) raise child_exception_type(err_msg) def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED, _WSTOPSIG=os.WSTOPSIG): """All callers to this function MUST hold self._waitpid_lock.""" # This method is called (indirectly) by __del__, so it cannot # refer to anything outside of its local scope. if _WIFSIGNALED(sts): self.returncode = -_WTERMSIG(sts) elif _WIFEXITED(sts): self.returncode = _WEXITSTATUS(sts) elif _WIFSTOPPED(sts): self.returncode = -_WSTOPSIG(sts) else: # Should never happen raise SubprocessError("Unknown child exit status!") def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD): """Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it cannot reference anything outside of the local scope (nor can any methods it calls). """ if self.returncode is None: if not self._waitpid_lock.acquire(False): # Something else is busy calling waitpid. Don't allow two # at once. We know nothing yet. return None try: if self.returncode is not None: return self.returncode # Another thread waited. pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except OSError as e: if _deadstate is not None: self.returncode = _deadstate elif e.errno == _ECHILD: # This happens if SIGCLD is set to be ignored or # waiting for child processes has otherwise been # disabled for our process. This child is dead, we # can't get the status. # http://bugs.python.org/issue15756 self.returncode = 0 finally: self._waitpid_lock.release() return self.returncode def _try_wait(self, wait_flags): """All callers to this function MUST hold self._waitpid_lock.""" try: (pid, sts) = os.waitpid(self.pid, wait_flags) except ChildProcessError: # This happens if SIGCLD is set to be ignored or waiting # for child processes has otherwise been disabled for our # process. This child is dead, we can't get the status. pid = self.pid sts = 0 return (pid, sts) def wait(self, timeout=None, endtime=None): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is not None: return self.returncode if endtime is not None: warnings.warn( "'endtime' argument is deprecated; use 'timeout'.", DeprecationWarning, stacklevel=2) if endtime is not None or timeout is not None: if endtime is None: endtime = _time() + timeout elif timeout is None: timeout = self._remaining_time(endtime) if endtime is not None: # Enter a busy loop if we have a timeout. This busy loop was # cribbed from Lib/threading.py in Thread.wait() at r71065. delay = 0.0005 # 500 us -> initial delay of 1 ms while True: if self._waitpid_lock.acquire(False): try: if self.returncode is not None: break # Another thread waited. (pid, sts) = self._try_wait(os.WNOHANG) assert pid == self.pid or pid == 0 if pid == self.pid: self._handle_exitstatus(sts) break finally: self._waitpid_lock.release() remaining = self._remaining_time(endtime) if remaining <= 0: raise TimeoutExpired(self.args, timeout) delay = min(delay * 2, remaining, .05) time.sleep(delay) else: while self.returncode is None: with self._waitpid_lock: if self.returncode is not None: break # Another thread waited. (pid, sts) = self._try_wait(0) # Check the pid and loop as waitpid has been known to # return 0 even without WNOHANG in odd situations. # http://bugs.python.org/issue14396. if pid == self.pid: self._handle_exitstatus(sts) return self.returncode def _communicate(self, input, endtime, orig_timeout): if self.stdin and not self._communication_started: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. try: self.stdin.flush() except BrokenPipeError: pass # communicate() must ignore BrokenPipeError. if not input: try: self.stdin.close() except BrokenPipeError: pass # communicate() must ignore BrokenPipeError. stdout = None stderr = None # Only create this mapping if we haven't already. if not self._communication_started: self._fileobj2output = {} if self.stdout: self._fileobj2output[self.stdout] = [] if self.stderr: self._fileobj2output[self.stderr] = [] if self.stdout: stdout = self._fileobj2output[self.stdout] if self.stderr: stderr = self._fileobj2output[self.stderr] self._save_input(input) if self._input: input_view = memoryview(self._input) with _PopenSelector() as selector: if self.stdin and input: selector.register(self.stdin, selectors.EVENT_WRITE) if self.stdout: selector.register(self.stdout, selectors.EVENT_READ) if self.stderr: selector.register(self.stderr, selectors.EVENT_READ) while selector.get_map(): timeout = self._remaining_time(endtime) if timeout is not None and timeout < 0: raise TimeoutExpired(self.args, orig_timeout) ready = selector.select(timeout) self._check_timeout(endtime, orig_timeout) # XXX Rewrite these to use non-blocking I/O on the file # objects; they are no longer using C stdio! for key, events in ready: if key.fileobj is self.stdin: chunk = input_view[self._input_offset : self._input_offset + _PIPE_BUF] try: self._input_offset += os.write(key.fd, chunk) except BrokenPipeError: selector.unregister(key.fileobj) key.fileobj.close() else: if self._input_offset >= len(self._input): selector.unregister(key.fileobj) key.fileobj.close() elif key.fileobj in (self.stdout, self.stderr): data = os.read(key.fd, 32768) if not data: selector.unregister(key.fileobj) key.fileobj.close() self._fileobj2output[key.fileobj].append(data) self.wait(timeout=self._remaining_time(endtime)) # All data exchanged. Translate lists into strings. if stdout is not None: stdout = b''.join(stdout) if stderr is not None: stderr = b''.join(stderr) # Translate newlines, if requested. # This also turns bytes into strings. if self.encoding or self.errors or self.universal_newlines: if stdout is not None: stdout = self._translate_newlines(stdout, self.stdout.encoding, self.stdout.errors) if stderr is not None: stderr = self._translate_newlines(stderr, self.stderr.encoding, self.stderr.errors) return (stdout, stderr) def _save_input(self, input): # This method is called from the _communicate_with_*() methods # so that if we time out while communicating, we can continue # sending input if we retry. if self.stdin and self._input is None: self._input_offset = 0 self._input = input if input is not None and ( self.encoding or self.errors or self.universal_newlines): self._input = self._input.encode(self.stdin.encoding, self.stdin.errors) def send_signal(self, sig): """Send a signal to the process.""" # Skip signalling a process that we know has already died. if self.returncode is None: os.kill(self.pid, sig) def terminate(self): """Terminate the process with SIGTERM """ self.send_signal(signal.SIGTERM) def kill(self): """Kill the process with SIGKILL """ self.send_signal(signal.SIGKILL)
62,367
1,604
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/wave.py
"""Stuff to parse WAVE files. Usage. Reading WAVE files: f = wave.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). When the setpos() and rewind() methods are not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for linear samples) getcompname() -- returns human-readable version of compression type ('not compressed' linear samples) getparams() -- returns a namedtuple consisting of all of the above in the above order getmarkers() -- returns None (for compatibility with the aifc module) getmark(id) -- raises an error since the mark does not exist (for compatibility with the aifc module) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell() and the position given to setpos() are compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing WAVE files: f = wave.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once tell() -- return current position in output file writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes(b'') or close() to patch up the sizes in the header. The close() method is called automatically when the class instance is destroyed. """ import builtins __all__ = ["open", "openfp", "Error", "Wave_read", "Wave_write"] class Error(Exception): pass WAVE_FORMAT_PCM = 0x0001 _array_fmts = None, 'b', 'h', None, 'i' import audioop import struct import sys from chunk import Chunk from collections import namedtuple _wave_params = namedtuple('_wave_params', 'nchannels sampwidth framerate nframes comptype compname') class Wave_read: """Variables used in this class: These variables are available to the user though appropriate methods of this class: _file -- the open file with methods read(), close(), and seek() set through the __init__() method _nchannels -- the number of audio channels available through the getnchannels() method _nframes -- the number of audio frames available through the getnframes() method _sampwidth -- the number of bytes per audio sample available through the getsampwidth() method _framerate -- the sampling frequency available through the getframerate() method _comptype -- the AIFF-C compression type ('NONE' if AIFF) available through the getcomptype() method _compname -- the human-readable AIFF-C compression type available through the getcomptype() method _soundpos -- the position in the audio stream available through the tell() method, set through the setpos() method These variables are used internally only: _fmt_chunk_read -- 1 iff the FMT chunk has been read _data_seek_needed -- 1 iff positioned correctly in audio file for readframes() _data_chunk -- instantiation of a chunk class for the DATA chunk _framesize -- size of one frame in the file """ def initfp(self, file): self._convert = None self._soundpos = 0 self._file = Chunk(file, bigendian = 0) if self._file.getname() != b'RIFF': raise Error('file does not start with RIFF id') if self._file.read(4) != b'WAVE': raise Error('not a WAVE file') self._fmt_chunk_read = 0 self._data_chunk = None while 1: self._data_seek_needed = 1 try: chunk = Chunk(self._file, bigendian = 0) except EOFError: break chunkname = chunk.getname() if chunkname == b'fmt ': self._read_fmt_chunk(chunk) self._fmt_chunk_read = 1 elif chunkname == b'data': if not self._fmt_chunk_read: raise Error('data chunk before fmt chunk') self._data_chunk = chunk self._nframes = chunk.chunksize // self._framesize self._data_seek_needed = 0 break chunk.skip() if not self._fmt_chunk_read or not self._data_chunk: raise Error('fmt chunk and/or data chunk missing') def __init__(self, f): self._i_opened_the_file = None if isinstance(f, str): f = builtins.open(f, 'rb') self._i_opened_the_file = f # else, assume it is an open file object already try: self.initfp(f) except: if self._i_opened_the_file: f.close() raise def __del__(self): self.close() def __enter__(self): return self def __exit__(self, *args): self.close() # # User visible methods. # def getfp(self): return self._file def rewind(self): self._data_seek_needed = 1 self._soundpos = 0 def close(self): self._file = None file = self._i_opened_the_file if file: self._i_opened_the_file = None file.close() def tell(self): return self._soundpos def getnchannels(self): return self._nchannels def getnframes(self): return self._nframes def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getcomptype(self): return self._comptype def getcompname(self): return self._compname def getparams(self): return _wave_params(self.getnchannels(), self.getsampwidth(), self.getframerate(), self.getnframes(), self.getcomptype(), self.getcompname()) def getmarkers(self): return None def getmark(self, id): raise Error('no marks') def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') self._soundpos = pos self._data_seek_needed = 1 def readframes(self, nframes): if self._data_seek_needed: self._data_chunk.seek(0, 0) pos = self._soundpos * self._framesize if pos: self._data_chunk.seek(pos, 0) self._data_seek_needed = 0 if nframes == 0: return b'' data = self._data_chunk.read(nframes * self._framesize) if self._sampwidth != 1 and sys.byteorder == 'big': data = audioop.byteswap(data, self._sampwidth) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) return data # # Internal methods. # def _read_fmt_chunk(self, chunk): wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from('<HHLLH', chunk.read(14)) if wFormatTag == WAVE_FORMAT_PCM: sampwidth = struct.unpack_from('<H', chunk.read(2))[0] self._sampwidth = (sampwidth + 7) // 8 else: raise Error('unknown format: %r' % (wFormatTag,)) self._framesize = self._nchannels * self._sampwidth self._comptype = 'NONE' self._compname = 'not compressed' class Wave_write: """Variables used in this class: These variables are user settable through appropriate methods of this class: _file -- the open file with methods write(), close(), tell(), seek() set through the __init__() method _comptype -- the AIFF-C compression type ('NONE' in AIFF) set through the setcomptype() or setparams() method _compname -- the human-readable AIFF-C compression type set through the setcomptype() or setparams() method _nchannels -- the number of audio channels set through the setnchannels() or setparams() method _sampwidth -- the number of bytes per audio sample set through the setsampwidth() or setparams() method _framerate -- the sampling frequency set through the setframerate() or setparams() method _nframes -- the number of audio frames written to the header set through the setnframes() or setparams() method These variables are used internally only: _datalength -- the size of the audio samples written to the header _nframeswritten -- the number of frames actually written _datawritten -- the size of the audio samples actually written """ def __init__(self, f): self._i_opened_the_file = None if isinstance(f, str): f = builtins.open(f, 'wb') self._i_opened_the_file = f try: self.initfp(f) except: if self._i_opened_the_file: f.close() raise def initfp(self, file): self._file = file self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._headerwritten = False def __del__(self): self.close() def __enter__(self): return self def __exit__(self, *args): self.close() # # User visible methods. # def setnchannels(self, nchannels): if self._datawritten: raise Error('cannot change parameters after starting to write') if nchannels < 1: raise Error('bad # of channels') self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error('number of channels not set') return self._nchannels def setsampwidth(self, sampwidth): if self._datawritten: raise Error('cannot change parameters after starting to write') if sampwidth < 1 or sampwidth > 4: raise Error('bad sample width') self._sampwidth = sampwidth def getsampwidth(self): if not self._sampwidth: raise Error('sample width not set') return self._sampwidth def setframerate(self, framerate): if self._datawritten: raise Error('cannot change parameters after starting to write') if framerate <= 0: raise Error('bad frame rate') self._framerate = int(round(framerate)) def getframerate(self): if not self._framerate: raise Error('frame rate not set') return self._framerate def setnframes(self, nframes): if self._datawritten: raise Error('cannot change parameters after starting to write') self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, comptype, compname): if self._datawritten: raise Error('cannot change parameters after starting to write') if comptype not in ('NONE',): raise Error('unsupported compression type') self._comptype = comptype self._compname = compname def getcomptype(self): return self._comptype def getcompname(self): return self._compname def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._datawritten: raise Error('cannot change parameters after starting to write') self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): if not self._nchannels or not self._sampwidth or not self._framerate: raise Error('not all parameters set') return _wave_params(self._nchannels, self._sampwidth, self._framerate, self._nframes, self._comptype, self._compname) def setmark(self, id, pos, name): raise Error('setmark() not supported') def getmark(self, id): raise Error('no marks') def getmarkers(self): return None def tell(self): return self._nframeswritten def writeframesraw(self, data): if not isinstance(data, (bytes, bytearray)): data = memoryview(data).cast('B') self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) if self._sampwidth != 1 and sys.byteorder == 'big': data = audioop.byteswap(data, self._sampwidth) self._file.write(data) self._datawritten += len(data) self._nframeswritten = self._nframeswritten + nframes def writeframes(self, data): self.writeframesraw(data) if self._datalength != self._datawritten: self._patchheader() def close(self): try: if self._file: self._ensure_header_written(0) if self._datalength != self._datawritten: self._patchheader() self._file.flush() finally: self._file = None file = self._i_opened_the_file if file: self._i_opened_the_file = None file.close() # # Internal methods. # def _ensure_header_written(self, datasize): if not self._headerwritten: if not self._nchannels: raise Error('# channels not specified') if not self._sampwidth: raise Error('sample width not specified') if not self._framerate: raise Error('sampling rate not specified') self._write_header(datasize) def _write_header(self, initlength): assert not self._headerwritten self._file.write(b'RIFF') if not self._nframes: self._nframes = initlength // (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth try: self._form_length_pos = self._file.tell() except (AttributeError, OSError): self._form_length_pos = None self._file.write(struct.pack('<L4s4sLHHLLHH4s', 36 + self._datalength, b'WAVE', b'fmt ', 16, WAVE_FORMAT_PCM, self._nchannels, self._framerate, self._nchannels * self._framerate * self._sampwidth, self._nchannels * self._sampwidth, self._sampwidth * 8, b'data')) if self._form_length_pos is not None: self._data_length_pos = self._file.tell() self._file.write(struct.pack('<L', self._datalength)) self._headerwritten = True def _patchheader(self): assert self._headerwritten if self._datawritten == self._datalength: return curpos = self._file.tell() self._file.seek(self._form_length_pos, 0) self._file.write(struct.pack('<L', 36 + self._datawritten)) self._file.seek(self._data_length_pos, 0) self._file.write(struct.pack('<L', self._datawritten)) self._file.seek(curpos, 0) self._datalength = self._datawritten def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Wave_read(f) elif mode in ('w', 'wb'): return Wave_write(f) else: raise Error("mode must be 'r', 'rb', 'w', or 'wb'") openfp = open # B/W compatibility
17,709
506
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/contextlib.py
"""Utilities for with-statement contexts. See PEP 343.""" import abc import sys import _collections_abc from collections import deque from functools import wraps __all__ = ["contextmanager", "closing", "AbstractContextManager", "ContextDecorator", "ExitStack", "redirect_stdout", "redirect_stderr", "suppress"] class AbstractContextManager(abc.ABC): """An abstract base class for context managers.""" def __enter__(self): """Return `self` upon entering the runtime context.""" return self @abc.abstractmethod def __exit__(self, exc_type, exc_value, traceback): """Raise any exception triggered within the runtime context.""" return None @classmethod def __subclasshook__(cls, C): if cls is AbstractContextManager: return _collections_abc._check_methods(C, "__enter__", "__exit__") return NotImplemented class ContextDecorator(object): "A base class or mixin that enables context managers to work as decorators." def _recreate_cm(self): """Return a recreated instance of self. Allows an otherwise one-shot context manager like _GeneratorContextManager to support use as a decorator via implicit recreation. This is a private interface just for _GeneratorContextManager. See issue #11647 for details. """ return self def __call__(self, func): @wraps(func) def inner(*args, **kwds): with self._recreate_cm(): return func(*args, **kwds) return inner class _GeneratorContextManager(ContextDecorator, AbstractContextManager): """Helper for @contextmanager decorator.""" def __init__(self, func, args, kwds): self.gen = func(*args, **kwds) self.func, self.args, self.kwds = func, args, kwds # Issue 19330: ensure context manager instances have good docstrings doc = getattr(func, "__doc__", None) if doc is None: doc = type(self).__doc__ self.__doc__ = doc # Unfortunately, this still doesn't provide good help output when # inspecting the created context manager instances, since pydoc # currently bypasses the instance docstring and shows the docstring # for the class instead. # See http://bugs.python.org/issue19404 for more details. def _recreate_cm(self): # _GCM instances are one-shot context managers, so the # CM must be recreated each time a decorated function is # called return self.__class__(self.func, self.args, self.kwds) def __enter__(self): try: return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") from None def __exit__(self, type, value, traceback): if type is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = type() try: self.gen.throw(type, value, traceback) except StopIteration as exc: # Suppress StopIteration *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed. return exc is not value except RuntimeError as exc: # Don't re-raise the passed in exception. (issue27122) if exc is value: return False # Likewise, avoid suppressing if a StopIteration exception # was passed to throw() and later wrapped into a RuntimeError # (see PEP 479). if type is StopIteration and exc.__cause__ is value: return False raise except: # only re-raise if it's *not* the exception that was # passed to throw(), because __exit__() must not raise # an exception unless __exit__() itself failed. But throw() # has to raise the exception to signal propagation, so this # fixes the impedance mismatch between the throw() protocol # and the __exit__() protocol. # if sys.exc_info()[1] is value: return False raise raise RuntimeError("generator didn't stop after throw()") def contextmanager(func): """@contextmanager decorator. Typical usage: @contextmanager def some_generator(<arguments>): <setup> try: yield <value> finally: <cleanup> This makes this: with some_generator(<arguments>) as <variable>: <body> equivalent to this: <setup> try: <variable> = <value> <body> finally: <cleanup> """ @wraps(func) def helper(*args, **kwds): return _GeneratorContextManager(func, args, kwds) return helper class closing(AbstractContextManager): """Context to automatically close something at the end of a block. Code like this: with closing(<module>.open(<arguments>)) as f: <block> is equivalent to this: f = <module>.open(<arguments>) try: <block> finally: f.close() """ def __init__(self, thing): self.thing = thing def __enter__(self): return self.thing def __exit__(self, *exc_info): self.thing.close() class _RedirectStream(AbstractContextManager): _stream = None def __init__(self, new_target): self._new_target = new_target # We use a list of old targets to make this CM re-entrant self._old_targets = [] def __enter__(self): self._old_targets.append(getattr(sys, self._stream)) setattr(sys, self._stream, self._new_target) return self._new_target def __exit__(self, exctype, excinst, exctb): setattr(sys, self._stream, self._old_targets.pop()) class redirect_stdout(_RedirectStream): """Context manager for temporarily redirecting stdout to another file. # How to send help() to stderr with redirect_stdout(sys.stderr): help(dir) # How to write help() to a file with open('help.txt', 'w') as f: with redirect_stdout(f): help(pow) """ _stream = "stdout" class redirect_stderr(_RedirectStream): """Context manager for temporarily redirecting stderr to another file.""" _stream = "stderr" class suppress(AbstractContextManager): """Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement. with suppress(FileNotFoundError): os.remove(somefile) # Execution still resumes here if the file was already removed """ def __init__(self, *exceptions): self._exceptions = exceptions def __enter__(self): pass def __exit__(self, exctype, excinst, exctb): # Unlike isinstance and issubclass, CPython exception handling # currently only looks at the concrete type hierarchy (ignoring # the instance and subclass checking hooks). While Guido considers # that a bug rather than a feature, it's a fairly hard one to fix # due to various internal implementation details. suppress provides # the simpler issubclass based semantics, rather than trying to # exactly reproduce the limitations of the CPython interpreter. # # See http://bugs.python.org/issue12029 for more details return exctype is not None and issubclass(exctype, self._exceptions) # Inspired by discussions on http://bugs.python.org/issue13585 class ExitStack(AbstractContextManager): """Context manager for dynamic management of a stack of exit callbacks For example: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception """ def __init__(self): self._exit_callbacks = deque() def pop_all(self): """Preserve the context stack by transferring it to a new instance""" new_stack = type(self)() new_stack._exit_callbacks = self._exit_callbacks self._exit_callbacks = deque() return new_stack def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods""" def _exit_wrapper(*exc_details): return cm_exit(cm, *exc_details) _exit_wrapper.__self__ = cm self.push(_exit_wrapper) def push(self, exit): """Registers a callback with the standard __exit__ method signature Can suppress exceptions the same way __exit__ methods can. Also accepts any object with an __exit__ method (registering a call to the method instead of the object itself) """ # We use an unbound method rather than a bound method to follow # the standard lookup behaviour for special methods _cb_type = type(exit) try: exit_method = _cb_type.__exit__ except AttributeError: # Not a context manager, so assume its a callable self._exit_callbacks.append(exit) else: self._push_cm_exit(exit, exit_method) return exit # Allow use as a decorator def callback(self, callback, *args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection _exit_wrapper.__wrapped__ = callback self.push(_exit_wrapper) return callback # Allow use as a decorator def enter_context(self, cm): """Enters the supplied context manager If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. """ # We look up the special methods on the type to match the with statement _cm_type = type(cm) _exit = _cm_type.__exit__ result = _cm_type.__enter__(cm) self._push_cm_exit(cm, _exit) return result def close(self): """Immediately unwind the context stack""" self.__exit__(None, None, None) def __exit__(self, *exc_details): received_exc = exc_details[0] is not None # We manipulate the exception state so it behaves as though # we were actually nesting multiple with statements frame_exc = sys.exc_info()[1] def _fix_exception_context(new_exc, old_exc): # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ if exc_context is old_exc: # Context is already set correctly (see issue 20317) return if exc_context is None or exc_context is frame_exc: break new_exc = exc_context # Change the end of the chain to point to the exception # we expect it to reference new_exc.__context__ = old_exc # Callbacks are invoked in LIFO order to match the behaviour of # nested context managers suppressed_exc = False pending_raise = False while self._exit_callbacks: cb = self._exit_callbacks.pop() try: if cb(*exc_details): suppressed_exc = True pending_raise = False exc_details = (None, None, None) except: new_exc_details = sys.exc_info() # simulate the stack of exceptions by setting the context _fix_exception_context(new_exc_details[1], exc_details[1]) pending_raise = True exc_details = new_exc_details if pending_raise: try: # bare "raise exc_details[1]" replaces our carefully # set-up context fixed_ctx = exc_details[1].__context__ raise exc_details[1] except BaseException: exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc
13,162
385
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/calendar.py
"""Calendar printing functions Note when comparing these calendars to the ones printed by cal(1): By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week (0=Monday, 6=Sunday).""" import sys import datetime import locale as _locale from itertools import repeat __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", "firstweekday", "isleap", "leapdays", "weekday", "monthrange", "monthcalendar", "prmonth", "month", "prcal", "calendar", "timegm", "month_name", "month_abbr", "day_name", "day_abbr", "Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar", "LocaleHTMLCalendar", "weekheader"] # Exception raised for bad input (with string parameter for details) error = ValueError # Exceptions raised for bad input class IllegalMonthError(ValueError): def __init__(self, month): self.month = month def __str__(self): return "bad month number %r; must be 1-12" % self.month class IllegalWeekdayError(ValueError): def __init__(self, weekday): self.weekday = weekday def __str__(self): return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday # Constants for months referenced later January = 1 February = 2 # Number of days per month (except for February in leap years) mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This module used to have hard-coded lists of day and month names, as # English strings. The classes following emulate a read-only version of # that, but supply localized names. Note that the values are computed # fresh on each call, in case the user changes locale between calls. class _localized_month: _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)] _months.insert(0, lambda x: "") def __init__(self, format): self.format = format def __getitem__(self, i): funcs = self._months[i] if isinstance(i, slice): return [f(self.format) for f in funcs] else: return funcs(self.format) def __len__(self): return 13 class _localized_day: # January 1, 2001, was a Monday. _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)] def __init__(self, format): self.format = format def __getitem__(self, i): funcs = self._days[i] if isinstance(i, slice): return [f(self.format) for f in funcs] else: return funcs(self.format) def __len__(self): return 7 # Full and abbreviated names of weekdays day_name = _localized_day('%A') day_abbr = _localized_day('%a') # Full and abbreviated names of months (1-based arrays!!!) month_name = _localized_month('%B') month_abbr = _localized_month('%b') # Constants for weekdays (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) def isleap(year): """Return True for leap years, False for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400) def weekday(year, month, day): """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31).""" return datetime.date(year, month, day).weekday() def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise IllegalMonthError(month) day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays class Calendar(object): """ Base calendar class. This class doesn't do any formatting. It simply provides data to subclasses. """ def __init__(self, firstweekday=0): self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday def getfirstweekday(self): return self._firstweekday % 7 def setfirstweekday(self, firstweekday): self._firstweekday = firstweekday firstweekday = property(getfirstweekday, setfirstweekday) def iterweekdays(self): """ Return an iterator for one week of weekday numbers starting with the configured first one. """ for i in range(self.firstweekday, self.firstweekday + 7): yield i%7 def itermonthdates(self, year, month): """ Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ date = datetime.date(year, month, 1) # Go back to the beginning of the week days = (date.weekday() - self.firstweekday) % 7 date -= datetime.timedelta(days=days) oneday = datetime.timedelta(days=1) while True: yield date try: date += oneday except OverflowError: # Adding one day could fail after datetime.MAXYEAR break if date.month != month and date.weekday() == self.firstweekday: break def itermonthdays2(self, year, month): """ Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0. """ for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday): yield d, i % 7 def itermonthdays(self, year, month): """ Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0. """ day1, ndays = monthrange(year, month) days_before = (day1 - self.firstweekday) % 7 yield from repeat(0, days_before) yield from range(1, ndays + 1) days_after = (self.firstweekday - day1 - ndays) % 7 yield from repeat(0, days_after) def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ] def monthdays2calendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero. """ days = list(self.itermonthdays2(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ] def monthdayscalendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero. """ days = list(self.itermonthdays(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ] def yeardatescalendar(self, year, width=3): """ Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects. """ months = [ self.monthdatescalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ] def yeardays2calendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero. """ months = [ self.monthdays2calendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ] def yeardayscalendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. """ months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ] class TextCalendar(Calendar): """ Subclass of Calendar that outputs a calendar as a simple plain text similar to the UNIX program cal. """ def prweek(self, theweek, width): """ Print a single week (no newline). """ print(self.formatweek(theweek, width), end=' ') def formatday(self, day, weekday, width): """ Returns a formatted day. """ if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days return s.center(width) def formatweek(self, theweek, width): """ Returns a single week in a string (no newline). """ return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) def formatweekday(self, day, width): """ Returns a formatted week day name. """ if width >= 9: names = day_name else: names = day_abbr return names[day][:width].center(width) def formatweekheader(self, width): """ Return a header for a week. """ return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays()) def formatmonthname(self, theyear, themonth, width, withyear=True): """ Return a formatted month name. """ s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear) return s.center(width) def prmonth(self, theyear, themonth, w=0, l=0): """ Print a month's calendar. """ print(self.formatmonth(theyear, themonth, w, l), end='') def formatmonth(self, theyear, themonth, w=0, l=0): """ Return a month's calendar string (multi-line). """ w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) s = s.rstrip() s += '\n' * l s += self.formatweekheader(w).rstrip() s += '\n' * l for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += '\n' * l return s def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = range(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip()) a('\n'*l) headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in range(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v) def pryear(self, theyear, w=0, l=0, c=6, m=3): """Print a year's calendar.""" print(self.formatyear(theyear, w, l, c, m)) class HTMLCalendar(Calendar): """ This calendar returns complete HTML pages. """ # CSS classes for the day <td>s cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] def formatday(self, day, weekday): """ Return a day as a table cell. """ if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month else: return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day) def formatweek(self, theweek): """ Return a complete week as a table row. """ s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) return '<tr>%s</tr>' % s def formatweekday(self, day): """ Return a weekday name as a table header. """ return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day]) def formatweekheader(self): """ Return a header for a week as a table row. """ s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) return '<tr>%s</tr>' % s def formatmonthname(self, theyear, themonth, withyear=True): """ Return a month name as a table row. """ if withyear: s = '%s %s' % (month_name[themonth], theyear) else: s = '%s' % month_name[themonth] return '<tr><th colspan="7" class="month">%s</th></tr>' % s def formatmonth(self, theyear, themonth, withyear=True): """ Return a formatted month as a table. """ v = [] a = v.append a('<table border="0" cellpadding="0" cellspacing="0" class="month">') a('\n') a(self.formatmonthname(theyear, themonth, withyear=withyear)) a('\n') a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): a(self.formatweek(week)) a('\n') a('</table>') a('\n') return ''.join(v) def formatyear(self, theyear, width=3): """ Return a formatted year as a table of tables. """ v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="year">') a('\n') a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear)) for i in range(January, January+12, width): # months in this row months = range(i, min(i+width, 13)) a('<tr>') for m in months: a('<td>') a(self.formatmonth(theyear, m, withyear=False)) a('</td>') a('</tr>') a('</table>') return ''.join(v) def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title>\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding, "xmlcharrefreplace") class different_locale: def __init__(self, locale): self.locale = locale def __enter__(self): self.oldlocale = _locale.getlocale(_locale.LC_TIME) _locale.setlocale(_locale.LC_TIME, self.locale) def __exit__(self, *args): _locale.setlocale(_locale.LC_TIME, self.oldlocale) class LocaleTextCalendar(TextCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. """ def __init__(self, firstweekday=0, locale=None): TextCalendar.__init__(self, firstweekday) if locale is None: locale = _locale.getdefaultlocale() self.locale = locale def formatweekday(self, day, width): with different_locale(self.locale): if width >= 9: names = day_name else: names = day_abbr name = names[day] return name[:width].center(width) def formatmonthname(self, theyear, themonth, width, withyear=True): with different_locale(self.locale): s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear) return s.center(width) class LocaleHTMLCalendar(HTMLCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. """ def __init__(self, firstweekday=0, locale=None): HTMLCalendar.__init__(self, firstweekday) if locale is None: locale = _locale.getdefaultlocale() self.locale = locale def formatweekday(self, day): with different_locale(self.locale): s = day_abbr[day] return '<th class="%s">%s</th>' % (self.cssclasses[day], s) def formatmonthname(self, theyear, themonth, withyear=True): with different_locale(self.locale): s = month_name[themonth] if withyear: s = '%s %s' % (s, theyear) return '<tr><th colspan="7" class="month">%s</th></tr>' % s # Support for old module level interface c = TextCalendar() firstweekday = c.getfirstweekday def setfirstweekday(firstweekday): if not MONDAY <= firstweekday <= SUNDAY: raise IllegalWeekdayError(firstweekday) c.firstweekday = firstweekday monthcalendar = c.monthdayscalendar prweek = c.prweek week = c.formatweek weekheader = c.formatweekheader prmonth = c.prmonth month = c.formatmonth calendar = c.formatyear prcal = c.pryear # Spacing of month columns for multi-column year calendar _colwidth = 7*3 - 1 # Amount printed by prweek() _spacing = 6 # Number of spaces between columns def format(cols, colwidth=_colwidth, spacing=_spacing): """Prints multi-column formatting for year calendars""" print(formatstring(cols, colwidth, spacing)) def formatstring(cols, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from n strings, centered within n columns.""" spacing *= ' ' return spacing.join(c.center(colwidth) for c in cols) EPOCH = 1970 _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal() def timegm(tuple): """Unrelated but handy function to calculate Unix timestamp from GMT.""" year, month, day, hour, minute, second = tuple[:6] days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds def main(args): try: import argparse except ImportError: print("error: argparse not yoinked", file=sys.stderr) sys.exit(1) parser = argparse.ArgumentParser() textgroup = parser.add_argument_group('text only arguments') htmlgroup = parser.add_argument_group('html only arguments') textgroup.add_argument( "-w", "--width", type=int, default=2, help="width of date column (default 2)" ) textgroup.add_argument( "-l", "--lines", type=int, default=1, help="number of lines for each week (default 1)" ) textgroup.add_argument( "-s", "--spacing", type=int, default=6, help="spacing between months (default 6)" ) textgroup.add_argument( "-m", "--months", type=int, default=3, help="months per row (default 3)" ) htmlgroup.add_argument( "-c", "--css", default="calendar.css", help="CSS to use for page" ) parser.add_argument( "-L", "--locale", default=None, help="locale to be used from month and weekday names" ) parser.add_argument( "-e", "--encoding", default=None, help="encoding to use for output" ) parser.add_argument( "-t", "--type", default="text", choices=("text", "html"), help="output type (text or html)" ) parser.add_argument( "year", nargs='?', type=int, help="year number (1-9999)" ) parser.add_argument( "month", nargs='?', type=int, help="month number (1-12, text only)" ) options = parser.parse_args(args[1:]) if options.locale and not options.encoding: parser.error("if --locale is specified --encoding is required") sys.exit(1) locale = options.locale, options.encoding if options.type == "html": if options.locale: cal = LocaleHTMLCalendar(locale=locale) else: cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) write = sys.stdout.buffer.write if options.year is None: write(cal.formatyearpage(datetime.date.today().year, **optdict)) elif options.month is None: write(cal.formatyearpage(options.year, **optdict)) else: parser.error("incorrect number of arguments") sys.exit(1) else: if options.locale: cal = LocaleTextCalendar(locale=locale) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if options.month is None: optdict["c"] = options.spacing optdict["m"] = options.months if options.year is None: result = cal.formatyear(datetime.date.today().year, **optdict) elif options.month is None: result = cal.formatyear(options.year, **optdict) else: result = cal.formatmonth(options.year, options.month, **optdict) write = sys.stdout.write if options.encoding: result = result.encode(options.encoding) write = sys.stdout.buffer.write write(result) if __name__ == "__main__": main(sys.argv)
23,333
719
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/queue.py
'''A multi-producer, multi-consumer queue.''' try: import threading except ImportError: import dummy_threading as threading from collections import deque from heapq import heappush, heappop from time import monotonic as time __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] class Empty(Exception): 'Exception raised by Queue.get(block=0)/get_nowait().' pass class Full(Exception): 'Exception raised by Queue.put(block=0)/put_nowait().' pass class Queue: '''Create a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite. ''' def __init__(self, maxsize=0): self.maxsize = maxsize self._init(maxsize) # mutex must be held whenever the queue is mutating. All methods # that acquire mutex must release it before returning. mutex # is shared between the three conditions, so acquiring and # releasing the conditions also acquires and releases mutex. self.mutex = threading.Lock() # Notify not_empty whenever an item is added to the queue; a # thread waiting to get is notified then. self.not_empty = threading.Condition(self.mutex) # Notify not_full whenever an item is removed from the queue; # a thread waiting to put is notified then. self.not_full = threading.Condition(self.mutex) # Notify all_tasks_done whenever the number of unfinished tasks # drops to zero; thread waiting to join() is notified to resume self.all_tasks_done = threading.Condition(self.mutex) self.unfinished_tasks = 0 def task_done(self): '''Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. ''' with self.all_tasks_done: unfinished = self.unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError('task_done() called too many times') self.all_tasks_done.notify_all() self.unfinished_tasks = unfinished def join(self): '''Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. ''' with self.all_tasks_done: while self.unfinished_tasks: self.all_tasks_done.wait() def qsize(self): '''Return the approximate size of the queue (not reliable!).''' with self.mutex: return self._qsize() def empty(self): '''Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs to wait for all queued tasks to be completed, the preferred technique is to use the join() method. ''' with self.mutex: return not self._qsize() def full(self): '''Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race condition where a queue can shrink before the result of full() or qsize() can be used. ''' with self.mutex: return 0 < self.maxsize <= self._qsize() def put(self, item, block=True, timeout=None): '''Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). ''' with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify() def get(self, block=True, timeout=None): '''Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). ''' with self.not_empty: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while not self._qsize(): remaining = endtime - time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item def put_nowait(self, item): '''Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception. ''' return self.put(item, block=False) def get_nowait(self): '''Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. ''' return self.get(block=False) # Override these methods to implement other queue organizations # (e.g. stack or priority queue). # These will only be called with appropriate locks held # Initialize the queue representation def _init(self, maxsize): self.queue = deque() def _qsize(self): return len(self.queue) # Put a new item in the queue def _put(self, item): self.queue.append(item) # Get an item from the queue def _get(self): return self.queue.popleft() class PriorityQueue(Queue): '''Variant of Queue that retrieves open entries in priority order (lowest first). Entries are typically tuples of the form: (priority number, data). ''' def _init(self, maxsize): self.queue = [] def _qsize(self): return len(self.queue) def _put(self, item): heappush(self.queue, item) def _get(self): return heappop(self.queue) class LifoQueue(Queue): '''Variant of Queue that retrieves most recently added entries first.''' def _init(self, maxsize): self.queue = [] def _qsize(self): return len(self.queue) def _put(self, item): self.queue.append(item) def _get(self): return self.queue.pop()
8,780
247
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/fileinput.py
"""Helper class to quickly write a loop over all standard input files. Typical use is: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-' it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the argument to input(). A single file name is also allowed. Functions filename(), lineno() return the filename and cumulative line number of the line that has just been read; filelineno() returns its line number in the current file; isfirstline() returns true iff the line just read is the first line of its file; isstdin() returns true iff the line was read from sys.stdin. Function nextfile() closes the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count; the filename is not changed until after the first line of the next file has been read. Function close() closes the sequence. Before any lines have been read, filename() returns None and both line numbers are zero; nextfile() has no effect. After all lines have been read, filename() and the line number functions return the values pertaining to the last line read; nextfile() has no effect. All files are opened in text mode by default, you can override this by setting the mode parameter to input() or FileInput.__init__(). If an I/O error occurs during opening or reading a file, the OSError exception is raised. If sys.stdin is used more than once, the second and further use will return no lines, except perhaps for interactive use, or if it has been explicitly reset (e.g. using sys.stdin.seek(0)). Empty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty. It is possible that the last line of a file doesn't end in a newline character; otherwise lines are returned including the trailing newline. Class FileInput is the implementation; its methods filename(), lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; sequence access and readline() cannot be mixed. Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file. This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup=".<some extension>" is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is ".bak" and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. XXX The current implementation does not work for MS-DOS 8+3 filesystems. XXX Possible additions: - optional getopt argument processing - isatty() - read(), read(size), even readlines() """ import sys, os __all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno", "fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed", "hook_encoded"] _state = None def input(files=None, inplace=False, backup="", bufsize=0, mode="r", openhook=None): """Return an instance of the FileInput class, which can be iterated. The parameters are passed to the constructor of the FileInput class. The returned instance, in addition to being an iterator, keeps global state for the functions of this module,. """ global _state if _state and _state._file: raise RuntimeError("input() already active") _state = FileInput(files, inplace, backup, bufsize, mode, openhook) return _state def close(): """Close the sequence.""" global _state state = _state _state = None if state: state.close() def nextfile(): """ Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect. """ if not _state: raise RuntimeError("no active input()") return _state.nextfile() def filename(): """ Return the name of the file currently being read. Before the first line has been read, returns None. """ if not _state: raise RuntimeError("no active input()") return _state.filename() def lineno(): """ Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line. """ if not _state: raise RuntimeError("no active input()") return _state.lineno() def filelineno(): """ Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. """ if not _state: raise RuntimeError("no active input()") return _state.filelineno() def fileno(): """ Return the file number of the current file. When no file is currently opened, returns -1. """ if not _state: raise RuntimeError("no active input()") return _state.fileno() def isfirstline(): """ Returns true the line just read is the first line of its file, otherwise returns false. """ if not _state: raise RuntimeError("no active input()") return _state.isfirstline() def isstdin(): """ Returns true if the last line was read from sys.stdin, otherwise returns false. """ if not _state: raise RuntimeError("no active input()") return _state.isstdin() class FileInput: """FileInput([files[, inplace[, backup[, bufsize, [, mode[, openhook]]]]]]) Class FileInput is the implementation of the module; its methods filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed. """ def __init__(self, files=None, inplace=False, backup="", bufsize=0, mode="r", openhook=None): if isinstance(files, str): files = (files,) else: if files is None: files = sys.argv[1:] if not files: files = ('-',) else: files = tuple(files) self._files = files self._inplace = inplace self._backup = backup if bufsize: import warnings warnings.warn('bufsize is deprecated and ignored', DeprecationWarning, stacklevel=2) self._savestdout = None self._output = None self._filename = None self._startlineno = 0 self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = None # restrict mode argument to reading modes if mode not in ('r', 'rU', 'U', 'rb'): raise ValueError("FileInput opening mode must be one of " "'r', 'rU', 'U' and 'rb'") if 'U' in mode: import warnings warnings.warn("'U' mode is deprecated", DeprecationWarning, 2) self._mode = mode if openhook: if inplace: raise ValueError("FileInput cannot use an opening hook in inplace mode") if not callable(openhook): raise ValueError("FileInput openhook must be callable") self._openhook = openhook def __del__(self): self.close() def close(self): try: self.nextfile() finally: self._files = () def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __iter__(self): return self def __next__(self): while True: line = self._readline() if line: self._filelineno += 1 return line if not self._file: raise StopIteration self.nextfile() # repeat with next file def __getitem__(self, i): if i != self.lineno(): raise RuntimeError("accessing lines out of order") try: return self.__next__() except StopIteration: raise IndexError("end of input reached") def nextfile(self): savestdout = self._savestdout self._savestdout = None if savestdout: sys.stdout = savestdout output = self._output self._output = None try: if output: output.close() finally: file = self._file self._file = None try: del self._readline # restore FileInput._readline except AttributeError: pass try: if file and not self._isstdin: file.close() finally: backupfilename = self._backupfilename self._backupfilename = None if backupfilename and not self._backup: try: os.unlink(backupfilename) except OSError: pass self._isstdin = False def readline(self): while True: line = self._readline() if line: self._filelineno += 1 return line if not self._file: return line self.nextfile() # repeat with next file def _readline(self): if not self._files: if 'b' in self._mode: return b'' else: return '' self._filename = self._files[0] self._files = self._files[1:] self._startlineno = self.lineno() self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' if 'b' in self._mode: self._file = getattr(sys.stdin, 'buffer', sys.stdin) else: self._file = sys.stdin self._isstdin = True else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or ".bak")) try: os.unlink(self._backupfilename) except OSError: pass # The next few lines may raise OSError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, self._mode) try: perm = os.fstat(self._file.fileno()).st_mode except OSError: self._output = open(self._filename, "w") else: mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC if hasattr(os, 'O_BINARY'): mode |= os.O_BINARY fd = os.open(self._filename, mode, perm) self._output = os.fdopen(fd, "w") try: if hasattr(os, 'chmod'): os.chmod(self._filename, perm) except OSError: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise OSError if self._openhook: self._file = self._openhook(self._filename, self._mode) else: self._file = open(self._filename, self._mode) self._readline = self._file.readline # hide FileInput._readline return self._readline() def filename(self): return self._filename def lineno(self): return self._startlineno + self._filelineno def filelineno(self): return self._filelineno def fileno(self): if self._file: try: return self._file.fileno() except ValueError: return -1 else: return -1 def isfirstline(self): return self._filelineno == 1 def isstdin(self): return self._isstdin def hook_compressed(filename, mode): ext = os.path.splitext(filename)[1] if ext == '.gz': import gzip return gzip.open(filename, mode) elif ext == '.bz2': import bz2 return bz2.BZ2File(filename, mode) else: return open(filename, mode) def hook_encoded(encoding, errors=None): def openhook(filename, mode): return open(filename, mode, encoding=encoding, errors=errors) return openhook def _test(): import getopt inplace = False backup = False opts, args = getopt.getopt(sys.argv[1:], "ib:") for o, a in opts: if o == '-i': inplace = True if o == '-b': backup = a for line in input(args, inplace=inplace, backup=backup): if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\r': line = line[:-1] print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), isfirstline() and "*" or "", line)) print("%d: %s[%d]" % (lineno(), filename(), filelineno())) if __name__ == '__main__': _test()
14,471
426
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/code.py
"""Utilities needed to emulate Python's interactive interpreter. """ # Inspired by similar code by Jeff Epler and Fredrik Lundh. import sys import traceback import argparse from codeop import CommandCompiler, compile_command __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] class InteractiveInterpreter: """Base class for InteractiveConsole. This class deals with parsing and interpreter state (the user's namespace); it doesn't deal with input buffering or prompting or input file naming (the filename is always passed in explicitly). """ def __init__(self, locals=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. """ if locals is None: locals = {"__name__": "__console__", "__doc__": None} self.locals = locals self.compile = CommandCompiler() def runsource(self, source, filename="<input>", symbol="single"): """Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens. 3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit). The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line. """ try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return False if code is None: # Case 2 return True # Case 3 self.runcode(code) return False def runcode(self, code): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: exec(code, self.locals) except SystemExit: raise except: self.showtraceback() def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below. """ type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value if sys.excepthook is sys.__excepthook__: lines = traceback.format_exception_only(type, value) self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(type, value, tb) def showtraceback(self): """Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below. """ sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() sys.last_traceback = last_tb try: lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) if sys.excepthook is sys.__excepthook__: self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(ei[0], ei[1], last_tb) finally: last_tb = ei = None def write(self, data): """Write a string. The base implementation writes to sys.stderr; a subclass may replace this with a different implementation. """ sys.stderr.write(data) class InteractiveConsole(InteractiveInterpreter): """Closely emulate the behavior of the interactive Python interpreter. This class builds on InteractiveInterpreter and adds prompting using the familiar sys.ps1 and sys.ps2, and input buffering. """ def __init__(self, locals=None, filename="<console>"): """Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. The optional filename argument should specify the (file)name of the input stream; it will show up in tracebacks. """ InteractiveInterpreter.__init__(self, locals) self.filename = filename self.resetbuffer() def resetbuffer(self): """Reset the input buffer.""" self.buffer = [] def interact(self, banner=None, exitmsg=None): """Closely emulate the interactive Python console. The optional banner argument specifies the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!). The optional exitmsg argument specifies the exit message printed when exiting. Pass the empty string to suppress printing an exit message. If exitmsg is not given or None, a default message is printed. """ try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) elif banner: self.write("%s\n" % str(banner)) more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = self.raw_input(prompt) except EOFError: self.write("\n") break else: more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0 if exitmsg is None: self.write('now exiting %s...\n' % self.__class__.__name__) elif exitmsg != '': self.write('%s\n' % exitmsg) def push(self, line): """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()). """ self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more def raw_input(self, prompt=""): """Write a prompt and read a line. The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. The base implementation uses the built-in function input(); a subclass may replace this with a different implementation. """ return input(prompt) def interact(banner=None, readfunc=None, local=None, exitmsg=None): """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() exitmsg -- passed to InteractiveConsole.interact() """ console = InteractiveConsole(local) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner, exitmsg) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-q', action='store_true', help="don't print version and copyright messages") args = parser.parse_args() if args.q or sys.flags.quiet: banner = '' else: banner = None interact(banner)
10,614
315
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/struct.py
__all__ = [ # Functions 'calcsize', 'pack', 'pack_into', 'unpack', 'unpack_from', 'iter_unpack', # Classes 'Struct', # Exceptions 'error' ] from _struct import Struct, calcsize, error, iter_unpack, pack, pack_into, unpack, unpack_from from _struct import _clearcache try: from _struct import __doc__ except ImportError: pass
364
19
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/genericpath.py
""" Path operations common to more than one OS Do not use directly. The OS specific modules import the appropriate functions from this module themselves. """ import os import stat __all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime', 'getsize', 'isdir', 'isfile', 'samefile', 'sameopenfile', 'samestat'] # Does a path exist? # This is false for dangling symbolic links on systems that support them. def exists(path): """Test whether a path exists. Returns False for broken symbolic links""" try: os.stat(path) except OSError: return False return True # This follows symbolic links, so both islink() and isdir() can be true # for the same path on systems that support symlinks def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except OSError: return False return stat.S_ISREG(st.st_mode) # Is a path a directory? # This follows symbolic links, so both islink() and isdir() # can be true for the same path on systems that support symlinks def isdir(s): """Return true if the pathname refers to an existing directory.""" try: st = os.stat(s) except OSError: return False return stat.S_ISDIR(st.st_mode) def getsize(filename): """Return the size of a file, reported by os.stat().""" return os.stat(filename).st_size def getmtime(filename): """Return the last modification time of a file, reported by os.stat().""" return os.stat(filename).st_mtime def getatime(filename): """Return the last access time of a file, reported by os.stat().""" return os.stat(filename).st_atime def getctime(filename): """Return the metadata change time of a file, reported by os.stat().""" return os.stat(filename).st_ctime # Return the longest prefix of all list elements. def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' # Some people pass in a list of pathname parts to operate in an OS-agnostic # fashion; don't try to translate in that case as that's an abuse of the # API and they are already doing what they need to be OS-agnostic and so # they most likely won't be using an os.PathLike object in the sublists. if not isinstance(m[0], (list, tuple)): m = tuple(map(os.fspath, m)) s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1 # Are two stat buffers (obtained from stat, fstat or lstat) # describing the same file? def samestat(s1, s2): """Test whether two stat buffers reference the same file""" return (s1.st_ino == s2.st_ino and s1.st_dev == s2.st_dev) # Are two filenames really pointing to the same file? def samefile(f1, f2): """Test whether two pathnames reference the same actual file""" s1 = os.stat(f1) s2 = os.stat(f2) return samestat(s1, s2) # Are two open files really referencing the same file? # (Not necessarily the same file descriptor!) def sameopenfile(fp1, fp2): """Test whether two open file objects reference the same file""" s1 = os.fstat(fp1) s2 = os.fstat(fp2) return samestat(s1, s2) # Split a path in root and extension. # The extension is everything starting at the last dot in the last # pathname component; the root is everything before that. # It is always true that root + ext == p. # Generic implementation of splitext, to be parametrized with # the separators def _splitext(p, sep, altsep, extsep): """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.""" # NOTE: This code must work for text and bytes strings. sepIndex = p.rfind(sep) if altsep: altsepIndex = p.rfind(altsep) sepIndex = max(sepIndex, altsepIndex) dotIndex = p.rfind(extsep) if dotIndex > sepIndex: # skip all leading dots filenameIndex = sepIndex + 1 while filenameIndex < dotIndex: if p[filenameIndex:filenameIndex+1] != extsep: return p[:dotIndex], p[dotIndex:] filenameIndex += 1 return p, p[:0] def _check_arg_types(funcname, *args): hasstr = hasbytes = False for s in args: if isinstance(s, str): hasstr = True elif isinstance(s, bytes): hasbytes = True else: raise TypeError('%s() argument must be str or bytes, not %r' % (funcname, s.__class__.__name__)) from None if hasstr and hasbytes: raise TypeError("Can't mix strings and bytes in path components") from None
4,756
152
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/antigravity.py
import webbrowser import hashlib webbrowser.open("https://xkcd.com/353/") def geohash(latitude, longitude, datedow): '''Compute geohash() using the Munroe algorithm. >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 37.857713 -122.544543 ''' # https://xkcd.com/426/ h = hashlib.md5(datedow).hexdigest() p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])] print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))
477
18
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/typing.py
import abc from abc import abstractmethod, abstractproperty import collections import contextlib import functools import re as stdlib_re # Avoid confusion with the re we export. import sys import types try: import collections.abc as collections_abc except ImportError: import collections as collections_abc # Fallback for PY3.2. if sys.version_info[:2] >= (3, 6): import _collections_abc # Needed for private function _check_methods # noqa try: from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType except ImportError: WrapperDescriptorType = type(object.__init__) MethodWrapperType = type(object().__str__) MethodDescriptorType = type(str.join) # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. 'Any', 'Callable', 'ClassVar', 'Generic', 'Optional', 'Tuple', 'Type', 'TypeVar', 'Union', # ABCs (from collections.abc). 'AbstractSet', # collections.abc.Set. 'GenericMeta', # subclass of abc.ABCMeta and a metaclass # for 'Generic' and ABCs below. 'ByteString', 'Container', 'ContextManager', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'Sequence', 'Sized', 'ValuesView', # The following are added depending on presence # of their non-generic counterparts in stdlib: # Awaitable, # AsyncIterator, # AsyncIterable, # Coroutine, # Collection, # AsyncGenerator, # AsyncContextManager # Structural checks, a.k.a. protocols. 'Reversible', 'SupportsAbs', 'SupportsBytes', 'SupportsComplex', 'SupportsFloat', 'SupportsInt', 'SupportsRound', # Concrete collection types. 'Counter', 'Deque', 'Dict', 'DefaultDict', 'List', 'Set', 'FrozenSet', 'NamedTuple', # Not really a type. 'Generator', # One-off things. 'AnyStr', 'cast', 'get_type_hints', 'NewType', 'no_type_check', 'no_type_check_decorator', 'overload', 'Text', 'TYPE_CHECKING', ] # The pseudo-submodules 're' and 'io' are part of the public # namespace, but excluded from __all__ because they might stomp on # legitimate imports of those modules. def _qualname(x): if sys.version_info[:2] >= (3, 3): return x.__qualname__ else: # Fall back to just name. return x.__name__ def _trim_name(nm): whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase') if nm.startswith('_') and nm not in whitelist: nm = nm[1:] return nm class TypingMeta(type): """Metaclass for most types defined in typing module (not a part of public API). This overrides __new__() to require an extra keyword parameter '_root', which serves as a guard against naive subclassing of the typing classes. Any legitimate class defined using a metaclass derived from TypingMeta must pass _root=True. This also defines a dummy constructor (all the work for most typing constructs is done in __new__) and a nicer repr(). """ _is_protocol = False def __new__(cls, name, bases, namespace, *, _root=False): if not _root: raise TypeError("Cannot subclass %s" % (', '.join(map(_type_repr, bases)) or '()')) return super().__new__(cls, name, bases, namespace) def __init__(self, *args, **kwds): pass def _eval_type(self, globalns, localns): """Override this in subclasses to interpret forward references. For example, List['C'] is internally stored as List[_ForwardRef('C')], which should evaluate to List[C], where C is an object found in globalns or localns (searching localns first, of course). """ return self def _get_type_vars(self, tvars): pass def __repr__(self): qname = _trim_name(_qualname(self)) return '%s.%s' % (self.__module__, qname) class _TypingBase(metaclass=TypingMeta, _root=True): """Internal indicator of special typing constructs.""" __slots__ = ('__weakref__',) def __init__(self, *args, **kwds): pass def __new__(cls, *args, **kwds): """Constructor. This only exists to give a better error message in case someone tries to subclass a special typing object (not a good idea). """ if (len(args) == 3 and isinstance(args[0], str) and isinstance(args[1], tuple)): # Close enough. raise TypeError("Cannot subclass %r" % cls) return super().__new__(cls) # Things that are not classes also need these. def _eval_type(self, globalns, localns): return self def _get_type_vars(self, tvars): pass def __repr__(self): cls = type(self) qname = _trim_name(_qualname(cls)) return '%s.%s' % (cls.__module__, qname) def __call__(self, *args, **kwds): raise TypeError("Cannot instantiate %r" % type(self)) class _FinalTypingBase(_TypingBase, _root=True): """Internal mix-in class to prevent instantiation. Prevents instantiation unless _root=True is given in class call. It is used to create pseudo-singleton instances Any, Union, Optional, etc. """ __slots__ = () def __new__(cls, *args, _root=False, **kwds): self = super().__new__(cls, *args, **kwds) if _root is True: return self raise TypeError("Cannot instantiate %r" % cls) def __reduce__(self): return _trim_name(type(self).__name__) class _ForwardRef(_TypingBase, _root=True): """Internal wrapper to hold a forward reference.""" __slots__ = ('__forward_arg__', '__forward_code__', '__forward_evaluated__', '__forward_value__') def __init__(self, arg): super().__init__(arg) if not isinstance(arg, str): raise TypeError('Forward reference must be a string -- got %r' % (arg,)) try: code = compile(arg, '<string>', 'eval') except SyntaxError: raise SyntaxError('Forward reference must be an expression -- got %r' % (arg,)) self.__forward_arg__ = arg self.__forward_code__ = code self.__forward_evaluated__ = False self.__forward_value__ = None def _eval_type(self, globalns, localns): if not self.__forward_evaluated__ or localns is not globalns: if globalns is None and localns is None: globalns = localns = {} elif globalns is None: globalns = localns elif localns is None: localns = globalns self.__forward_value__ = _type_check( eval(self.__forward_code__, globalns, localns), "Forward references must evaluate to types.") self.__forward_evaluated__ = True return self.__forward_value__ def __eq__(self, other): if not isinstance(other, _ForwardRef): return NotImplemented return (self.__forward_arg__ == other.__forward_arg__ and self.__forward_value__ == other.__forward_value__) def __hash__(self): return hash((self.__forward_arg__, self.__forward_value__)) def __instancecheck__(self, obj): raise TypeError("Forward references cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Forward references cannot be used with issubclass().") def __repr__(self): return '_ForwardRef(%r)' % (self.__forward_arg__,) class _TypeAlias(_TypingBase, _root=True): """Internal helper class for defining generic variants of concrete types. Note that this is not a type; let's call it a pseudo-type. It cannot be used in instance and subclass checks in parameterized form, i.e. ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning ``False``. """ __slots__ = ('name', 'type_var', 'impl_type', 'type_checker') def __init__(self, name, type_var, impl_type, type_checker): """Initializer. Args: name: The name, e.g. 'Pattern'. type_var: The type parameter, e.g. AnyStr, or the specific type, e.g. str. impl_type: The implementation type. type_checker: Function that takes an impl_type instance. and returns a value that should be a type_var instance. """ assert isinstance(name, str), repr(name) assert isinstance(impl_type, type), repr(impl_type) assert not isinstance(impl_type, TypingMeta), repr(impl_type) assert isinstance(type_var, (type, _TypingBase)), repr(type_var) self.name = name self.type_var = type_var self.impl_type = impl_type self.type_checker = type_checker def __repr__(self): return "%s[%s]" % (self.name, _type_repr(self.type_var)) def __getitem__(self, parameter): if not isinstance(self.type_var, TypeVar): raise TypeError("%s cannot be further parameterized." % self) if self.type_var.__constraints__ and isinstance(parameter, type): if not issubclass(parameter, self.type_var.__constraints__): raise TypeError("%s is not a valid substitution for %s." % (parameter, self.type_var)) if isinstance(parameter, TypeVar) and parameter is not self.type_var: raise TypeError("%s cannot be re-parameterized." % self) return self.__class__(self.name, parameter, self.impl_type, self.type_checker) def __eq__(self, other): if not isinstance(other, _TypeAlias): return NotImplemented return self.name == other.name and self.type_var == other.type_var def __hash__(self): return hash((self.name, self.type_var)) def __instancecheck__(self, obj): if not isinstance(self.type_var, TypeVar): raise TypeError("Parameterized type aliases cannot be used " "with isinstance().") return isinstance(obj, self.impl_type) def __subclasscheck__(self, cls): if not isinstance(self.type_var, TypeVar): raise TypeError("Parameterized type aliases cannot be used " "with issubclass().") return issubclass(cls, self.impl_type) def _get_type_vars(types, tvars): for t in types: if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): t._get_type_vars(tvars) def _type_vars(types): tvars = [] _get_type_vars(types, tvars) return tuple(tvars) def _eval_type(t, globalns, localns): if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): return t._eval_type(globalns, localns) return t def _type_check(arg, msg): """Check that the argument is a type, and return it (internal helper). As a special case, accept None and return type(None) instead. Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable. The msg argument is a human-readable error message, e.g. "Union[arg, ...]: arg should be a type." We append the repr() of the actual value (truncated to 100 chars). """ if arg is None: return type(None) if isinstance(arg, str): arg = _ForwardRef(arg) if ( isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or not isinstance(arg, (type, _TypingBase)) and not callable(arg) ): raise TypeError(msg + " Got %.100r." % (arg,)) # Bare Union etc. are not valid as type arguments if ( type(arg).__name__ in ('_Union', '_Optional') and not getattr(arg, '__origin__', None) or isinstance(arg, TypingMeta) and arg._gorg in (Generic, _Protocol) ): raise TypeError("Plain %s is not valid as type argument" % arg) return arg def _type_repr(obj): """Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall back on repr(obj). """ if isinstance(obj, type) and not isinstance(obj, TypingMeta): if obj.__module__ == 'builtins': return _qualname(obj) return '%s.%s' % (obj.__module__, _qualname(obj)) if obj is ...: return('...') if isinstance(obj, types.FunctionType): return obj.__name__ return repr(obj) class _Any(_FinalTypingBase, _root=True): """Special type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. - All values assumed to be instances of Any. Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance or class checks. """ __slots__ = () def __instancecheck__(self, obj): raise TypeError("Any cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Any cannot be used with issubclass().") Any = _Any(_root=True) class _NoReturn(_FinalTypingBase, _root=True): """Special type indicating functions that never return. Example:: from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') This type is invalid in other positions, e.g., ``List[NoReturn]`` will fail in static type checkers. """ __slots__ = () def __instancecheck__(self, obj): raise TypeError("NoReturn cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("NoReturn cannot be used with issubclass().") NoReturn = _NoReturn(_root=True) class TypeVar(_TypingBase, _root=True): """Type variable. Usage:: T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows: def repeat(x: T, n: int) -> List[T]: '''Return a list containing n references to x.''' return [x]*n def longest(x: A, y: A) -> A: '''Return the longest of two strings.''' return x if len(x) >= len(y) else y The latter example's signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str. At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. Type variables defined with covariant=True or contravariant=True can be used do declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables. Type variables can be introspected. e.g.: T.__name__ == 'T' T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes) """ __slots__ = ('__name__', '__bound__', '__constraints__', '__covariant__', '__contravariant__') def __init__(self, name, *constraints, bound=None, covariant=False, contravariant=False): super().__init__(name, *constraints, bound=bound, covariant=covariant, contravariant=contravariant) self.__name__ = name if covariant and contravariant: raise ValueError("Bivariant types are not supported.") self.__covariant__ = bool(covariant) self.__contravariant__ = bool(contravariant) if constraints and bound is not None: raise TypeError("Constraints cannot be combined with bound=...") if constraints and len(constraints) == 1: raise TypeError("A single constraint is not allowed") msg = "TypeVar(name, constraint, ...): constraints must be types." self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) if bound: self.__bound__ = _type_check(bound, "Bound must be a type.") else: self.__bound__ = None def _get_type_vars(self, tvars): if self not in tvars: tvars.append(self) def __repr__(self): if self.__covariant__: prefix = '+' elif self.__contravariant__: prefix = '-' else: prefix = '~' return prefix + self.__name__ def __instancecheck__(self, instance): raise TypeError("Type variables cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Type variables cannot be used with issubclass().") # Some unconstrained type variables. These are used by the container types. # (These are not for export.) T = TypeVar('T') # Any type. KT = TypeVar('KT') # Key type. VT = TypeVar('VT') # Value type. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. # A useful type variable with constraints. This represents string types. # (This one *is* for export!) AnyStr = TypeVar('AnyStr', bytes, str) def _replace_arg(arg, tvars, args): """An internal helper function: replace arg if it is a type variable found in tvars with corresponding substitution from args or with corresponding substitution sub-tree if arg is a generic type. """ if tvars is None: tvars = [] if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)): return arg._subs_tree(tvars, args) if isinstance(arg, TypeVar): for i, tvar in enumerate(tvars): if arg == tvar: return args[i] return arg # Special typing constructs Union, Optional, Generic, Callable and Tuple # use three special attributes for internal bookkeeping of generic types: # * __parameters__ is a tuple of unique free type parameters of a generic # type, for example, Dict[T, T].__parameters__ == (T,); # * __origin__ keeps a reference to a type that was subscripted, # e.g., Union[T, int].__origin__ == Union; # * __args__ is a tuple of all arguments used in subscripting, # e.g., Dict[T, int].__args__ == (T, int). def _subs_tree(cls, tvars=None, args=None): """An internal helper function: calculate substitution tree for generic cls after replacing its type parameters with substitutions in tvars -> args (if any). Repeat the same following __origin__'s. Return a list of arguments with all possible substitutions performed. Arguments that are generic classes themselves are represented as tuples (so that no new classes are created by this function). For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)] """ if cls.__origin__ is None: return cls # Make of chain of origins (i.e. cls -> cls.__origin__) current = cls.__origin__ orig_chain = [] while current.__origin__ is not None: orig_chain.append(current) current = current.__origin__ # Replace type variables in __args__ if asked ... tree_args = [] for arg in cls.__args__: tree_args.append(_replace_arg(arg, tvars, args)) # ... then continue replacing down the origin chain. for ocls in orig_chain: new_tree_args = [] for arg in ocls.__args__: new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args)) tree_args = new_tree_args return tree_args def _remove_dups_flatten(parameters): """An internal helper for Union creation and substitution: flatten Union's among parameters, then remove duplicates and strict subclasses. """ # Flatten out Union[Union[...], ...]. params = [] for p in parameters: if isinstance(p, _Union) and p.__origin__ is Union: params.extend(p.__args__) elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union: params.extend(p[1:]) else: params.append(p) # Weed out strict duplicates, preserving the first of each occurrence. all_params = set(params) if len(all_params) < len(params): new_params = [] for t in params: if t in all_params: new_params.append(t) all_params.remove(t) params = new_params assert not all_params, all_params # Weed out subclasses. # E.g. Union[int, Employee, Manager] == Union[int, Employee]. # If object is present it will be sole survivor among proper classes. # Never discard type variables. # (In particular, Union[str, AnyStr] != AnyStr.) all_params = set(params) for t1 in params: if not isinstance(t1, type): continue if any(isinstance(t2, type) and issubclass(t1, t2) for t2 in all_params - {t1} if not (isinstance(t2, GenericMeta) and t2.__origin__ is not None)): all_params.remove(t1) return tuple(t for t in params if t in all_params) def _check_generic(cls, parameters): # Check correct count for parameters of a generic cls (internal helper). if not cls.__parameters__: raise TypeError("%s is not a generic class" % repr(cls)) alen = len(parameters) elen = len(cls.__parameters__) if alen != elen: raise TypeError("Too %s parameters for %s; actual %s, expected %s" % ("many" if alen > elen else "few", repr(cls), alen, elen)) _cleanups = [] def _tp_cache(func): """Internal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. """ cached = functools.lru_cache()(func) _cleanups.append(cached.cache_clear) @functools.wraps(func) def inner(*args, **kwds): try: return cached(*args, **kwds) except TypeError: pass # All real errors (not unhashable args) are raised below. return func(*args, **kwds) return inner class _Union(_FinalTypingBase, _root=True): """Union type; Union[X, Y] means either X or Y. To define a union, use e.g. Union[int, str]. Details: - The arguments must be types and there must be at least one. - None as an argument is a special case and is replaced by type(None). - Unions of unions are flattened, e.g.:: Union[Union[int, str], float] == Union[int, str, float] - Unions of a single argument vanish, e.g.:: Union[int] == int # The constructor actually returns int - Redundant arguments are skipped, e.g.:: Union[int, str, int] == Union[int, str] - When comparing unions, the argument order is ignored, e.g.:: Union[int, str] == Union[str, int] - When two arguments have a subclass relationship, the least derived argument is kept, e.g.:: class Employee: pass class Manager(Employee): pass Union[int, Employee, Manager] == Union[int, Employee] Union[Manager, int, Employee] == Union[int, Employee] Union[Employee, Manager] == Employee - Similar for object:: Union[int, object] == object - You cannot subclass or instantiate a union. - You can use Optional[X] as a shorthand for Union[X, None]. """ __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__') def __new__(cls, parameters=None, origin=None, *args, _root=False): self = super().__new__(cls, parameters, origin, *args, _root=_root) if origin is None: self.__parameters__ = None self.__args__ = None self.__origin__ = None self.__tree_hash__ = hash(frozenset(('Union',))) return self if not isinstance(parameters, tuple): raise TypeError("Expected parameters=<tuple>") if origin is Union: parameters = _remove_dups_flatten(parameters) # It's not a union if there's only one type left. if len(parameters) == 1: return parameters[0] self.__parameters__ = _type_vars(parameters) self.__args__ = parameters self.__origin__ = origin # Pre-calculate the __hash__ on instantiation. # This improves speed for complex substitutions. subs_tree = self._subs_tree() if isinstance(subs_tree, tuple): self.__tree_hash__ = hash(frozenset(subs_tree)) else: self.__tree_hash__ = hash(subs_tree) return self def _eval_type(self, globalns, localns): if self.__args__ is None: return self ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__) ev_origin = _eval_type(self.__origin__, globalns, localns) if ev_args == self.__args__ and ev_origin == self.__origin__: # Everything is already evaluated. return self return self.__class__(ev_args, ev_origin, _root=True) def _get_type_vars(self, tvars): if self.__origin__ and self.__parameters__: _get_type_vars(self.__parameters__, tvars) def __repr__(self): if self.__origin__ is None: return super().__repr__() tree = self._subs_tree() if not isinstance(tree, tuple): return repr(tree) return tree[0]._tree_repr(tree) def _tree_repr(self, tree): arg_list = [] for arg in tree[1:]: if not isinstance(arg, tuple): arg_list.append(_type_repr(arg)) else: arg_list.append(arg[0]._tree_repr(arg)) return super().__repr__() + '[%s]' % ', '.join(arg_list) @_tp_cache def __getitem__(self, parameters): if parameters == (): raise TypeError("Cannot take a Union of no types.") if not isinstance(parameters, tuple): parameters = (parameters,) if self.__origin__ is None: msg = "Union[arg, ...]: each arg must be a type." else: msg = "Parameters to generic types must be types." parameters = tuple(_type_check(p, msg) for p in parameters) if self is not Union: _check_generic(self, parameters) return self.__class__(parameters, origin=self, _root=True) def _subs_tree(self, tvars=None, args=None): if self is Union: return Union # Nothing to substitute tree_args = _subs_tree(self, tvars, args) tree_args = _remove_dups_flatten(tree_args) if len(tree_args) == 1: return tree_args[0] # Union of a single type is that type return (Union,) + tree_args def __eq__(self, other): if isinstance(other, _Union): return self.__tree_hash__ == other.__tree_hash__ elif self is not Union: return self._subs_tree() == other else: return self is other def __hash__(self): return self.__tree_hash__ def __instancecheck__(self, obj): raise TypeError("Unions cannot be used with isinstance().") def __subclasscheck__(self, cls): raise TypeError("Unions cannot be used with issubclass().") Union = _Union(_root=True) class _Optional(_FinalTypingBase, _root=True): """Optional type. Optional[X] is equivalent to Union[X, None]. """ __slots__ = () @_tp_cache def __getitem__(self, arg): arg = _type_check(arg, "Optional[t] requires a single type.") return Union[arg, type(None)] Optional = _Optional(_root=True) def _next_in_mro(cls): """Helper for Generic.__new__. Returns the class after the last occurrence of Generic or Generic[...] in cls.__mro__. """ next_in_mro = object # Look for the last occurrence of Generic or Generic[...]. for i, c in enumerate(cls.__mro__[:-1]): if isinstance(c, GenericMeta) and c._gorg is Generic: next_in_mro = cls.__mro__[i + 1] return next_in_mro def _make_subclasshook(cls): """Construct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls. """ if isinstance(cls.__extra__, abc.ABCMeta): # The logic mirrors that of ABCMeta.__subclasscheck__. # Registered classes need not be checked here because # cls and its extra share the same _abc_registry. def __extrahook__(subclass): res = cls.__extra__.__subclasshook__(subclass) if res is not NotImplemented: return res if cls.__extra__ in subclass.__mro__: return True for scls in cls.__extra__.__subclasses__(): if isinstance(scls, GenericMeta): continue if issubclass(subclass, scls): return True return NotImplemented else: # For non-ABC extras we'll just call issubclass(). def __extrahook__(subclass): if cls.__extra__ and issubclass(subclass, cls.__extra__): return True return NotImplemented return __extrahook__ def _no_slots_copy(dct): """Internal helper: copy class __dict__ and clean slots class variables. (They will be re-created if necessary by normal class machinery.) """ dict_copy = dict(dct) if '__slots__' in dict_copy: for slot in dict_copy['__slots__']: dict_copy.pop(slot, None) return dict_copy class GenericMeta(TypingMeta, abc.ABCMeta): """Metaclass for generic types. This is a metaclass for typing.Generic and generic ABCs defined in typing module. User defined subclasses of GenericMeta can override __new__ and invoke super().__new__. Note that GenericMeta.__new__ has strict rules on what is allowed in its bases argument: * plain Generic is disallowed in bases; * Generic[...] should appear in bases at most once; * if Generic[...] is present, then it should list all type variables that appear in other bases. In addition, type of all generic bases is erased, e.g., C[int] is stripped to plain C. """ def __new__(cls, name, bases, namespace, tvars=None, args=None, origin=None, extra=None, orig_bases=None): """Create a new generic class. GenericMeta.__new__ accepts keyword arguments that are used for internal bookkeeping, therefore an override should pass unused keyword arguments to super(). """ if tvars is not None: # Called from __getitem__() below. assert origin is not None assert all(isinstance(t, TypeVar) for t in tvars), tvars else: # Called from class statement. assert tvars is None, tvars assert args is None, args assert origin is None, origin # Get the full set of tvars from the bases. tvars = _type_vars(bases) # Look for Generic[T1, ..., Tn]. # If found, tvars must be a subset of it. # If not found, tvars is it. # Also check for and reject plain Generic, # and reject multiple Generic[...]. gvars = None for base in bases: if base is Generic: raise TypeError("Cannot inherit from plain Generic") if (isinstance(base, GenericMeta) and base.__origin__ is Generic): if gvars is not None: raise TypeError( "Cannot inherit from Generic[...] multiple types.") gvars = base.__parameters__ if gvars is None: gvars = tvars else: tvarset = set(tvars) gvarset = set(gvars) if not tvarset <= gvarset: raise TypeError( "Some type variables (%s) " "are not listed in Generic[%s]" % (", ".join(str(t) for t in tvars if t not in gvarset), ", ".join(str(g) for g in gvars))) tvars = gvars initial_bases = bases if extra is not None and type(extra) is abc.ABCMeta and extra not in bases: bases = (extra,) + bases bases = tuple(b._gorg if isinstance(b, GenericMeta) else b for b in bases) # remove bare Generic from bases if there are other generic bases if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): bases = tuple(b for b in bases if b is not Generic) namespace.update({'__origin__': origin, '__extra__': extra, '_gorg': None if not origin else origin._gorg}) self = super().__new__(cls, name, bases, namespace, _root=True) super(GenericMeta, self).__setattr__('_gorg', self if not origin else origin._gorg) self.__parameters__ = tvars # Be prepared that GenericMeta will be subclassed by TupleMeta # and CallableMeta, those two allow ..., (), or [] in __args___. self.__args__ = tuple(... if a is _TypingEllipsis else () if a is _TypingEmpty else a for a in args) if args else None # Speed hack (https://github.com/python/typing/issues/196). self.__next_in_mro__ = _next_in_mro(self) # Preserve base classes on subclassing (__bases__ are type erased now). if orig_bases is None: self.__orig_bases__ = initial_bases # This allows unparameterized generic collections to be used # with issubclass() and isinstance() in the same way as their # collections.abc counterparts (e.g., isinstance([], Iterable)). if ( '__subclasshook__' not in namespace and extra or # allow overriding getattr(self.__subclasshook__, '__name__', '') == '__extrahook__' ): self.__subclasshook__ = _make_subclasshook(self) if isinstance(extra, abc.ABCMeta): self._abc_registry = extra._abc_registry self._abc_cache = extra._abc_cache elif origin is not None: self._abc_registry = origin._abc_registry self._abc_cache = origin._abc_cache if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2. self.__qualname__ = origin.__qualname__ self.__tree_hash__ = (hash(self._subs_tree()) if origin else super(GenericMeta, self).__hash__()) return self # _abc_negative_cache and _abc_negative_cache_version # realised as descriptors, since GenClass[t1, t2, ...] always # share subclass info with GenClass. # This is an important memory optimization. @property def _abc_negative_cache(self): if isinstance(self.__extra__, abc.ABCMeta): return self.__extra__._abc_negative_cache return self._gorg._abc_generic_negative_cache @_abc_negative_cache.setter def _abc_negative_cache(self, value): if self.__origin__ is None: if isinstance(self.__extra__, abc.ABCMeta): self.__extra__._abc_negative_cache = value else: self._abc_generic_negative_cache = value @property def _abc_negative_cache_version(self): if isinstance(self.__extra__, abc.ABCMeta): return self.__extra__._abc_negative_cache_version return self._gorg._abc_generic_negative_cache_version @_abc_negative_cache_version.setter def _abc_negative_cache_version(self, value): if self.__origin__ is None: if isinstance(self.__extra__, abc.ABCMeta): self.__extra__._abc_negative_cache_version = value else: self._abc_generic_negative_cache_version = value def _get_type_vars(self, tvars): if self.__origin__ and self.__parameters__: _get_type_vars(self.__parameters__, tvars) def _eval_type(self, globalns, localns): ev_origin = (self.__origin__._eval_type(globalns, localns) if self.__origin__ else None) ev_args = tuple(_eval_type(a, globalns, localns) for a in self.__args__) if self.__args__ else None if ev_origin == self.__origin__ and ev_args == self.__args__: return self return self.__class__(self.__name__, self.__bases__, _no_slots_copy(self.__dict__), tvars=_type_vars(ev_args) if ev_args else None, args=ev_args, origin=ev_origin, extra=self.__extra__, orig_bases=self.__orig_bases__) def __repr__(self): if self.__origin__ is None: return super().__repr__() return self._tree_repr(self._subs_tree()) def _tree_repr(self, tree): arg_list = [] for arg in tree[1:]: if arg == (): arg_list.append('()') elif not isinstance(arg, tuple): arg_list.append(_type_repr(arg)) else: arg_list.append(arg[0]._tree_repr(arg)) return super().__repr__() + '[%s]' % ', '.join(arg_list) def _subs_tree(self, tvars=None, args=None): if self.__origin__ is None: return self tree_args = _subs_tree(self, tvars, args) return (self._gorg,) + tuple(tree_args) def __eq__(self, other): if not isinstance(other, GenericMeta): return NotImplemented if self.__origin__ is None or other.__origin__ is None: return self is other return self.__tree_hash__ == other.__tree_hash__ def __hash__(self): return self.__tree_hash__ @_tp_cache def __getitem__(self, params): if not isinstance(params, tuple): params = (params,) if not params and self._gorg is not Tuple: raise TypeError( "Parameter list to %s[...] cannot be empty" % _qualname(self)) msg = "Parameters to generic types must be types." params = tuple(_type_check(p, msg) for p in params) if self is Generic: # Generic can only be subscripted with unique type variables. if not all(isinstance(p, TypeVar) for p in params): raise TypeError( "Parameters to Generic[...] must all be type variables") if len(set(params)) != len(params): raise TypeError( "Parameters to Generic[...] must all be unique") tvars = params args = params elif self in (Tuple, Callable): tvars = _type_vars(params) args = params elif self is _Protocol: # _Protocol is internal, don't check anything. tvars = params args = params elif self.__origin__ in (Generic, _Protocol): # Can't subscript Generic[...] or _Protocol[...]. raise TypeError("Cannot subscript already-subscripted %s" % repr(self)) else: # Subscripting a regular Generic subclass. _check_generic(self, params) tvars = _type_vars(params) args = params prepend = (self,) if self.__origin__ is None else () return self.__class__(self.__name__, prepend + self.__bases__, _no_slots_copy(self.__dict__), tvars=tvars, args=args, origin=self, extra=self.__extra__, orig_bases=self.__orig_bases__) def __subclasscheck__(self, cls): if self.__origin__ is not None: if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: raise TypeError("Parameterized generics cannot be used with class " "or instance checks") return False if self is Generic: raise TypeError("Class %r cannot be used with class " "or instance checks" % self) return super().__subclasscheck__(cls) def __instancecheck__(self, instance): # Since we extend ABC.__subclasscheck__ and # ABC.__instancecheck__ inlines the cache checking done by the # latter, we must extend __instancecheck__ too. For simplicity # we just skip the cache check -- instance checks for generic # classes are supposed to be rare anyways. return issubclass(instance.__class__, self) def __setattr__(self, attr, value): # We consider all the subscripted generics as proxies for original class if ( attr.startswith('__') and attr.endswith('__') or attr.startswith('_abc_') or self._gorg is None # The class is not fully created, see #typing/506 ): super(GenericMeta, self).__setattr__(attr, value) else: super(GenericMeta, self._gorg).__setattr__(attr, value) # Prevent checks for Generic to crash when defining Generic. Generic = None def _generic_new(base_cls, cls, *args, **kwds): # Assure type is erased on instantiation, # but attempt to store it in __orig_class__ if cls.__origin__ is None: if (base_cls.__new__ is object.__new__ and cls.__init__ is not object.__init__): return base_cls.__new__(cls) else: return base_cls.__new__(cls, *args, **kwds) else: origin = cls._gorg if (base_cls.__new__ is object.__new__ and cls.__init__ is not object.__init__): obj = base_cls.__new__(origin) else: obj = base_cls.__new__(origin, *args, **kwds) try: obj.__orig_class__ = cls except AttributeError: pass obj.__init__(*args, **kwds) return obj class Generic(metaclass=GenericMeta): """Abstract base class for generic types. A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default """ __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Generic: raise TypeError("Type Generic cannot be instantiated; " "it can be used only as a base class") return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) class _TypingEmpty: """Internal placeholder for () or []. Used by TupleMeta and CallableMeta to allow empty list/tuple in specific places, without allowing them to sneak in where prohibited. """ class _TypingEllipsis: """Internal placeholder for ... (ellipsis).""" class TupleMeta(GenericMeta): """Metaclass for Tuple (internal).""" @_tp_cache def __getitem__(self, parameters): if self.__origin__ is not None or self._gorg is not Tuple: # Normal generic rules apply if this is not the first subscription # or a subscription of a subclass. return super().__getitem__(parameters) if parameters == (): return super().__getitem__((_TypingEmpty,)) if not isinstance(parameters, tuple): parameters = (parameters,) if len(parameters) == 2 and parameters[1] is ...: msg = "Tuple[t, ...]: t must be a type." p = _type_check(parameters[0], msg) return super().__getitem__((p, _TypingEllipsis)) msg = "Tuple[t0, t1, ...]: each t must be a type." parameters = tuple(_type_check(p, msg) for p in parameters) return super().__getitem__(parameters) def __instancecheck__(self, obj): if self.__args__ is None: return isinstance(obj, tuple) raise TypeError("Parameterized Tuple cannot be used " "with isinstance().") def __subclasscheck__(self, cls): if self.__args__ is None: return issubclass(cls, tuple) raise TypeError("Parameterized Tuple cannot be used " "with issubclass().") class Tuple(tuple, extra=tuple, metaclass=TupleMeta): """Tuple type; Tuple[X, Y] is the cross-product type of X and Y. Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. """ __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Tuple: raise TypeError("Type Tuple cannot be instantiated; " "use tuple() instead") return _generic_new(tuple, cls, *args, **kwds) class CallableMeta(GenericMeta): """Metaclass for Callable (internal).""" def __repr__(self): if self.__origin__ is None: return super().__repr__() return self._tree_repr(self._subs_tree()) def _tree_repr(self, tree): if self._gorg is not Callable: return super()._tree_repr(tree) # For actual Callable (not its subclass) we override # super()._tree_repr() for nice formatting. arg_list = [] for arg in tree[1:]: if not isinstance(arg, tuple): arg_list.append(_type_repr(arg)) else: arg_list.append(arg[0]._tree_repr(arg)) if arg_list[0] == '...': return repr(tree[0]) + '[..., %s]' % arg_list[1] return (repr(tree[0]) + '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1])) def __getitem__(self, parameters): """A thin wrapper around __getitem_inner__ to provide the latter with hashable arguments to improve speed. """ if self.__origin__ is not None or self._gorg is not Callable: return super().__getitem__(parameters) if not isinstance(parameters, tuple) or len(parameters) != 2: raise TypeError("Callable must be used as " "Callable[[arg, ...], result].") args, result = parameters if args is Ellipsis: parameters = (Ellipsis, result) else: if not isinstance(args, list): raise TypeError("Callable[args, result]: args must be a list." " Got %.100r." % (args,)) parameters = (tuple(args), result) return self.__getitem_inner__(parameters) @_tp_cache def __getitem_inner__(self, parameters): args, result = parameters msg = "Callable[args, result]: result must be a type." result = _type_check(result, msg) if args is Ellipsis: return super().__getitem__((_TypingEllipsis, result)) msg = "Callable[[arg, ...], result]: each arg must be a type." args = tuple(_type_check(arg, msg) for arg in args) parameters = args + (result,) return super().__getitem__(parameters) class Callable(extra=collections_abc.Callable, metaclass=CallableMeta): """Callable type; Callable[[int], str] is a function of (int) -> str. The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or ellipsis; the return type must be a single type. There is no syntax to indicate optional or keyword arguments, such function types are rarely used as callback types. """ __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Callable: raise TypeError("Type Callable cannot be instantiated; " "use a non-abstract subclass instead") return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) class _ClassVar(_FinalTypingBase, _root=True): """Special type construct to mark class variables. An annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:: class Starship: stats: ClassVar[Dict[str, int]] = {} # class variable damage: int = 10 # instance variable ClassVar accepts only types and cannot be further subscribed. Note that ClassVar is not a class itself, and should not be used with isinstance() or issubclass(). """ __slots__ = ('__type__',) def __init__(self, tp=None, **kwds): self.__type__ = tp def __getitem__(self, item): cls = type(self) if self.__type__ is None: return cls(_type_check(item, '{} accepts only single type.'.format(cls.__name__[1:])), _root=True) raise TypeError('{} cannot be further subscripted' .format(cls.__name__[1:])) def _eval_type(self, globalns, localns): new_tp = _eval_type(self.__type__, globalns, localns) if new_tp == self.__type__: return self return type(self)(new_tp, _root=True) def __repr__(self): r = super().__repr__() if self.__type__ is not None: r += '[{}]'.format(_type_repr(self.__type__)) return r def __hash__(self): return hash((type(self).__name__, self.__type__)) def __eq__(self, other): if not isinstance(other, _ClassVar): return NotImplemented if self.__type__ is not None: return self.__type__ == other.__type__ return self is other ClassVar = _ClassVar(_root=True) def cast(typ, val): """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). """ return val def _get_defaults(func): """Internal helper to extract the default arguments, by name.""" try: code = func.__code__ except AttributeError: # Some built-in functions don't have __code__, __defaults__, etc. return {} pos_count = code.co_argcount arg_names = code.co_varnames arg_names = arg_names[:pos_count] defaults = func.__defaults__ or () kwdefaults = func.__kwdefaults__ res = dict(kwdefaults) if kwdefaults else {} pos_offset = pos_count - len(defaults) for name, value in zip(arg_names[pos_offset:], defaults): assert name not in res res[name] = value return res _allowed_types = (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.ModuleType, WrapperDescriptorType, MethodWrapperType, MethodDescriptorType) def get_type_hints(obj, globalns=None, localns=None): """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set. The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members. TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present. BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals. - If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module's globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. - If one dict argument is passed, it is used for both globals and locals. - If two dict arguments are passed, they specify globals and locals, respectively. """ if getattr(obj, '__no_type_check__', None): return {} # Classes require a special treatment. if isinstance(obj, type): hints = {} for base in reversed(obj.__mro__): if globalns is None: base_globals = sys.modules[base.__module__].__dict__ else: base_globals = globalns ann = base.__dict__.get('__annotations__', {}) for name, value in ann.items(): if value is None: value = type(None) if isinstance(value, str): value = _ForwardRef(value) value = _eval_type(value, base_globals, localns) hints[name] = value return hints if globalns is None: if isinstance(obj, types.ModuleType): globalns = obj.__dict__ else: globalns = getattr(obj, '__globals__', {}) if localns is None: localns = globalns elif localns is None: localns = globalns hints = getattr(obj, '__annotations__', None) if hints is None: # Return empty annotations for something that _could_ have them. if isinstance(obj, _allowed_types): return {} else: raise TypeError('{!r} is not a module, class, method, ' 'or function.'.format(obj)) defaults = _get_defaults(obj) hints = dict(hints) for name, value in hints.items(): if value is None: value = type(None) if isinstance(value, str): value = _ForwardRef(value) value = _eval_type(value, globalns, localns) if name in defaults and defaults[name] is None: value = Optional[value] hints[name] = value return hints def no_type_check(arg): """Decorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the function(s) or class(es) in place. """ if isinstance(arg, type): arg_attrs = arg.__dict__.copy() for attr, val in arg.__dict__.items(): if val in arg.__bases__ + (arg,): arg_attrs.pop(attr) for obj in arg_attrs.values(): if isinstance(obj, types.FunctionType): obj.__no_type_check__ = True if isinstance(obj, type): no_type_check(obj) try: arg.__no_type_check__ = True except TypeError: # built-in classes pass return arg def no_type_check_decorator(decorator): """Decorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check. """ @functools.wraps(decorator) def wrapped_decorator(*args, **kwds): func = decorator(*args, **kwds) func = no_type_check(func) return func return wrapped_decorator def _overload_dummy(*args, **kwds): """Helper for @overload to raise when called.""" raise NotImplementedError( "You should not call an overloaded function. " "A series of @overload-decorated functions " "outside a stub module should always be followed " "by an implementation that is not @overload-ed.") def overload(func): """Decorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should *not* be decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): # implementation goes here """ return _overload_dummy class _ProtocolMeta(GenericMeta): """Internal metaclass for _Protocol. This exists so _Protocol classes can be generic without deriving from Generic. """ def __instancecheck__(self, obj): if _Protocol not in self.__bases__: return super().__instancecheck__(obj) raise TypeError("Protocols cannot be used with isinstance().") def __subclasscheck__(self, cls): if not self._is_protocol: # No structural checks since this isn't a protocol. return NotImplemented if self is _Protocol: # Every class is a subclass of the empty protocol. return True # Find all attributes defined in the protocol. attrs = self._get_protocol_attrs() for attr in attrs: if not any(attr in d.__dict__ for d in cls.__mro__): return False return True def _get_protocol_attrs(self): # Get all Protocol base classes. protocol_bases = [] for c in self.__mro__: if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol': protocol_bases.append(c) # Get attributes included in protocol. attrs = set() for base in protocol_bases: for attr in base.__dict__.keys(): # Include attributes not defined in any non-protocol bases. for c in self.__mro__: if (c is not base and attr in c.__dict__ and not getattr(c, '_is_protocol', False)): break else: if (not attr.startswith('_abc_') and attr != '__abstractmethods__' and attr != '__annotations__' and attr != '__weakref__' and attr != '_is_protocol' and attr != '_gorg' and attr != '__dict__' and attr != '__args__' and attr != '__slots__' and attr != '_get_protocol_attrs' and attr != '__next_in_mro__' and attr != '__parameters__' and attr != '__origin__' and attr != '__orig_bases__' and attr != '__extra__' and attr != '__tree_hash__' and attr != '__module__'): attrs.add(attr) return attrs class _Protocol(metaclass=_ProtocolMeta): """Internal base class for protocol classes. This implements a simple-minded structural issubclass check (similar but more general than the one-offs in collections.abc such as Hashable). """ __slots__ = () _is_protocol = True # Various ABCs mimicking those in collections.abc. # A few are simply re-exported for completeness. Hashable = collections_abc.Hashable # Not generic. if hasattr(collections_abc, 'Awaitable'): class Awaitable(Generic[T_co], extra=collections_abc.Awaitable): __slots__ = () __all__.append('Awaitable') if hasattr(collections_abc, 'Coroutine'): class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co], extra=collections_abc.Coroutine): __slots__ = () __all__.append('Coroutine') if hasattr(collections_abc, 'AsyncIterable'): class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable): __slots__ = () class AsyncIterator(AsyncIterable[T_co], extra=collections_abc.AsyncIterator): __slots__ = () __all__.append('AsyncIterable') __all__.append('AsyncIterator') class Iterable(Generic[T_co], extra=collections_abc.Iterable): __slots__ = () class Iterator(Iterable[T_co], extra=collections_abc.Iterator): __slots__ = () class SupportsInt(_Protocol): __slots__ = () @abstractmethod def __int__(self) -> int: pass class SupportsFloat(_Protocol): __slots__ = () @abstractmethod def __float__(self) -> float: pass class SupportsComplex(_Protocol): __slots__ = () @abstractmethod def __complex__(self) -> complex: pass class SupportsBytes(_Protocol): __slots__ = () @abstractmethod def __bytes__(self) -> bytes: pass class SupportsAbs(_Protocol[T_co]): __slots__ = () @abstractmethod def __abs__(self) -> T_co: pass class SupportsRound(_Protocol[T_co]): __slots__ = () @abstractmethod def __round__(self, ndigits: int = 0) -> T_co: pass if hasattr(collections_abc, 'Reversible'): class Reversible(Iterable[T_co], extra=collections_abc.Reversible): __slots__ = () else: class Reversible(_Protocol[T_co]): __slots__ = () @abstractmethod def __reversed__(self) -> 'Iterator[T_co]': pass Sized = collections_abc.Sized # Not generic. class Container(Generic[T_co], extra=collections_abc.Container): __slots__ = () if hasattr(collections_abc, 'Collection'): class Collection(Sized, Iterable[T_co], Container[T_co], extra=collections_abc.Collection): __slots__ = () __all__.append('Collection') # Callable was defined earlier. if hasattr(collections_abc, 'Collection'): class AbstractSet(Collection[T_co], extra=collections_abc.Set): __slots__ = () else: class AbstractSet(Sized, Iterable[T_co], Container[T_co], extra=collections_abc.Set): __slots__ = () class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet): __slots__ = () # NOTE: It is only covariant in the value type. if hasattr(collections_abc, 'Collection'): class Mapping(Collection[KT], Generic[KT, VT_co], extra=collections_abc.Mapping): __slots__ = () else: class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co], extra=collections_abc.Mapping): __slots__ = () class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping): __slots__ = () if hasattr(collections_abc, 'Reversible'): if hasattr(collections_abc, 'Collection'): class Sequence(Reversible[T_co], Collection[T_co], extra=collections_abc.Sequence): __slots__ = () else: class Sequence(Sized, Reversible[T_co], Container[T_co], extra=collections_abc.Sequence): __slots__ = () else: class Sequence(Sized, Iterable[T_co], Container[T_co], extra=collections_abc.Sequence): __slots__ = () class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence): __slots__ = () class ByteString(Sequence[int], extra=collections_abc.ByteString): __slots__ = () class List(list, MutableSequence[T], extra=list): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is List: raise TypeError("Type List cannot be instantiated; " "use list() instead") return _generic_new(list, cls, *args, **kwds) class Deque(collections.deque, MutableSequence[T], extra=collections.deque): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Deque: return collections.deque(*args, **kwds) return _generic_new(collections.deque, cls, *args, **kwds) class Set(set, MutableSet[T], extra=set): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Set: raise TypeError("Type Set cannot be instantiated; " "use set() instead") return _generic_new(set, cls, *args, **kwds) class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is FrozenSet: raise TypeError("Type FrozenSet cannot be instantiated; " "use frozenset() instead") return _generic_new(frozenset, cls, *args, **kwds) class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView): __slots__ = () class KeysView(MappingView[KT], AbstractSet[KT], extra=collections_abc.KeysView): __slots__ = () class ItemsView(MappingView[Tuple[KT, VT_co]], AbstractSet[Tuple[KT, VT_co]], Generic[KT, VT_co], extra=collections_abc.ItemsView): __slots__ = () class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView): __slots__ = () if hasattr(contextlib, 'AbstractContextManager'): class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager): __slots__ = () else: class ContextManager(Generic[T_co]): __slots__ = () def __enter__(self): return self @abc.abstractmethod def __exit__(self, exc_type, exc_value, traceback): return None @classmethod def __subclasshook__(cls, C): if cls is ContextManager: # In Python 3.6+, it is possible to set a method to None to # explicitly indicate that the class does not implement an ABC # (https://bugs.python.org/issue25958), but we do not support # that pattern here because this fallback class is only used # in Python 3.5 and earlier. if (any("__enter__" in B.__dict__ for B in C.__mro__) and any("__exit__" in B.__dict__ for B in C.__mro__)): return True return NotImplemented if hasattr(contextlib, 'AbstractAsyncContextManager'): class AsyncContextManager(Generic[T_co], extra=contextlib.AbstractAsyncContextManager): __slots__ = () __all__.append('AsyncContextManager') elif sys.version_info[:2] >= (3, 5): exec(""" class AsyncContextManager(Generic[T_co]): __slots__ = () async def __aenter__(self): return self @abc.abstractmethod async def __aexit__(self, exc_type, exc_value, traceback): return None @classmethod def __subclasshook__(cls, C): if cls is AsyncContextManager: if sys.version_info[:2] >= (3, 6): return _collections_abc._check_methods(C, "__aenter__", "__aexit__") if (any("__aenter__" in B.__dict__ for B in C.__mro__) and any("__aexit__" in B.__dict__ for B in C.__mro__)): return True return NotImplemented __all__.append('AsyncContextManager') """) class Dict(dict, MutableMapping[KT, VT], extra=dict): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Dict: raise TypeError("Type Dict cannot be instantiated; " "use dict() instead") return _generic_new(dict, cls, *args, **kwds) class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], extra=collections.defaultdict): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is DefaultDict: return collections.defaultdict(*args, **kwds) return _generic_new(collections.defaultdict, cls, *args, **kwds) class Counter(collections.Counter, Dict[T, int], extra=collections.Counter): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Counter: return collections.Counter(*args, **kwds) return _generic_new(collections.Counter, cls, *args, **kwds) if hasattr(collections, 'ChainMap'): # ChainMap only exists in 3.3+ __all__.append('ChainMap') class ChainMap(collections.ChainMap, MutableMapping[KT, VT], extra=collections.ChainMap): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is ChainMap: return collections.ChainMap(*args, **kwds) return _generic_new(collections.ChainMap, cls, *args, **kwds) # Determine what base class to use for Generator. if hasattr(collections_abc, 'Generator'): # Sufficiently recent versions of 3.5 have a Generator ABC. _G_base = collections_abc.Generator else: # Fall back on the exact type. _G_base = types.GeneratorType class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], extra=_G_base): __slots__ = () def __new__(cls, *args, **kwds): if cls._gorg is Generator: raise TypeError("Type Generator cannot be instantiated; " "create a subclass instead") return _generic_new(_G_base, cls, *args, **kwds) if hasattr(collections_abc, 'AsyncGenerator'): class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra], extra=collections_abc.AsyncGenerator): __slots__ = () __all__.append('AsyncGenerator') # Internal type variable used for Type[]. CT_co = TypeVar('CT_co', covariant=True, bound=type) # This is not a real generic class. Don't use outside annotations. class Type(Generic[CT_co], extra=type): """A special construct usable to annotate class objects. For example, suppose we have the following classes:: class User: ... # Abstract base for User classes class BasicUser(User): ... class ProUser(User): ... class TeamUser(User): ... And a function that takes a class argument that's a subclass of User and returns an instance of the corresponding class:: U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: user = user_class() # (Here we could write the user object to a database) return user joe = new_user(BasicUser) At this point the type checker knows that joe has type BasicUser. """ __slots__ = () def _make_nmtuple(name, types): msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type" types = [(n, _type_check(t, msg)) for n, t in types] nm_tpl = collections.namedtuple(name, [n for n, t in types]) # Prior to PEP 526, only _field_types attribute was assigned. # Now, both __annotations__ and _field_types are used to maintain compatibility. nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types) try: nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass return nm_tpl _PY36 = sys.version_info[:2] >= (3, 6) # attributes prohibited to set in NamedTuple class syntax _prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__', '_fields', '_field_defaults', '_field_types', '_make', '_replace', '_asdict', '_source') _special = ('__module__', '__name__', '__qualname__', '__annotations__') class NamedTupleMeta(type): def __new__(cls, typename, bases, ns): if ns.get('_root', False): return super().__new__(cls, typename, bases, ns) if not _PY36: raise TypeError("Class syntax for NamedTuple is only supported" " in Python 3.6+") types = ns.get('__annotations__', {}) nm_tpl = _make_nmtuple(typename, types.items()) defaults = [] defaults_dict = {} for field_name in types: if field_name in ns: default_value = ns[field_name] defaults.append(default_value) defaults_dict[field_name] = default_value elif defaults: raise TypeError("Non-default namedtuple field {field_name} cannot " "follow default field(s) {default_names}" .format(field_name=field_name, default_names=', '.join(defaults_dict.keys()))) nm_tpl.__new__.__annotations__ = collections.OrderedDict(types) nm_tpl.__new__.__defaults__ = tuple(defaults) nm_tpl._field_defaults = defaults_dict # update from user namespace without overriding special namedtuple attributes for key in ns: if key in _prohibited: raise AttributeError("Cannot overwrite NamedTuple attribute " + key) elif key not in _special and key not in nm_tpl._fields: setattr(nm_tpl, key, ns[key]) return nm_tpl class NamedTuple(metaclass=NamedTupleMeta): """Typed version of namedtuple. Usage in Python versions >= 3.6:: class Employee(NamedTuple): name: str id: int This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has extra __annotations__ and _field_types attributes, giving an ordered dict mapping field names to types. __annotations__ should be preferred, while _field_types is kept to maintain pre PEP 526 compatibility. (The field names are in the _fields attribute, which is part of the namedtuple API.) Alternative equivalent keyword syntax is also accepted:: Employee = NamedTuple('Employee', name=str, id=int) In Python versions <= 3.5 use:: Employee = NamedTuple('Employee', [('name', str), ('id', int)]) """ _root = True def __new__(self, typename, fields=None, **kwargs): if kwargs and not _PY36: raise TypeError("Keyword syntax for NamedTuple is only supported" " in Python 3.6+") if fields is None: fields = kwargs.items() elif kwargs: raise TypeError("Either list of fields or keywords" " can be provided to NamedTuple, not both") return _make_nmtuple(typename, fields) def NewType(name, tp): """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int """ def new_type(x): return x new_type.__name__ = name new_type.__supertype__ = tp return new_type # Python-version-specific alias (Python 2: unicode; Python 3: str) Text = str # Constant that's True when type checking, but False here. TYPE_CHECKING = False class IO(Generic[AnyStr]): """Generic base class for TextIO and BinaryIO. This is an abstract, generic version of the return of open(). NOTE: This does not distinguish between the different possible classes (text vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO and BinaryIO subclasses below capture the distinctions between text vs. binary, which is pervasive in the interface; however we currently do not offer a way to track the other distinctions in the type system. """ __slots__ = () @abstractproperty def mode(self) -> str: pass @abstractproperty def name(self) -> str: pass @abstractmethod def close(self) -> None: pass @abstractmethod def closed(self) -> bool: pass @abstractmethod def fileno(self) -> int: pass @abstractmethod def flush(self) -> None: pass @abstractmethod def isatty(self) -> bool: pass @abstractmethod def read(self, n: int = -1) -> AnyStr: pass @abstractmethod def readable(self) -> bool: pass @abstractmethod def readline(self, limit: int = -1) -> AnyStr: pass @abstractmethod def readlines(self, hint: int = -1) -> List[AnyStr]: pass @abstractmethod def seek(self, offset: int, whence: int = 0) -> int: pass @abstractmethod def seekable(self) -> bool: pass @abstractmethod def tell(self) -> int: pass @abstractmethod def truncate(self, size: int = None) -> int: pass @abstractmethod def writable(self) -> bool: pass @abstractmethod def write(self, s: AnyStr) -> int: pass @abstractmethod def writelines(self, lines: List[AnyStr]) -> None: pass @abstractmethod def __enter__(self) -> 'IO[AnyStr]': pass @abstractmethod def __exit__(self, type, value, traceback) -> None: pass class BinaryIO(IO[bytes]): """Typed version of the return of open() in binary mode.""" __slots__ = () @abstractmethod def write(self, s: Union[bytes, bytearray]) -> int: pass @abstractmethod def __enter__(self) -> 'BinaryIO': pass class TextIO(IO[str]): """Typed version of the return of open() in text mode.""" __slots__ = () @abstractproperty def buffer(self) -> BinaryIO: pass @abstractproperty def encoding(self) -> str: pass @abstractproperty def errors(self) -> Optional[str]: pass @abstractproperty def line_buffering(self) -> bool: pass @abstractproperty def newlines(self) -> Any: pass @abstractmethod def __enter__(self) -> 'TextIO': pass class io: """Wrapper namespace for IO generic classes.""" __all__ = ['IO', 'TextIO', 'BinaryIO'] IO = IO TextIO = TextIO BinaryIO = BinaryIO io.__name__ = __name__ + '.io' sys.modules[io.__name__] = io Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), lambda p: p.pattern) Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')), lambda m: m.re.pattern) class re: """Wrapper namespace for re type aliases.""" __all__ = ['Pattern', 'Match'] Pattern = Pattern Match = Match re.__name__ = __name__ + '.re' sys.modules[re.__name__] = re
80,274
2,413
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/__init__.py
"""Core XML support for Python. This package contains four sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. etree -- The ElementTree XML library. This is a subset of the full ElementTree XML release. """ __all__ = ["dom", "parsers", "sax", "etree"]
558
22
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/parsers/expat.py
"""Interface to the Expat non-validating XML parser.""" __all__ = [ 'EXPAT_VERSION', 'ErrorString', 'ExpatError', 'ParserCreate', 'XMLParserType', 'XML_PARAM_ENTITY_PARSING_ALWAYS', 'XML_PARAM_ENTITY_PARSING_NEVER', 'XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE', 'error', 'errors', 'expat_CAPI', 'features', 'model', 'native_encoding', 'sys', 'version_info', ] import sys from pyexpat import EXPAT_VERSION, ErrorString, ExpatError, ParserCreate, XMLParserType, XML_PARAM_ENTITY_PARSING_ALWAYS, XML_PARAM_ENTITY_PARSING_NEVER, XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE, error, errors, expat_CAPI, features, model, native_encoding, version_info # provide pyexpat submodules as xml.parsers.expat submodules sys.modules['xml.parsers.expat.model'] = model sys.modules['xml.parsers.expat.errors'] = errors
868
29
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/parsers/__init__.py
"""Python interfaces to XML parsers. This package contains one module: expat -- Python wrapper for James Clark's Expat parser, with namespace support. """
167
9
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/sax/xmlreader.py
"""An XML Reader is the SAX 2 name for an XML parser. XML Parsers should be based on this code. """ from . import handler from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException # ===== XMLREADER ===== class XMLReader: """Interface for reading an XML document using callbacks. XMLReader is the interface that an XML parser's SAX2 driver must implement. This interface allows an application to set and query features and properties in the parser, to register event handlers for document processing, and to initiate a document parse. All SAX interfaces are assumed to be synchronous: the parse methods must not return until parsing is complete, and readers must wait for an event-handler callback to return before reporting the next event.""" def __init__(self): self._cont_handler = handler.ContentHandler() self._dtd_handler = handler.DTDHandler() self._ent_handler = handler.EntityResolver() self._err_handler = handler.ErrorHandler() def parse(self, source): "Parse an XML document from a system identifier or an InputSource." raise NotImplementedError("This method must be implemented!") def getContentHandler(self): "Returns the current ContentHandler." return self._cont_handler def setContentHandler(self, handler): "Registers a new object to receive document content events." self._cont_handler = handler def getDTDHandler(self): "Returns the current DTD handler." return self._dtd_handler def setDTDHandler(self, handler): "Register an object to receive basic DTD-related events." self._dtd_handler = handler def getEntityResolver(self): "Returns the current EntityResolver." return self._ent_handler def setEntityResolver(self, resolver): "Register an object to resolve external entities." self._ent_handler = resolver def getErrorHandler(self): "Returns the current ErrorHandler." return self._err_handler def setErrorHandler(self, handler): "Register an object to receive error-message events." self._err_handler = handler def setLocale(self, locale): """Allow an application to set the locale for errors and warnings. SAX parsers are not required to provide localization for errors and warnings; if they cannot support the requested locale, however, they must raise a SAX exception. Applications may request a locale change in the middle of a parse.""" raise SAXNotSupportedException("Locale support not implemented") def getFeature(self, name): "Looks up and returns the state of a SAX2 feature." raise SAXNotRecognizedException("Feature '%s' not recognized" % name) def setFeature(self, name, state): "Sets the state of a SAX2 feature." raise SAXNotRecognizedException("Feature '%s' not recognized" % name) def getProperty(self, name): "Looks up and returns the value of a SAX2 property." raise SAXNotRecognizedException("Property '%s' not recognized" % name) def setProperty(self, name, value): "Sets the value of a SAX2 property." raise SAXNotRecognizedException("Property '%s' not recognized" % name) class IncrementalParser(XMLReader): """This interface adds three extra methods to the XMLReader interface that allow XML parsers to support incremental parsing. Support for this interface is optional, since not all underlying XML parsers support this functionality. When the parser is instantiated it is ready to begin accepting data from the feed method immediately. After parsing has been finished with a call to close the reset method must be called to make the parser ready to accept new data, either from feed or using the parse method. Note that these methods must _not_ be called during parsing, that is, after parse has been called and before it returns. By default, the class also implements the parse method of the XMLReader interface using the feed, close and reset methods of the IncrementalParser interface as a convenience to SAX 2.0 driver writers.""" def __init__(self, bufsize=2**16): self._bufsize = bufsize XMLReader.__init__(self) def parse(self, source): from . import saxutils source = saxutils.prepare_input_source(source) self.prepareParser(source) file = source.getCharacterStream() if file is None: file = source.getByteStream() buffer = file.read(self._bufsize) while buffer: self.feed(buffer) buffer = file.read(self._bufsize) self.close() def feed(self, data): """This method gives the raw XML data in the data parameter to the parser and makes it parse the data, emitting the corresponding events. It is allowed for XML constructs to be split across several calls to feed. feed may raise SAXException.""" raise NotImplementedError("This method must be implemented!") def prepareParser(self, source): """This method is called by the parse implementation to allow the SAX 2.0 driver to prepare itself for parsing.""" raise NotImplementedError("prepareParser must be overridden!") def close(self): """This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer. The parser will not be ready to parse another document until the reset method has been called. close may raise SAXException.""" raise NotImplementedError("This method must be implemented!") def reset(self): """This method is called after close has been called to reset the parser so that it is ready to parse new documents. The results of calling parse or feed after close without calling reset are undefined.""" raise NotImplementedError("This method must be implemented!") # ===== LOCATOR ===== class Locator: """Interface for associating a SAX event with a document location. A locator object will return valid results only during calls to DocumentHandler methods; at any other time, the results are unpredictable.""" def getColumnNumber(self): "Return the column number where the current event ends." return -1 def getLineNumber(self): "Return the line number where the current event ends." return -1 def getPublicId(self): "Return the public identifier for the current event." return None def getSystemId(self): "Return the system identifier for the current event." return None # ===== INPUTSOURCE ===== class InputSource: """Encapsulation of the information needed by the XMLReader to read entities. This class may include information about the public identifier, system identifier, byte stream (possibly with character encoding information) and/or the character stream of an entity. Applications will create objects of this class for use in the XMLReader.parse method and for returning from EntityResolver.resolveEntity. An InputSource belongs to the application, the XMLReader is not allowed to modify InputSource objects passed to it from the application, although it may make copies and modify those.""" def __init__(self, system_id = None): self.__system_id = system_id self.__public_id = None self.__encoding = None self.__bytefile = None self.__charfile = None def setPublicId(self, public_id): "Sets the public identifier of this InputSource." self.__public_id = public_id def getPublicId(self): "Returns the public identifier of this InputSource." return self.__public_id def setSystemId(self, system_id): "Sets the system identifier of this InputSource." self.__system_id = system_id def getSystemId(self): "Returns the system identifier of this InputSource." return self.__system_id def setEncoding(self, encoding): """Sets the character encoding of this InputSource. The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML recommendation). The encoding attribute of the InputSource is ignored if the InputSource also contains a character stream.""" self.__encoding = encoding def getEncoding(self): "Get the character encoding of this InputSource." return self.__encoding def setByteStream(self, bytefile): """Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.""" self.__bytefile = bytefile def getByteStream(self): """Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown.""" return self.__bytefile def setCharacterStream(self, charfile): """Set the character stream for this input source. (The stream must be a Python 2.0 Unicode-wrapped file-like that performs conversion to Unicode strings.) If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier.""" self.__charfile = charfile def getCharacterStream(self): "Get the character stream for this input source." return self.__charfile # ===== ATTRIBUTESIMPL ===== class AttributesImpl: def __init__(self, attrs): """Non-NS-aware implementation. attrs should be of the form {name : value}.""" self._attrs = attrs def getLength(self): return len(self._attrs) def getType(self, name): return "CDATA" def getValue(self, name): return self._attrs[name] def getValueByQName(self, name): return self._attrs[name] def getNameByQName(self, name): if name not in self._attrs: raise KeyError(name) return name def getQNameByName(self, name): if name not in self._attrs: raise KeyError(name) return name def getNames(self): return list(self._attrs.keys()) def getQNames(self): return list(self._attrs.keys()) def __len__(self): return len(self._attrs) def __getitem__(self, name): return self._attrs[name] def keys(self): return list(self._attrs.keys()) def __contains__(self, name): return name in self._attrs def get(self, name, alternative=None): return self._attrs.get(name, alternative) def copy(self): return self.__class__(self._attrs) def items(self): return list(self._attrs.items()) def values(self): return list(self._attrs.values()) # ===== ATTRIBUTESNSIMPL ===== class AttributesNSImpl(AttributesImpl): def __init__(self, attrs, qnames): """NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.""" self._attrs = attrs self._qnames = qnames def getValueByQName(self, name): for (nsname, qname) in self._qnames.items(): if qname == name: return self._attrs[nsname] raise KeyError(name) def getNameByQName(self, name): for (nsname, qname) in self._qnames.items(): if qname == name: return nsname raise KeyError(name) def getQNameByName(self, name): return self._qnames[name] def getQNames(self): return list(self._qnames.values()) def copy(self): return self.__class__(self._attrs, self._qnames) def _test(): XMLReader() IncrementalParser() Locator() if __name__ == "__main__": _test()
12,684
381
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/sax/handler.py
""" This module contains the core classes of version 2.0 of SAX for Python. This file provides only default classes with absolutely minimum functionality, from which drivers and applications can be subclassed. Many of these classes are empty and are included only as documentation of the interfaces. $Id$ """ version = '2.0beta' #============================================================================ # # HANDLER INTERFACES # #============================================================================ # ===== ERRORHANDLER ===== class ErrorHandler: """Basic interface for SAX error handlers. If you create an object that implements this interface, then register the object with your XMLReader, the parser will call the methods in your object to report all warnings and errors. There are three levels of errors available: warnings, (possibly) recoverable errors, and unrecoverable errors. All methods take a SAXParseException as the only parameter.""" def error(self, exception): "Handle a recoverable error." raise exception def fatalError(self, exception): "Handle a non-recoverable error." raise exception def warning(self, exception): "Handle a warning." print(exception) # ===== CONTENTHANDLER ===== class ContentHandler: """Interface for receiving logical document content events. This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface mirrors the order of the information in the document.""" def __init__(self): self._locator = None def setDocumentLocator(self, locator): """Called by the parser to give the application a locator for locating the origin of document events. SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the DocumentHandler interface. The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application's business rules). The information returned by the locator is probably not sufficient for use with a search engine. Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.""" self._locator = locator def startDocument(self): """Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).""" def endDocument(self): """Receive notification of the end of a document. The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input.""" def startPrefixMapping(self, prefix, uri): """Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary. Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed.""" def endPrefixMapping(self, prefix): """End the scope of a prefix-URI mapping. See startPrefixMapping for details. This event will always occur after the corresponding endElement event, but the order of endPrefixMapping events is not otherwise guaranteed.""" def startElement(self, name, attrs): """Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an instance of the Attributes class containing the attributes of the element.""" def endElement(self, name): """Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement event.""" def startElementNS(self, name, qname, attrs): """Signals the start of an element in namespace mode. The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter the raw XML 1.0 name used in the source document, and the attrs parameter holds an instance of the Attributes class containing the attributes of the element. The uri part of the name tuple is None for elements which have no namespace.""" def endElementNS(self, name, qname): """Signals the end of an element in namespace mode. The name parameter contains the name of the element type, just as with the startElementNS event.""" def characters(self, content): """Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.""" def ignorableWhitespace(self, whitespace): """Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.""" def processingInstruction(self, target, data): """Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.""" def skippedEntity(self, name): """Receive notification of a skipped entity. The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the http://xml.org/sax/features/external-general-entities and the http://xml.org/sax/features/external-parameter-entities properties.""" # ===== DTDHandler ===== class DTDHandler: """Handle DTD events. This interface specifies only those DTD events required for basic parsing (unparsed entities and attributes).""" def notationDecl(self, name, publicId, systemId): "Handle a notation declaration event." def unparsedEntityDecl(self, name, publicId, systemId, ndata): "Handle an unparsed entity declaration event." # ===== ENTITYRESOLVER ===== class EntityResolver: """Basic interface for resolving entities. If you create an object implementing this interface, then register the object with your Parser, the parser will call the method in your object to resolve all external entities. Note that DefaultHandler implements this interface with the default behaviour.""" def resolveEntity(self, publicId, systemId): """Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from.""" return systemId #============================================================================ # # CORE FEATURES # #============================================================================ feature_namespaces = "http://xml.org/sax/features/namespaces" # true: Perform Namespace processing (default). # false: Optionally do not perform Namespace processing # (implies namespace-prefixes). # access: (parsing) read-only; (not parsing) read/write feature_namespace_prefixes = "http://xml.org/sax/features/namespace-prefixes" # true: Report the original prefixed names and attributes used for Namespace # declarations. # false: Do not report attributes used for Namespace declarations, and # optionally do not report original prefixed names (default). # access: (parsing) read-only; (not parsing) read/write feature_string_interning = "http://xml.org/sax/features/string-interning" # true: All element names, prefixes, attribute names, Namespace URIs, and # local names are interned using the built-in intern function. # false: Names are not necessarily interned, although they may be (default). # access: (parsing) read-only; (not parsing) read/write feature_validation = "http://xml.org/sax/features/validation" # true: Report all validation errors (implies external-general-entities and # external-parameter-entities). # false: Do not report validation errors. # access: (parsing) read-only; (not parsing) read/write feature_external_ges = "http://xml.org/sax/features/external-general-entities" # true: Include all external general (text) entities. # false: Do not include external general entities. # access: (parsing) read-only; (not parsing) read/write feature_external_pes = "http://xml.org/sax/features/external-parameter-entities" # true: Include all external parameter entities, including the external # DTD subset. # false: Do not include any external parameter entities, even the external # DTD subset. # access: (parsing) read-only; (not parsing) read/write all_features = [feature_namespaces, feature_namespace_prefixes, feature_string_interning, feature_validation, feature_external_ges, feature_external_pes] #============================================================================ # # CORE PROPERTIES # #============================================================================ property_lexical_handler = "http://xml.org/sax/properties/lexical-handler" # data type: xml.sax.sax2lib.LexicalHandler # description: An optional extension handler for lexical events like comments. # access: read/write property_declaration_handler = "http://xml.org/sax/properties/declaration-handler" # data type: xml.sax.sax2lib.DeclHandler # description: An optional extension handler for DTD-related events other # than notations and unparsed entities. # access: read/write property_dom_node = "http://xml.org/sax/properties/dom-node" # data type: org.w3c.dom.Node # description: When parsing, the current DOM node being visited if this is # a DOM iterator; when not parsing, the root DOM node for # iteration. # access: (parsing) read-only; (not parsing) read/write property_xml_string = "http://xml.org/sax/properties/xml-string" # data type: String # description: The literal string of characters that was the source for # the current event. # access: read-only property_encoding = "http://www.python.org/sax/properties/encoding" # data type: String # description: The name of the encoding to assume for input data. # access: write: set the encoding, e.g. established by a higher-level # protocol. May change during parsing (e.g. after # processing a META tag) # read: return the current encoding (possibly established through # auto-detection. # initial value: UTF-8 # property_interning_dict = "http://www.python.org/sax/properties/interning-dict" # data type: Dictionary # description: The dictionary used to intern common strings in the document # access: write: Request that the parser uses a specific dictionary, to # allow interning across different documents # read: return the current interning dictionary, or None # all_properties = [property_lexical_handler, property_dom_node, property_declaration_handler, property_xml_string, property_encoding, property_interning_dict]
13,922
343
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/sax/saxutils.py
"""\ A library of useful helper classes to the SAX classes, for the convenience of application and driver writers. """ import os, urllib.parse, urllib.request import io import codecs from . import handler from . import xmlreader def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s def escape(data, entities={}): """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ # must do ampersand first data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") if entities: data = __dict_replace(data, entities) return data def unescape(data, entities={}): """Unescape &amp;, &lt;, and &gt; in a string of data. You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ data = data.replace("&lt;", "<") data = data.replace("&gt;", ">") if entities: data = __dict_replace(data, entities) # must do ampersand last return data.replace("&amp;", "&") def quoteattr(data, entities={}): """Escape and quote an attribute value. Escape &, <, and > in a string of data, then quote it for use as an attribute value. The \" character will be escaped as well, if necessary. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ entities = entities.copy() entities.update({'\n': '&#10;', '\r': '&#13;', '\t':'&#9;'}) data = escape(data, entities) if '"' in data: if "'" in data: data = '"%s"' % data.replace('"', "&quot;") else: data = "'%s'" % data else: data = '"%s"' % data return data def _gettextwriter(out, encoding): if out is None: import sys return sys.stdout if isinstance(out, io.TextIOBase): # use a text writer as is return out if isinstance(out, (codecs.StreamWriter, codecs.StreamReaderWriter)): # use a codecs stream writer as is return out # wrap a binary writer with TextIOWrapper if isinstance(out, io.RawIOBase): # Keep the original file open when the TextIOWrapper is # destroyed class _wrapper: __class__ = out.__class__ def __getattr__(self, name): return getattr(out, name) buffer = _wrapper() buffer.close = lambda: None else: # This is to handle passed objects that aren't in the # IOBase hierarchy, but just have a write method buffer = io.BufferedIOBase() buffer.writable = lambda: True buffer.write = out.write try: # TextIOWrapper uses this methods to determine # if BOM (for UTF-16, etc) should be added buffer.seekable = out.seekable buffer.tell = out.tell except AttributeError: pass return io.TextIOWrapper(buffer, encoding=encoding, errors='xmlcharrefreplace', newline='\n', write_through=True) class XMLGenerator(handler.ContentHandler): def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False): handler.ContentHandler.__init__(self) out = _gettextwriter(out, encoding) self._write = out.write self._flush = out.flush self._ns_contexts = [{}] # contains uri -> prefix dicts self._current_context = self._ns_contexts[-1] self._undeclared_ns_maps = [] self._encoding = encoding self._short_empty_elements = short_empty_elements self._pending_start_element = False def _qname(self, name): """Builds a qualified name from a (ns_url, localname) pair""" if name[0]: # Per http://www.w3.org/XML/1998/namespace, The 'xml' prefix is # bound by definition to http://www.w3.org/XML/1998/namespace. It # does not need to be declared and will not usually be found in # self._current_context. if 'http://www.w3.org/XML/1998/namespace' == name[0]: return 'xml:' + name[1] # The name is in a non-empty namespace prefix = self._current_context[name[0]] if prefix: # If it is not the default namespace, prepend the prefix return prefix + ":" + name[1] # Return the unqualified name return name[1] def _finish_pending_start_element(self,endElement=False): if self._pending_start_element: self._write('>') self._pending_start_element = False # ContentHandler methods def startDocument(self): self._write('<?xml version="1.0" encoding="%s"?>\n' % self._encoding) def endDocument(self): self._flush() def startPrefixMapping(self, prefix, uri): self._ns_contexts.append(self._current_context.copy()) self._current_context[uri] = prefix self._undeclared_ns_maps.append((prefix, uri)) def endPrefixMapping(self, prefix): self._current_context = self._ns_contexts[-1] del self._ns_contexts[-1] def startElement(self, name, attrs): self._finish_pending_start_element() self._write('<' + name) for (name, value) in attrs.items(): self._write(' %s=%s' % (name, quoteattr(value))) if self._short_empty_elements: self._pending_start_element = True else: self._write(">") def endElement(self, name): if self._pending_start_element: self._write('/>') self._pending_start_element = False else: self._write('</%s>' % name) def startElementNS(self, name, qname, attrs): self._finish_pending_start_element() self._write('<' + self._qname(name)) for prefix, uri in self._undeclared_ns_maps: if prefix: self._write(' xmlns:%s="%s"' % (prefix, uri)) else: self._write(' xmlns="%s"' % uri) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): self._write(' %s=%s' % (self._qname(name), quoteattr(value))) if self._short_empty_elements: self._pending_start_element = True else: self._write(">") def endElementNS(self, name, qname): if self._pending_start_element: self._write('/>') self._pending_start_element = False else: self._write('</%s>' % self._qname(name)) def characters(self, content): if content: self._finish_pending_start_element() if not isinstance(content, str): content = str(content, self._encoding) self._write(escape(content)) def ignorableWhitespace(self, content): if content: self._finish_pending_start_element() if not isinstance(content, str): content = str(content, self._encoding) self._write(content) def processingInstruction(self, target, data): self._finish_pending_start_element() self._write('<?%s %s?>' % (target, data)) class XMLFilterBase(xmlreader.XMLReader): """This class is designed to sit between an XMLReader and the client application's event handlers. By default, it does nothing but pass requests up to the reader and events on to the handlers unmodified, but subclasses can override specific methods to modify the event stream or the configuration requests as they pass through.""" def __init__(self, parent = None): xmlreader.XMLReader.__init__(self) self._parent = parent # ErrorHandler methods def error(self, exception): self._err_handler.error(exception) def fatalError(self, exception): self._err_handler.fatalError(exception) def warning(self, exception): self._err_handler.warning(exception) # ContentHandler methods def setDocumentLocator(self, locator): self._cont_handler.setDocumentLocator(locator) def startDocument(self): self._cont_handler.startDocument() def endDocument(self): self._cont_handler.endDocument() def startPrefixMapping(self, prefix, uri): self._cont_handler.startPrefixMapping(prefix, uri) def endPrefixMapping(self, prefix): self._cont_handler.endPrefixMapping(prefix) def startElement(self, name, attrs): self._cont_handler.startElement(name, attrs) def endElement(self, name): self._cont_handler.endElement(name) def startElementNS(self, name, qname, attrs): self._cont_handler.startElementNS(name, qname, attrs) def endElementNS(self, name, qname): self._cont_handler.endElementNS(name, qname) def characters(self, content): self._cont_handler.characters(content) def ignorableWhitespace(self, chars): self._cont_handler.ignorableWhitespace(chars) def processingInstruction(self, target, data): self._cont_handler.processingInstruction(target, data) def skippedEntity(self, name): self._cont_handler.skippedEntity(name) # DTDHandler methods def notationDecl(self, name, publicId, systemId): self._dtd_handler.notationDecl(name, publicId, systemId) def unparsedEntityDecl(self, name, publicId, systemId, ndata): self._dtd_handler.unparsedEntityDecl(name, publicId, systemId, ndata) # EntityResolver methods def resolveEntity(self, publicId, systemId): return self._ent_handler.resolveEntity(publicId, systemId) # XMLReader methods def parse(self, source): self._parent.setContentHandler(self) self._parent.setErrorHandler(self) self._parent.setEntityResolver(self) self._parent.setDTDHandler(self) self._parent.parse(source) def setLocale(self, locale): self._parent.setLocale(locale) def getFeature(self, name): return self._parent.getFeature(name) def setFeature(self, name, state): self._parent.setFeature(name, state) def getProperty(self, name): return self._parent.getProperty(name) def setProperty(self, name, value): self._parent.setProperty(name, value) # XMLFilter methods def getParent(self): return self._parent def setParent(self, parent): self._parent = parent # --- Utility functions def prepare_input_source(source, base=""): """This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.""" if isinstance(source, str): source = xmlreader.InputSource(source) elif hasattr(source, "read"): f = source source = xmlreader.InputSource() if isinstance(f.read(0), str): source.setCharacterStream(f) else: source.setByteStream(f) if hasattr(f, "name") and isinstance(f.name, str): source.setSystemId(f.name) if source.getCharacterStream() is None and source.getByteStream() is None: sysid = source.getSystemId() basehead = os.path.dirname(os.path.normpath(base)) sysidfilename = os.path.join(basehead, sysid) if os.path.isfile(sysidfilename): source.setSystemId(sysidfilename) f = open(sysidfilename, "rb") else: source.setSystemId(urllib.parse.urljoin(base, sysid)) f = urllib.request.urlopen(source.getSystemId()) source.setByteStream(f) return source
12,205
369
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/sax/_exceptions.py
"""Different kinds of SAX Exceptions""" # ===== SAXEXCEPTION ===== class SAXException(Exception): """Encapsulate an XML error or warning. This class can contain basic error or warning information from either the XML parser or the application: you can subclass it to provide additional functionality, or to add localization. Note that although you will receive a SAXException as the argument to the handlers in the ErrorHandler interface, you are not actually required to raise the exception; instead, you can simply read the information in it.""" def __init__(self, msg, exception=None): """Creates an exception. The message is required, but the exception is optional.""" self._msg = msg self._exception = exception Exception.__init__(self, msg) def getMessage(self): "Return a message for this exception." return self._msg def getException(self): "Return the embedded exception, or None if there was none." return self._exception def __str__(self): "Create a string representation of the exception." return self._msg def __getitem__(self, ix): """Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.""" raise AttributeError("__getitem__") # ===== SAXPARSEEXCEPTION ===== class SAXParseException(SAXException): """Encapsulate an XML parse error or warning. This exception will include information for locating the error in the original XML document. Note that although the application will receive a SAXParseException as the argument to the handlers in the ErrorHandler interface, the application is not actually required to raise the exception; instead, it can simply read the information in it and take a different action. Since this exception is a subclass of SAXException, it inherits the ability to wrap another exception.""" def __init__(self, msg, exception, locator): "Creates the exception. The exception parameter is allowed to be None." SAXException.__init__(self, msg, exception) self._locator = locator # We need to cache this stuff at construction time. # If this exception is raised, the objects through which we must # traverse to get this information may be deleted by the time # it gets caught. self._systemId = self._locator.getSystemId() self._colnum = self._locator.getColumnNumber() self._linenum = self._locator.getLineNumber() def getColumnNumber(self): """The column number of the end of the text where the exception occurred.""" return self._colnum def getLineNumber(self): "The line number of the end of the text where the exception occurred." return self._linenum def getPublicId(self): "Get the public identifier of the entity where the exception occurred." return self._locator.getPublicId() def getSystemId(self): "Get the system identifier of the entity where the exception occurred." return self._systemId def __str__(self): "Create a string representation of the exception." sysid = self.getSystemId() if sysid is None: sysid = "<unknown>" linenum = self.getLineNumber() if linenum is None: linenum = "?" colnum = self.getColumnNumber() if colnum is None: colnum = "?" return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg) # ===== SAXNOTRECOGNIZEDEXCEPTION ===== class SAXNotRecognizedException(SAXException): """Exception class for an unrecognized identifier. An XMLReader will raise this exception when it is confronted with an unrecognized feature or property. SAX applications and extensions may use this class for similar purposes.""" # ===== SAXNOTSUPPORTEDEXCEPTION ===== class SAXNotSupportedException(SAXException): """Exception class for an unsupported operation. An XMLReader will raise this exception when a service it cannot perform is requested (specifically setting a state or value). SAX applications and extensions may use this class for similar purposes.""" # ===== SAXNOTSUPPORTEDEXCEPTION ===== class SAXReaderNotAvailable(SAXNotSupportedException): """Exception class for a missing driver. An XMLReader module (driver) should raise this exception when it is first imported, e.g. when a support module cannot be imported. It also may be raised during parsing, e.g. if executing an external program is not permitted."""
4,699
128
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/sax/__init__.py
"""Simple API for XML (SAX) implementation for Python. This module provides an implementation of the SAX 2 interface; information about the Java version of the interface can be found at http://www.megginson.com/SAX/. The Python version of the interface is documented at <...>. This package contains the following modules: handler -- Base classes and constants which define the SAX 2 API for the 'client-side' of SAX for Python. saxutils -- Implementation of the convenience classes commonly used to work with SAX. xmlreader -- Base classes and constants which define the SAX 2 API for the parsers used with SAX for Python. expatreader -- Driver that allows use of the Expat parser with SAX. """ from .xmlreader import InputSource from .handler import ContentHandler, ErrorHandler from ._exceptions import SAXException, SAXNotRecognizedException, \ SAXParseException, SAXNotSupportedException, \ SAXReaderNotAvailable if __name__ == 'PYOBJ.COM': import xml.sax def parse(source, handler, errorHandler=ErrorHandler()): parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) parser.parse(source) def parseString(string, handler, errorHandler=ErrorHandler()): import io if errorHandler is None: errorHandler = ErrorHandler() parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) inpsrc = InputSource() if isinstance(string, str): inpsrc.setCharacterStream(io.StringIO(string)) else: inpsrc.setByteStream(io.BytesIO(string)) parser.parse(inpsrc) # this is the parser list used by the make_parser function if no # alternatives are given as parameters to the function default_parser_list = ["xml.sax.expatreader"] # tell modulefinder that importing sax potentially imports expatreader _false = 0 if _false: import xml.sax.expatreader import os, sys if not sys.flags.ignore_environment and "PY_SAX_PARSER" in os.environ: default_parser_list = os.environ["PY_SAX_PARSER"].split(",") del os _key = "python.xml.sax.parser" if sys.platform[:4] == "java" and sys.registry.containsKey(_key): default_parser_list = sys.registry.getProperty(_key).split(",") def make_parser(parser_list = []): """Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the list created by doing parser_list + default_parser_list. The lists must contain the names of Python modules containing both a SAX parser and a create_parser function.""" for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) except ImportError as e: import sys if parser_name in sys.modules: # The parser module was found, but importing it # failed unexpectedly, pass this exception through raise except SAXReaderNotAvailable: # The parser module detected that it won't work properly, # so try the next one pass raise SAXReaderNotAvailable("No parsers found", None) # --- Internal utility methods used by make_parser if sys.platform[ : 4] == "java": def _create_parser(parser_name): # from org.python.core import imp drv_module = imp.importName(parser_name, 0, globals()) return drv_module.create_parser() else: def _create_parser(parser_name): drv_module = __import__(parser_name,{},{},['create_parser']) return drv_module.create_parser() del sys
3,679
110
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/sax/expatreader.py
""" SAX driver for the pyexpat C module. This driver works with pyexpat.__version__ == '2.22'. """ version = "0.20" from xml.sax._exceptions import * from xml.sax.handler import feature_validation, feature_namespaces from xml.sax.handler import feature_namespace_prefixes from xml.sax.handler import feature_external_ges, feature_external_pes from xml.sax.handler import feature_string_interning from xml.sax.handler import property_xml_string, property_interning_dict # xml.parsers.expat does not raise ImportError in Jython import sys if sys.platform[:4] == "java": raise SAXReaderNotAvailable("expat not available in Java", None) del sys try: from xml.parsers import expat except ImportError: raise SAXReaderNotAvailable("expat not supported", None) else: if not hasattr(expat, "ParserCreate"): raise SAXReaderNotAvailable("expat not supported", None) from xml.sax import xmlreader, saxutils, handler AttributesImpl = xmlreader.AttributesImpl AttributesNSImpl = xmlreader.AttributesNSImpl # If we're using a sufficiently recent version of Python, we can use # weak references to avoid cycles between the parser and content # handler, otherwise we'll just have to pretend. try: import _weakref except ImportError: def _mkproxy(o): return o else: import weakref _mkproxy = weakref.proxy del weakref, _weakref class _ClosedParser: pass # --- ExpatLocator class ExpatLocator(xmlreader.Locator): """Locator for use with the ExpatParser class. This uses a weak reference to the parser object to avoid creating a circular reference between the parser and the content handler. """ def __init__(self, parser): self._ref = _mkproxy(parser) def getColumnNumber(self): parser = self._ref if parser._parser is None: return None return parser._parser.ErrorColumnNumber def getLineNumber(self): parser = self._ref if parser._parser is None: return 1 return parser._parser.ErrorLineNumber def getPublicId(self): parser = self._ref if parser is None: return None return parser._source.getPublicId() def getSystemId(self): parser = self._ref if parser is None: return None return parser._source.getSystemId() # --- ExpatParser class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): """SAX driver for the pyexpat C module.""" def __init__(self, namespaceHandling=0, bufsize=2**16-20): xmlreader.IncrementalParser.__init__(self, bufsize) self._source = xmlreader.InputSource() self._parser = None self._namespaces = namespaceHandling self._lex_handler_prop = None self._parsing = 0 self._entity_stack = [] self._external_ges = 0 self._interning = None # XMLReader methods def parse(self, source): "Parse an XML document from a URL or an InputSource." source = saxutils.prepare_input_source(source) self._source = source try: self.reset() self._cont_handler.setDocumentLocator(ExpatLocator(self)) xmlreader.IncrementalParser.parse(self, source) except: # bpo-30264: Close the source on error to not leak resources: # xml.sax.parse() doesn't give access to the underlying parser # to the caller self._close_source() raise def prepareParser(self, source): if source.getSystemId() is not None: self._parser.SetBase(source.getSystemId()) # Redefined setContentHandler to allow changing handlers during parsing def setContentHandler(self, handler): xmlreader.IncrementalParser.setContentHandler(self, handler) if self._parsing: self._reset_cont_handler() def getFeature(self, name): if name == feature_namespaces: return self._namespaces elif name == feature_string_interning: return self._interning is not None elif name in (feature_validation, feature_external_pes, feature_namespace_prefixes): return 0 elif name == feature_external_ges: return self._external_ges raise SAXNotRecognizedException("Feature '%s' not recognized" % name) def setFeature(self, name, state): if self._parsing: raise SAXNotSupportedException("Cannot set features while parsing") if name == feature_namespaces: self._namespaces = state elif name == feature_external_ges: self._external_ges = state elif name == feature_string_interning: if state: if self._interning is None: self._interning = {} else: self._interning = None elif name == feature_validation: if state: raise SAXNotSupportedException( "expat does not support validation") elif name == feature_external_pes: if state: raise SAXNotSupportedException( "expat does not read external parameter entities") elif name == feature_namespace_prefixes: if state: raise SAXNotSupportedException( "expat does not report namespace prefixes") else: raise SAXNotRecognizedException( "Feature '%s' not recognized" % name) def getProperty(self, name): if name == handler.property_lexical_handler: return self._lex_handler_prop elif name == property_interning_dict: return self._interning elif name == property_xml_string: if self._parser: if hasattr(self._parser, "GetInputContext"): return self._parser.GetInputContext() else: raise SAXNotRecognizedException( "This version of expat does not support getting" " the XML string") else: raise SAXNotSupportedException( "XML string cannot be returned when not parsing") raise SAXNotRecognizedException("Property '%s' not recognized" % name) def setProperty(self, name, value): if name == handler.property_lexical_handler: self._lex_handler_prop = value if self._parsing: self._reset_lex_handler_prop() elif name == property_interning_dict: self._interning = value elif name == property_xml_string: raise SAXNotSupportedException("Property '%s' cannot be set" % name) else: raise SAXNotRecognizedException("Property '%s' not recognized" % name) # IncrementalParser methods def feed(self, data, isFinal = 0): if not self._parsing: self.reset() self._parsing = 1 self._cont_handler.startDocument() try: # The isFinal parameter is internal to the expat reader. # If it is set to true, expat will check validity of the entire # document. When feeding chunks, they are not normally final - # except when invoked from close. self._parser.Parse(data, isFinal) except expat.error as e: exc = SAXParseException(expat.ErrorString(e.code), e, self) # FIXME: when to invoke error()? self._err_handler.fatalError(exc) def _close_source(self): source = self._source try: file = source.getCharacterStream() if file is not None: file.close() finally: file = source.getByteStream() if file is not None: file.close() def close(self): if (self._entity_stack or self._parser is None or isinstance(self._parser, _ClosedParser)): # If we are completing an external entity, do nothing here return try: self.feed("", isFinal = 1) self._cont_handler.endDocument() self._parsing = 0 # break cycle created by expat handlers pointing to our methods self._parser = None finally: self._parsing = 0 if self._parser is not None: # Keep ErrorColumnNumber and ErrorLineNumber after closing. parser = _ClosedParser() parser.ErrorColumnNumber = self._parser.ErrorColumnNumber parser.ErrorLineNumber = self._parser.ErrorLineNumber self._parser = parser self._close_source() def _reset_cont_handler(self): self._parser.ProcessingInstructionHandler = \ self._cont_handler.processingInstruction self._parser.CharacterDataHandler = self._cont_handler.characters def _reset_lex_handler_prop(self): lex = self._lex_handler_prop parser = self._parser if lex is None: parser.CommentHandler = None parser.StartCdataSectionHandler = None parser.EndCdataSectionHandler = None parser.StartDoctypeDeclHandler = None parser.EndDoctypeDeclHandler = None else: parser.CommentHandler = lex.comment parser.StartCdataSectionHandler = lex.startCDATA parser.EndCdataSectionHandler = lex.endCDATA parser.StartDoctypeDeclHandler = self.start_doctype_decl parser.EndDoctypeDeclHandler = lex.endDTD def reset(self): if self._namespaces: self._parser = expat.ParserCreate(self._source.getEncoding(), " ", intern=self._interning) self._parser.namespace_prefixes = 1 self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate(self._source.getEncoding(), intern = self._interning) self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler = self.end_element self._reset_cont_handler() self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl self._parser.NotationDeclHandler = self.notation_decl self._parser.StartNamespaceDeclHandler = self.start_namespace_decl self._parser.EndNamespaceDeclHandler = self.end_namespace_decl self._decl_handler_prop = None if self._lex_handler_prop: self._reset_lex_handler_prop() # self._parser.DefaultHandler = # self._parser.DefaultHandlerExpand = # self._parser.NotStandaloneHandler = self._parser.ExternalEntityRefHandler = self.external_entity_ref try: self._parser.SkippedEntityHandler = self.skipped_entity_handler except AttributeError: # This pyexpat does not support SkippedEntity pass self._parser.SetParamEntityParsing( expat.XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) self._parsing = 0 self._entity_stack = [] # Locator methods def getColumnNumber(self): if self._parser is None: return None return self._parser.ErrorColumnNumber def getLineNumber(self): if self._parser is None: return 1 return self._parser.ErrorLineNumber def getPublicId(self): return self._source.getPublicId() def getSystemId(self): return self._source.getSystemId() # event handlers def start_element(self, name, attrs): self._cont_handler.startElement(name, AttributesImpl(attrs)) def end_element(self, name): self._cont_handler.endElement(name) def start_element_ns(self, name, attrs): pair = name.split() if len(pair) == 1: # no namespace pair = (None, name) elif len(pair) == 3: pair = pair[0], pair[1] else: # default namespace pair = tuple(pair) newattrs = {} qnames = {} for (aname, value) in attrs.items(): parts = aname.split() length = len(parts) if length == 1: # no namespace qname = aname apair = (None, aname) elif length == 3: qname = "%s:%s" % (parts[2], parts[1]) apair = parts[0], parts[1] else: # default namespace qname = parts[1] apair = tuple(parts) newattrs[apair] = value qnames[apair] = qname self._cont_handler.startElementNS(pair, None, AttributesNSImpl(newattrs, qnames)) def end_element_ns(self, name): pair = name.split() if len(pair) == 1: pair = (None, name) elif len(pair) == 3: pair = pair[0], pair[1] else: pair = tuple(pair) self._cont_handler.endElementNS(pair, None) # this is not used (call directly to ContentHandler) def processing_instruction(self, target, data): self._cont_handler.processingInstruction(target, data) # this is not used (call directly to ContentHandler) def character_data(self, data): self._cont_handler.characters(data) def start_namespace_decl(self, prefix, uri): self._cont_handler.startPrefixMapping(prefix, uri) def end_namespace_decl(self, prefix): self._cont_handler.endPrefixMapping(prefix) def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): self._lex_handler_prop.startDTD(name, pubid, sysid) def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name) def notation_decl(self, name, base, sysid, pubid): self._dtd_handler.notationDecl(name, pubid, sysid) def external_entity_ref(self, context, base, sysid, pubid): if not self._external_ges: return 1 source = self._ent_handler.resolveEntity(pubid, sysid) source = saxutils.prepare_input_source(source, self._source.getSystemId() or "") self._entity_stack.append((self._parser, self._source)) self._parser = self._parser.ExternalEntityParserCreate(context) self._source = source try: xmlreader.IncrementalParser.parse(self, source) except: return 0 # FIXME: save error info here? (self._parser, self._source) = self._entity_stack[-1] del self._entity_stack[-1] return 1 def skipped_entity_handler(self, name, is_pe): if is_pe: # The SAX spec requires to report skipped PEs with a '%' name = '%'+name self._cont_handler.skippedEntity(name) # --- def create_parser(*args, **kwargs): return ExpatParser(*args, **kwargs) # --- if __name__ == "__main__": import xml.sax.saxutils p = create_parser() p.setContentHandler(xml.sax.saxutils.XMLGenerator()) p.setErrorHandler(xml.sax.ErrorHandler()) p.parse("http://www.ibiblio.org/xml/examples/shakespeare/hamlet.xml")
15,704
447
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/etree/ElementTree.py
"""Lightweight XML support for Python. XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. This module has two classes for this purpose: 1. ElementTree represents the whole XML document as a tree and 2. Element represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level. Element is a flexible container object designed to store hierarchical data structures in memory. It can be described as a cross between a list and a dictionary. Each Element has a number of properties associated with it: 'tag' - a string containing the element's name. 'attributes' - a Python dictionary storing the element's attributes. 'text' - a string containing the element's text content. 'tail' - an optional string containing text after the element's end tag. And a number of child elements stored in a Python sequence. To create an element instance, use the Element constructor, or the SubElement factory function. You can also use the ElementTree class to wrap an element structure and convert it to and from XML. """ #--------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. # # ElementTree # Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved. # # [email protected] # http://www.pythonware.com # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2008 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- __all__ = [ # public symbols "Comment", "dump", "Element", "ElementTree", "fromstring", "fromstringlist", "iselement", "iterparse", "parse", "ParseError", "PI", "ProcessingInstruction", "QName", "SubElement", "tostring", "tostringlist", "TreeBuilder", "VERSION", "XML", "XMLID", "XMLParser", "XMLPullParser", "register_namespace", ] VERSION = "1.3.0" import sys import re import warnings import io import collections import contextlib from . import ElementPath class ParseError(SyntaxError): """An error when parsing an XML document. In addition to its exception value, a ParseError contains two extra attributes: 'code' - the specific exception code 'position' - the line and column of the error """ pass # -------------------------------------------------------------------- def iselement(element): """Return True if *element* appears to be an Element.""" return hasattr(element, 'tag') class Element: """An XML element. This class is the reference implementation of the Element interface. An element's length is its number of subelements. That means if you want to check if an element is truly empty, you should check BOTH its length AND its text attribute. The element tag, attribute names, and attribute values can be either bytes or strings. *tag* is the element name. *attrib* is an optional dictionary containing element attributes. *extra* are additional element attributes given as keyword arguments. Example form: <tag attrib>text<child/>...</tag>tail """ tag = None """The element's name.""" attrib = None """Dictionary of the element's attributes.""" text = None """ Text before first subelement. This is either a string or the value None. Note that if there is no text, this attribute may be either None or the empty string, depending on the parser. """ tail = None """ Text after this element's end tag, but before the next sibling element's start tag. This is either a string or the value None. Note that if there was no text, this attribute may be either None or an empty string, depending on the parser. """ def __init__(self, tag, attrib={}, **extra): if not isinstance(attrib, dict): raise TypeError("attrib must be dict, not %s" % ( attrib.__class__.__name__,)) attrib = attrib.copy() attrib.update(extra) self.tag = tag self.attrib = attrib self._children = [] def __repr__(self): return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self)) def makeelement(self, tag, attrib): """Create a new element with the same type. *tag* is a string containing the element name. *attrib* is a dictionary containing the element attributes. Do not call this method, use the SubElement factory function instead. """ return self.__class__(tag, attrib) def copy(self): """Return copy of current element. This creates a shallow copy. Subelements will be shared with the original tree. """ elem = self.makeelement(self.tag, self.attrib) elem.text = self.text elem.tail = self.tail elem[:] = self return elem def __len__(self): return len(self._children) def __bool__(self): warnings.warn( "The behavior of this method will change in future versions. " "Use specific 'len(elem)' or 'elem is not None' test instead.", FutureWarning, stacklevel=2 ) return len(self._children) != 0 # emulate old behaviour, for now def __getitem__(self, index): return self._children[index] def __setitem__(self, index, element): # if isinstance(index, slice): # for elt in element: # assert iselement(elt) # else: # assert iselement(element) self._children[index] = element def __delitem__(self, index): del self._children[index] def append(self, subelement): """Add *subelement* to the end of this element. The new element will appear in document order after the last existing subelement (or directly after the text, if it's the first subelement), but before the end tag for this element. """ self._assert_is_element(subelement) self._children.append(subelement) def extend(self, elements): """Append subelements from a sequence. *elements* is a sequence with zero or more elements. """ for element in elements: self._assert_is_element(element) self._children.extend(elements) def insert(self, index, subelement): """Insert *subelement* at position *index*.""" self._assert_is_element(subelement) self._children.insert(index, subelement) def _assert_is_element(self, e): # Need to refer to the actual Python implementation, not the # shadowing C implementation. if not isinstance(e, _Element_Py): raise TypeError('expected an Element, not %s' % type(e).__name__) def remove(self, subelement): """Remove matching subelement. Unlike the find methods, this method compares elements based on identity, NOT ON tag value or contents. To remove subelements by other means, the easiest way is to use a list comprehension to select what elements to keep, and then use slice assignment to update the parent element. ValueError is raised if a matching element could not be found. """ # assert iselement(element) self._children.remove(subelement) def getchildren(self): """(Deprecated) Return all subelements. Elements are returned in document order. """ warnings.warn( "This method will be removed in future versions. " "Use 'list(elem)' or iteration over elem instead.", DeprecationWarning, stacklevel=2 ) return self._children def find(self, path, namespaces=None): """Find first matching element by tag name or path. *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found. """ return ElementPath.find(self, path, namespaces) def findtext(self, path, default=None, namespaces=None): """Find text for first matching element by tag name or path. *path* is a string having either an element tag or an XPath, *default* is the value to return if the element was not found, *namespaces* is an optional mapping from namespace prefix to full name. Return text content of first matching element, or default value if none was found. Note that if an element is found having no text content, the empty string is returned. """ return ElementPath.findtext(self, path, default, namespaces) def findall(self, path, namespaces=None): """Find all matching subelements by tag name or path. *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Returns list containing all matching elements in document order. """ return ElementPath.findall(self, path, namespaces) def iterfind(self, path, namespaces=None): """Find all matching subelements by tag name or path. *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return an iterable yielding all matching elements in document order. """ return ElementPath.iterfind(self, path, namespaces) def clear(self): """Reset element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to None. """ self.attrib.clear() self._children = [] self.text = self.tail = None def get(self, key, default=None): """Get element attribute. Equivalent to attrib.get, but some implementations may handle this a bit more efficiently. *key* is what attribute to look for, and *default* is what to return if the attribute was not found. Returns a string containing the attribute value, or the default if attribute was not found. """ return self.attrib.get(key, default) def set(self, key, value): """Set element attribute. Equivalent to attrib[key] = value, but some implementations may handle this a bit more efficiently. *key* is what attribute to set, and *value* is the attribute value to set it to. """ self.attrib[key] = value def keys(self): """Get list of attribute names. Names are returned in an arbitrary order, just like an ordinary Python dict. Equivalent to attrib.keys() """ return self.attrib.keys() def items(self): """Get element attributes as a sequence. The attributes are returned in arbitrary order. Equivalent to attrib.items(). Return a list of (name, value) tuples. """ return self.attrib.items() def iter(self, tag=None): """Create tree iterator. The iterator loops over the element and all subelements in document order, returning all elements with a matching tag. If the tree structure is modified during iteration, new or removed elements may or may not be included. To get a stable set, use the list() function on the iterator, and loop over the resulting list. *tag* is what tags to look for (default is to return all elements) Return an iterator containing all the matching elements. """ if tag == "*": tag = None if tag is None or self.tag == tag: yield self for e in self._children: yield from e.iter(tag) # compatibility def getiterator(self, tag=None): # Change for a DeprecationWarning in 1.4 warnings.warn( "This method will be removed in future versions. " "Use 'elem.iter()' or 'list(elem.iter())' instead.", PendingDeprecationWarning, stacklevel=2 ) return list(self.iter(tag)) def itertext(self): """Create text iterator. The iterator loops over the element and all subelements in document order, returning all inner text. """ tag = self.tag if not isinstance(tag, str) and tag is not None: return t = self.text if t: yield t for e in self: yield from e.itertext() t = e.tail if t: yield t def SubElement(parent, tag, attrib={}, **extra): """Subelement factory which creates an element instance, and appends it to an existing parent. The element tag, attribute names, and attribute values can be either bytes or Unicode strings. *parent* is the parent element, *tag* is the subelements name, *attrib* is an optional directory containing element attributes, *extra* are additional attributes given as keyword arguments. """ attrib = attrib.copy() attrib.update(extra) element = parent.makeelement(tag, attrib) parent.append(element) return element def Comment(text=None): """Comment element factory. This function creates a special element which the standard serializer serializes as an XML comment. *text* is a string containing the comment string. """ element = Element(Comment) element.text = text return element def ProcessingInstruction(target, text=None): """Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any. """ element = Element(ProcessingInstruction) element.text = target if text: element.text = element.text + " " + text return element PI = ProcessingInstruction class QName: """Qualified name wrapper. This class can be used to wrap a QName attribute value in order to get proper namespace handing on output. *text_or_uri* is a string containing the QName value either in the form {uri}local, or if the tag argument is given, the URI part of a QName. *tag* is an optional argument which if given, will make the first argument (text_or_uri) be interpreted as a URI, and this argument (tag) be interpreted as a local name. """ def __init__(self, text_or_uri, tag=None): if tag: text_or_uri = "{%s}%s" % (text_or_uri, tag) self.text = text_or_uri def __str__(self): return self.text def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self.text) def __hash__(self): return hash(self.text) def __le__(self, other): if isinstance(other, QName): return self.text <= other.text return self.text <= other def __lt__(self, other): if isinstance(other, QName): return self.text < other.text return self.text < other def __ge__(self, other): if isinstance(other, QName): return self.text >= other.text return self.text >= other def __gt__(self, other): if isinstance(other, QName): return self.text > other.text return self.text > other def __eq__(self, other): if isinstance(other, QName): return self.text == other.text return self.text == other # -------------------------------------------------------------------- class ElementTree: """An XML element hierarchy. This class also provides support for serialization to and from standard XML. *element* is an optional root element node, *file* is an optional file handle or file name of an XML file whose contents will be used to initialize the tree with. """ def __init__(self, element=None, file=None): # assert element is None or iselement(element) self._root = element # first node if file: self.parse(file) def getroot(self): """Return root element of this tree.""" return self._root def _setroot(self, element): """Replace root element of this tree. This will discard the current contents of the tree and replace it with the given element. Use with care! """ # assert iselement(element) self._root = element def parse(self, source, parser=None): """Load external XML document into element tree. *source* is a file name or file object, *parser* is an optional parser instance that defaults to XMLParser. ParseError is raised if the parser fails to parse the document. Returns the root element of the given source document. """ close_source = False if not hasattr(source, "read"): source = open(source, "rb") close_source = True try: if parser is None: # If no parser was specified, create a default XMLParser parser = XMLParser() if hasattr(parser, '_parse_whole'): # The default XMLParser, when it comes from an accelerator, # can define an internal _parse_whole API for efficiency. # It can be used to parse the whole source without feeding # it with chunks. self._root = parser._parse_whole(source) return self._root while True: data = source.read(65536) if not data: break parser.feed(data) self._root = parser.close() return self._root finally: if close_source: source.close() def iter(self, tag=None): """Create and return tree iterator for the root element. The iterator loops over all elements in this tree, in document order. *tag* is a string with the tag name to iterate over (default is to return all elements). """ # assert self._root is not None return self._root.iter(tag) # compatibility def getiterator(self, tag=None): # Change for a DeprecationWarning in 1.4 warnings.warn( "This method will be removed in future versions. " "Use 'tree.iter()' or 'list(tree.iter())' instead.", PendingDeprecationWarning, stacklevel=2 ) return list(self.iter(tag)) def find(self, path, namespaces=None): """Find first matching element by tag name or path. Same as getroot().find(path), which is Element.find() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.find(path, namespaces) def findtext(self, path, default=None, namespaces=None): """Find first matching element by tag name or path. Same as getroot().findtext(path), which is Element.findtext() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.findtext(path, default, namespaces) def findall(self, path, namespaces=None): """Find all matching subelements by tag name or path. Same as getroot().findall(path), which is Element.findall(). *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return list containing all matching elements in document order. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.findall(path, namespaces) def iterfind(self, path, namespaces=None): """Find all matching subelements by tag name or path. Same as getroot().iterfind(path), which is element.iterfind() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return an iterable yielding all matching elements in document order. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.iterfind(path, namespaces) def write(self, file_or_filename, encoding=None, xml_declaration=None, default_namespace=None, method=None, *, short_empty_elements=True): """Write element tree to a file as XML. Arguments: *file_or_filename* -- file name or a file object opened for writing *encoding* -- the output encoding (default: US-ASCII) *xml_declaration* -- bool indicating if an XML declaration should be added to the output. If None, an XML declaration is added if encoding IS NOT either of: US-ASCII, UTF-8, or Unicode *default_namespace* -- sets the default XML namespace (for "xmlns") *method* -- either "xml" (default), "html, "text", or "c14n" *short_empty_elements* -- controls the formatting of elements that contain no content. If True (default) they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags """ if not method: method = "xml" elif method not in _serialize: raise ValueError("unknown method %r" % method) if not encoding: if method == "c14n": encoding = "utf-8" else: encoding = "us-ascii" enc_lower = encoding.lower() with _get_writer(file_or_filename, enc_lower) as write: if method == "xml" and (xml_declaration or (xml_declaration is None and enc_lower not in ("utf-8", "us-ascii", "unicode"))): declared_encoding = encoding if enc_lower == "unicode": # Retrieve the default encoding for the xml declaration import locale declared_encoding = locale.getpreferredencoding() write("<?xml version='1.0' encoding='%s'?>\n" % ( declared_encoding,)) if method == "text": _serialize_text(write, self._root) else: qnames, namespaces = _namespaces(self._root, default_namespace) serialize = _serialize[method] serialize(write, self._root, qnames, namespaces, short_empty_elements=short_empty_elements) def write_c14n(self, file): # lxml.etree compatibility. use output method instead return self.write(file, method="c14n") # -------------------------------------------------------------------- # serialization support @contextlib.contextmanager def _get_writer(file_or_filename, encoding): # returns text write method and release all resources after using try: write = file_or_filename.write except AttributeError: # file_or_filename is a file name if encoding == "unicode": file = open(file_or_filename, "w") else: file = open(file_or_filename, "w", encoding=encoding, errors="xmlcharrefreplace") with file: yield file.write else: # file_or_filename is a file-like object # encoding determines if it is a text or binary writer if encoding == "unicode": # use a text writer as is yield write else: # wrap a binary writer with TextIOWrapper with contextlib.ExitStack() as stack: if isinstance(file_or_filename, io.BufferedIOBase): file = file_or_filename elif isinstance(file_or_filename, io.RawIOBase): file = io.BufferedWriter(file_or_filename) # Keep the original file open when the BufferedWriter is # destroyed stack.callback(file.detach) else: # This is to handle passed objects that aren't in the # IOBase hierarchy, but just have a write method file = io.BufferedIOBase() file.writable = lambda: True file.write = write try: # TextIOWrapper uses this methods to determine # if BOM (for UTF-16, etc) should be added file.seekable = file_or_filename.seekable file.tell = file_or_filename.tell except AttributeError: pass file = io.TextIOWrapper(file, encoding=encoding, errors="xmlcharrefreplace", newline="\n") # Keep the original file open when the TextIOWrapper is # destroyed stack.callback(file.detach) yield file.write def _namespaces(elem, default_namespace=None): # identify namespaces used in this tree # maps qnames to *encoded* prefix:local names qnames = {None: None} # maps uri:s to prefixes namespaces = {} if default_namespace: namespaces[default_namespace] = "" def add_qname(qname): # calculate serialized qname representation try: if qname[:1] == "{": uri, tag = qname[1:].rsplit("}", 1) prefix = namespaces.get(uri) if prefix is None: prefix = _namespace_map.get(uri) if prefix is None: prefix = "ns%d" % len(namespaces) if prefix != "xml": namespaces[uri] = prefix if prefix: qnames[qname] = "%s:%s" % (prefix, tag) else: qnames[qname] = tag # default element else: if default_namespace: # FIXME: can this be handled in XML 1.0? raise ValueError( "cannot use non-qualified names with " "default_namespace option" ) qnames[qname] = qname except TypeError: _raise_serialization_error(qname) # populate qname and namespaces table for elem in elem.iter(): tag = elem.tag if isinstance(tag, QName): if tag.text not in qnames: add_qname(tag.text) elif isinstance(tag, str): if tag not in qnames: add_qname(tag) elif tag is not None and tag is not Comment and tag is not PI: _raise_serialization_error(tag) for key, value in elem.items(): if isinstance(key, QName): key = key.text if key not in qnames: add_qname(key) if isinstance(value, QName) and value.text not in qnames: add_qname(value.text) text = elem.text if isinstance(text, QName) and text.text not in qnames: add_qname(text.text) return qnames, namespaces def _serialize_xml(write, elem, qnames, namespaces, short_empty_elements, **kwargs): tag = elem.tag text = elem.text if tag is Comment: write("<!--%s-->" % text) elif tag is ProcessingInstruction: write("<?%s?>" % text) else: tag = qnames[tag] if tag is None: if text: write(_escape_cdata(text)) for e in elem: _serialize_xml(write, e, qnames, None, short_empty_elements=short_empty_elements) else: write("<" + tag) items = list(elem.items()) if items or namespaces: if namespaces: for v, k in sorted(namespaces.items(), key=lambda x: x[1]): # sort on prefix if k: k = ":" + k write(" xmlns%s=\"%s\"" % ( k, _escape_attrib(v) )) for k, v in sorted(items): # lexical order if isinstance(k, QName): k = k.text if isinstance(v, QName): v = qnames[v.text] else: v = _escape_attrib(v) write(" %s=\"%s\"" % (qnames[k], v)) if text or len(elem) or not short_empty_elements: write(">") if text: write(_escape_cdata(text)) for e in elem: _serialize_xml(write, e, qnames, None, short_empty_elements=short_empty_elements) write("</" + tag + ">") else: write(" />") if elem.tail: write(_escape_cdata(elem.tail)) HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr", "img", "input", "isindex", "link", "meta", "param") try: HTML_EMPTY = set(HTML_EMPTY) except NameError: pass def _serialize_html(write, elem, qnames, namespaces, **kwargs): tag = elem.tag text = elem.text if tag is Comment: write("<!--%s-->" % _escape_cdata(text)) elif tag is ProcessingInstruction: write("<?%s?>" % _escape_cdata(text)) else: tag = qnames[tag] if tag is None: if text: write(_escape_cdata(text)) for e in elem: _serialize_html(write, e, qnames, None) else: write("<" + tag) items = list(elem.items()) if items or namespaces: if namespaces: for v, k in sorted(namespaces.items(), key=lambda x: x[1]): # sort on prefix if k: k = ":" + k write(" xmlns%s=\"%s\"" % ( k, _escape_attrib(v) )) for k, v in sorted(items): # lexical order if isinstance(k, QName): k = k.text if isinstance(v, QName): v = qnames[v.text] else: v = _escape_attrib_html(v) # FIXME: handle boolean attributes write(" %s=\"%s\"" % (qnames[k], v)) write(">") ltag = tag.lower() if text: if ltag == "script" or ltag == "style": write(text) else: write(_escape_cdata(text)) for e in elem: _serialize_html(write, e, qnames, None) if ltag not in HTML_EMPTY: write("</" + tag + ">") if elem.tail: write(_escape_cdata(elem.tail)) def _serialize_text(write, elem): for part in elem.itertext(): write(part) if elem.tail: write(elem.tail) _serialize = { "xml": _serialize_xml, "html": _serialize_html, "text": _serialize_text, # this optional method is imported at the end of the module # "c14n": _serialize_c14n, } def register_namespace(prefix, uri): """Register a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. *prefix* is the namespace prefix, *uri* is a namespace uri. Tags and attributes in this namespace will be serialized with prefix if possible. ValueError is raised if prefix is reserved or is invalid. """ if re.match(r"ns\d+$", prefix): raise ValueError("Prefix format reserved for internal use") for k, v in list(_namespace_map.items()): if k == uri or v == prefix: del _namespace_map[k] _namespace_map[uri] = prefix _namespace_map = { # "well-known" namespace prefixes "http://www.w3.org/XML/1998/namespace": "xml", "http://www.w3.org/1999/xhtml": "html", "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", "http://schemas.xmlsoap.org/wsdl/": "wsdl", # xml schema "http://www.w3.org/2001/XMLSchema": "xs", "http://www.w3.org/2001/XMLSchema-instance": "xsi", # dublin core "http://purl.org/dc/elements/1.1/": "dc", } # For tests and troubleshooting register_namespace._namespace_map = _namespace_map def _raise_serialization_error(text): raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) ) def _escape_cdata(text): # escape character data try: # it's worth avoiding do-nothing calls for strings that are # shorter than 500 characters, or so. assume that's, by far, # the most common case in most applications. if "&" in text: text = text.replace("&", "&amp;") if "<" in text: text = text.replace("<", "&lt;") if ">" in text: text = text.replace(">", "&gt;") return text except (TypeError, AttributeError): _raise_serialization_error(text) def _escape_attrib(text): # escape attribute value try: if "&" in text: text = text.replace("&", "&amp;") if "<" in text: text = text.replace("<", "&lt;") if ">" in text: text = text.replace(">", "&gt;") if "\"" in text: text = text.replace("\"", "&quot;") # The following business with carriage returns is to satisfy # Section 2.11 of the XML specification, stating that # CR or CR LN should be replaced with just LN # http://www.w3.org/TR/REC-xml/#sec-line-ends if "\r\n" in text: text = text.replace("\r\n", "\n") if "\r" in text: text = text.replace("\r", "\n") #The following four lines are issue 17582 if "\n" in text: text = text.replace("\n", "&#10;") if "\t" in text: text = text.replace("\t", "&#09;") return text except (TypeError, AttributeError): _raise_serialization_error(text) def _escape_attrib_html(text): # escape attribute value try: if "&" in text: text = text.replace("&", "&amp;") if ">" in text: text = text.replace(">", "&gt;") if "\"" in text: text = text.replace("\"", "&quot;") return text except (TypeError, AttributeError): _raise_serialization_error(text) # -------------------------------------------------------------------- def tostring(element, encoding=None, method=None, *, short_empty_elements=True): """Generate string representation of XML element. All subelements are included. If encoding is "unicode", a string is returned. Otherwise a bytestring is returned. *element* is an Element instance, *encoding* is an optional output encoding defaulting to US-ASCII, *method* is an optional output which can be one of "xml" (default), "html", "text" or "c14n". Returns an (optionally) encoded string containing the XML data. """ stream = io.StringIO() if encoding == 'unicode' else io.BytesIO() ElementTree(element).write(stream, encoding, method=method, short_empty_elements=short_empty_elements) return stream.getvalue() class _ListDataStream(io.BufferedIOBase): """An auxiliary stream accumulating into a list reference.""" def __init__(self, lst): self.lst = lst def writable(self): return True def seekable(self): return True def write(self, b): self.lst.append(b) def tell(self): return len(self.lst) def tostringlist(element, encoding=None, method=None, *, short_empty_elements=True): lst = [] stream = _ListDataStream(lst) ElementTree(element).write(stream, encoding, method=method, short_empty_elements=short_empty_elements) return lst def dump(elem): """Write element tree or element structure to sys.stdout. This function should be used for debugging only. *elem* is either an ElementTree, or a single Element. The exact output format is implementation dependent. In this version, it's written as an ordinary XML file. """ # debugging if not isinstance(elem, ElementTree): elem = ElementTree(elem) elem.write(sys.stdout, encoding="unicode") tail = elem.getroot().tail if not tail or tail[-1] != "\n": sys.stdout.write("\n") # -------------------------------------------------------------------- # parsing def parse(source, parser=None): """Parse XML document into element tree. *source* is a filename or file object containing XML data, *parser* is an optional parser instance defaulting to XMLParser. Return an ElementTree instance. """ tree = ElementTree() tree.parse(source, parser) return tree def iterparse(source, events=None, parser=None): """Incrementally parse XML document into ElementTree. This class also reports what's going on to the user based on the *events* it is initialized with. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get detailed namespace information). If *events* is omitted, only "end" events are reported. *source* is a filename or file object containing XML data, *events* is a list of events to report back, *parser* is an optional parser instance. Returns an iterator providing (event, elem) pairs. """ # Use the internal, undocumented _parser argument for now; When the # parser argument of iterparse is removed, this can be killed. pullparser = XMLPullParser(events=events, _parser=parser) def iterator(): try: while True: yield from pullparser.read_events() # load event buffer data = source.read(16 * 1024) if not data: break pullparser.feed(data) root = pullparser._close_and_return_root() yield from pullparser.read_events() it.root = root finally: if close_source: source.close() class IterParseIterator(collections.Iterator): __next__ = iterator().__next__ it = IterParseIterator() it.root = None del iterator, IterParseIterator close_source = False if not hasattr(source, "read"): source = open(source, "rb") close_source = True return it class XMLPullParser: def __init__(self, events=None, *, _parser=None): # The _parser argument is for internal use only and must not be relied # upon in user code. It will be removed in a future release. # See http://bugs.python.org/issue17741 for more details. self._events_queue = collections.deque() self._parser = _parser or XMLParser(target=TreeBuilder()) # wire up the parser for event reporting if events is None: events = ("end",) self._parser._setevents(self._events_queue, events) def feed(self, data): """Feed encoded data to parser.""" if self._parser is None: raise ValueError("feed() called after end of stream") if data: try: self._parser.feed(data) except SyntaxError as exc: self._events_queue.append(exc) def _close_and_return_root(self): # iterparse needs this to set its root attribute properly :( root = self._parser.close() self._parser = None return root def close(self): """Finish feeding data to parser. Unlike XMLParser, does not return the root element. Use read_events() to consume elements from XMLPullParser. """ self._close_and_return_root() def read_events(self): """Return an iterator over currently available (event, elem) pairs. Events are consumed from the internal event queue as they are retrieved from the iterator. """ events = self._events_queue while events: event = events.popleft() if isinstance(event, Exception): raise event else: yield event def XML(text, parser=None): """Parse XML document from string constant. This function can be used to embed "XML Literals" in Python code. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an Element instance. """ if not parser: parser = XMLParser(target=TreeBuilder()) parser.feed(text) return parser.close() def XMLID(text, parser=None): """Parse XML document from string constant for its IDs. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an (Element, dict) tuple, in which the dict maps element id:s to elements. """ if not parser: parser = XMLParser(target=TreeBuilder()) parser.feed(text) tree = parser.close() ids = {} for elem in tree.iter(): id = elem.get("id") if id: ids[id] = elem return tree, ids # Parse XML document from string constant. Alias for XML(). fromstring = XML def fromstringlist(sequence, parser=None): """Parse XML document from sequence of string fragments. *sequence* is a list of other sequence, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an Element instance. """ if not parser: parser = XMLParser(target=TreeBuilder()) for text in sequence: parser.feed(text) return parser.close() # -------------------------------------------------------------------- class TreeBuilder: """Generic element structure builder. This builder converts a sequence of start, data, and end method calls to a well-formed element structure. You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format. *element_factory* is an optional element factory which is called to create new Element instances, as necessary. """ def __init__(self, element_factory=None): self._data = [] # data collector self._elem = [] # element stack self._last = None # last element self._tail = None # true if we're after an end tag if element_factory is None: element_factory = Element self._factory = element_factory def close(self): """Flush builder buffers and return toplevel document Element.""" assert len(self._elem) == 0, "missing end tags" assert self._last is not None, "missing toplevel element" return self._last def _flush(self): if self._data: if self._last is not None: text = "".join(self._data) if self._tail: assert self._last.tail is None, "internal error (tail)" self._last.tail = text else: assert self._last.text is None, "internal error (text)" self._last.text = text self._data = [] def data(self, data): """Add text to current element.""" self._data.append(data) def start(self, tag, attrs): """Open new element and return it. *tag* is the element name, *attrs* is a dict containing element attributes. """ self._flush() self._last = elem = self._factory(tag, attrs) if self._elem: self._elem[-1].append(elem) self._elem.append(elem) self._tail = 0 return elem def end(self, tag): """Close and return current Element. *tag* is the element name. """ self._flush() self._last = self._elem.pop() assert self._last.tag == tag,\ "end tag mismatch (expected %s, got %s)" % ( self._last.tag, tag) self._tail = 1 return self._last # also see ElementTree and TreeBuilder class XMLParser: """Element structure builder for XML source data based on the expat parser. *html* are predefined HTML entities (deprecated and not supported), *target* is an optional target object which defaults to an instance of the standard TreeBuilder class, *encoding* is an optional encoding string which if given, overrides the encoding specified in the XML file: http://www.iana.org/assignments/character-sets """ def __init__(self, html=0, target=None, encoding=None): try: from xml.parsers import expat except ImportError: try: import pyexpat as expat except ImportError: raise ImportError( "No module named expat; use SimpleXMLTreeBuilder instead" ) parser = expat.ParserCreate(encoding, "}") if target is None: target = TreeBuilder() # underscored names are provided for compatibility only self.parser = self._parser = parser self.target = self._target = target self._error = expat.error self._names = {} # name memo cache # main callbacks parser.DefaultHandlerExpand = self._default if hasattr(target, 'start'): parser.StartElementHandler = self._start if hasattr(target, 'end'): parser.EndElementHandler = self._end if hasattr(target, 'data'): parser.CharacterDataHandler = target.data # miscellaneous callbacks if hasattr(target, 'comment'): parser.CommentHandler = target.comment if hasattr(target, 'pi'): parser.ProcessingInstructionHandler = target.pi # Configure pyexpat: buffering, new-style attribute handling. parser.buffer_text = 1 parser.ordered_attributes = 1 parser.specified_attributes = 1 self._doctype = None self.entity = {} try: self.version = "Expat %d.%d.%d" % expat.version_info except AttributeError: pass # unknown def _setevents(self, events_queue, events_to_report): # Internal API for XMLPullParser # events_to_report: a list of events to report during parsing (same as # the *events* of XMLPullParser's constructor. # events_queue: a list of actual parsing events that will be populated # by the underlying parser. # parser = self._parser append = events_queue.append for event_name in events_to_report: if event_name == "start": parser.ordered_attributes = 1 parser.specified_attributes = 1 def handler(tag, attrib_in, event=event_name, append=append, start=self._start): append((event, start(tag, attrib_in))) parser.StartElementHandler = handler elif event_name == "end": def handler(tag, event=event_name, append=append, end=self._end): append((event, end(tag))) parser.EndElementHandler = handler elif event_name == "start-ns": def handler(prefix, uri, event=event_name, append=append): append((event, (prefix or "", uri or ""))) parser.StartNamespaceDeclHandler = handler elif event_name == "end-ns": def handler(prefix, event=event_name, append=append): append((event, None)) parser.EndNamespaceDeclHandler = handler else: raise ValueError("unknown event %r" % event_name) def _raiseerror(self, value): err = ParseError(value) err.code = value.code err.position = value.lineno, value.offset raise err def _fixname(self, key): # expand qname, and convert name string to ascii, if possible try: name = self._names[key] except KeyError: name = key if "}" in name: name = "{" + name self._names[key] = name return name def _start(self, tag, attr_list): # Handler for expat's StartElementHandler. Since ordered_attributes # is set, the attributes are reported as a list of alternating # attribute name,value. fixname = self._fixname tag = fixname(tag) attrib = {} if attr_list: for i in range(0, len(attr_list), 2): attrib[fixname(attr_list[i])] = attr_list[i+1] return self.target.start(tag, attrib) def _end(self, tag): return self.target.end(self._fixname(tag)) def _default(self, text): prefix = text[:1] if prefix == "&": # deal with undefined entities try: data_handler = self.target.data except AttributeError: return try: data_handler(self.entity[text[1:-1]]) except KeyError: from xml.parsers import expat err = expat.error( "undefined entity %s: line %d, column %d" % (text, self.parser.ErrorLineNumber, self.parser.ErrorColumnNumber) ) err.code = 11 # XML_ERROR_UNDEFINED_ENTITY err.lineno = self.parser.ErrorLineNumber err.offset = self.parser.ErrorColumnNumber raise err elif prefix == "<" and text[:9] == "<!DOCTYPE": self._doctype = [] # inside a doctype declaration elif self._doctype is not None: # parse doctype contents if prefix == ">": self._doctype = None return text = text.strip() if not text: return self._doctype.append(text) n = len(self._doctype) if n > 2: type = self._doctype[1] if type == "PUBLIC" and n == 4: name, type, pubid, system = self._doctype if pubid: pubid = pubid[1:-1] elif type == "SYSTEM" and n == 3: name, type, system = self._doctype pubid = None else: return if hasattr(self.target, "doctype"): self.target.doctype(name, pubid, system[1:-1]) elif self.doctype != self._XMLParser__doctype: # warn about deprecated call self._XMLParser__doctype(name, pubid, system[1:-1]) self.doctype(name, pubid, system[1:-1]) self._doctype = None def doctype(self, name, pubid, system): """(Deprecated) Handle doctype declaration *name* is the Doctype name, *pubid* is the public identifier, and *system* is the system identifier. """ warnings.warn( "This method of XMLParser is deprecated. Define doctype() " "method on the TreeBuilder target.", DeprecationWarning, ) # sentinel, if doctype is redefined in a subclass __doctype = doctype def feed(self, data): """Feed encoded data to parser.""" try: self.parser.Parse(data, 0) except self._error as v: self._raiseerror(v) def close(self): """Finish feeding data to parser and return element structure.""" try: self.parser.Parse("", 1) # end of data except self._error as v: self._raiseerror(v) try: close_handler = self.target.close except AttributeError: pass else: return close_handler() finally: # get rid of circular references del self.parser, self._parser del self.target, self._target # Import the C accelerators try: # Element is going to be shadowed by the C implementation. We need to keep # the Python version of it accessible for some "creative" by external code # (see tests) _Element_Py = Element # Element, SubElement, ParseError, TreeBuilder, XMLParser from _elementtree import * except ImportError: pass
57,029
1,657
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/etree/cElementTree.py
# Deprecated alias for xml.etree.ElementTree from xml.etree.ElementTree import * if __name__ == 'PYOBJ.COM': Comment = 0 Element = 0 ElementTree = 0 PI = 0 ParseError = 0 ProcessingInstruction = 0 QName = 0 SubElement = 0 TreeBuilder = 0 VERSION = 0 XML = 0 XMLID = 0 XMLParser = 0 XMLPullParser = 0 dump = 0 fromstring = 0 fromstringlist = 0 iselement = 0 iterparse = 0 parse = 0 register_namespace = 0 tostring = 0 tostringlist = 0
528
29
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/etree/ElementPath.py
# # ElementTree # $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $ # # limited xpath support for element trees # # history: # 2003-05-23 fl created # 2003-05-28 fl added support for // etc # 2003-08-27 fl fixed parsing of periods in element names # 2007-09-10 fl new selection engine # 2007-09-12 fl fixed parent selector # 2007-09-13 fl added iterfind; changed findall to return a list # 2007-11-30 fl added namespaces support # 2009-10-30 fl added child element value filter # # Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved. # # [email protected] # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2009 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. ## # Implementation module for XPath support. There's usually no reason # to import this module directly; the <b>ElementTree</b> does this for # you, if needed. ## import re xpath_tokenizer_re = re.compile( r"(" r"'[^']*'|\"[^\"]*\"|" r"::|" r"//?|" r"\.\.|" r"\(\)|" r"[/.*:\[\]\(\)@=])|" r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|" r"\s+" ) def xpath_tokenizer(pattern, namespaces=None): for token in xpath_tokenizer_re.findall(pattern): tag = token[1] if tag and tag[0] != "{" and ":" in tag: try: prefix, uri = tag.split(":", 1) if not namespaces: raise KeyError yield token[0], "{%s}%s" % (namespaces[prefix], uri) except KeyError: raise SyntaxError("prefix %r not found in prefix map" % prefix) else: yield token def get_parent_map(context): parent_map = context.parent_map if parent_map is None: context.parent_map = parent_map = {} for p in context.root.iter(): for e in p: parent_map[e] = p return parent_map def prepare_child(next, token): tag = token[1] def select(context, result): for elem in result: for e in elem: if e.tag == tag: yield e return select def prepare_star(next, token): def select(context, result): for elem in result: yield from elem return select def prepare_self(next, token): def select(context, result): yield from result return select def prepare_descendant(next, token): try: token = next() except StopIteration: return if token[0] == "*": tag = "*" elif not token[0]: tag = token[1] else: raise SyntaxError("invalid descendant") def select(context, result): for elem in result: for e in elem.iter(tag): if e is not elem: yield e return select def prepare_parent(next, token): def select(context, result): # FIXME: raise error if .. is applied at toplevel? parent_map = get_parent_map(context) result_map = {} for elem in result: if elem in parent_map: parent = parent_map[elem] if parent not in result_map: result_map[parent] = None yield parent return select def prepare_predicate(next, token): # FIXME: replace with real parser!!! refs: # http://effbot.org/zone/simple-iterator-parser.htm # http://javascript.crockford.com/tdop/tdop.html signature = [] predicate = [] while 1: try: token = next() except StopIteration: return if token[0] == "]": break if token[0] and token[0][:1] in "'\"": token = "'", token[0][1:-1] signature.append(token[0] or "-") predicate.append(token[1]) signature = "".join(signature) # use signature to determine predicate type if signature == "@-": # [@attribute] predicate key = predicate[1] def select(context, result): for elem in result: if elem.get(key) is not None: yield elem return select if signature == "@-='": # [@attribute='value'] key = predicate[1] value = predicate[-1] def select(context, result): for elem in result: if elem.get(key) == value: yield elem return select if signature == "-" and not re.match(r"\-?\d+$", predicate[0]): # [tag] tag = predicate[0] def select(context, result): for elem in result: if elem.find(tag) is not None: yield elem return select if signature == "-='" and not re.match(r"\-?\d+$", predicate[0]): # [tag='value'] tag = predicate[0] value = predicate[-1] def select(context, result): for elem in result: for e in elem.findall(tag): if "".join(e.itertext()) == value: yield elem break return select if signature == "-" or signature == "-()" or signature == "-()-": # [index] or [last()] or [last()-index] if signature == "-": # [index] index = int(predicate[0]) - 1 if index < 0: raise SyntaxError("XPath position >= 1 expected") else: if predicate[0] != "last": raise SyntaxError("unsupported function") if signature == "-()-": try: index = int(predicate[2]) - 1 except ValueError: raise SyntaxError("unsupported expression") if index > -2: raise SyntaxError("XPath offset from last() must be negative") else: index = -1 def select(context, result): parent_map = get_parent_map(context) for elem in result: try: parent = parent_map[elem] # FIXME: what if the selector is "*" ? elems = list(parent.findall(elem.tag)) if elems[index] is elem: yield elem except (IndexError, KeyError): pass return select raise SyntaxError("invalid predicate") ops = { "": prepare_child, "*": prepare_star, ".": prepare_self, "..": prepare_parent, "//": prepare_descendant, "[": prepare_predicate, } _cache = {} class _SelectorContext: parent_map = None def __init__(self, root): self.root = root # -------------------------------------------------------------------- ## # Generate all matching objects. def iterfind(elem, path, namespaces=None): # compile selector pattern cache_key = (path, None if namespaces is None else tuple(sorted(namespaces.items()))) if path[-1:] == "/": path = path + "*" # implicit all (FIXME: keep this?) try: selector = _cache[cache_key] except KeyError: if len(_cache) > 100: _cache.clear() if path[:1] == "/": raise SyntaxError("cannot use absolute path on element") next = iter(xpath_tokenizer(path, namespaces)).__next__ try: token = next() except StopIteration: return selector = [] while 1: try: selector.append(ops[token[0]](next, token)) except StopIteration: raise SyntaxError("invalid path") try: token = next() if token[0] == "/": token = next() except StopIteration: break _cache[cache_key] = selector # execute selector pattern result = [elem] context = _SelectorContext(elem) for select in selector: result = select(context, result) return result ## # Find first matching object. def find(elem, path, namespaces=None): return next(iterfind(elem, path, namespaces), None) ## # Find all matching objects. def findall(elem, path, namespaces=None): return list(iterfind(elem, path, namespaces)) ## # Find text for first matching object. def findtext(elem, path, default=None, namespaces=None): try: elem = next(iterfind(elem, path, namespaces)) return elem.text or "" except StopIteration: return default
9,935
315
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/etree/ElementInclude.py
# # ElementTree # $Id: ElementInclude.py 3375 2008-02-13 08:05:08Z fredrik $ # # limited xinclude support for element trees # # history: # 2003-08-15 fl created # 2003-11-14 fl fixed default loader # # Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved. # # [email protected] # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2008 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. ## # Limited XInclude support for the ElementTree package. ## import copy from . import ElementTree XINCLUDE = "{http://www.w3.org/2001/XInclude}" XINCLUDE_INCLUDE = XINCLUDE + "include" XINCLUDE_FALLBACK = XINCLUDE + "fallback" ## # Fatal include error. class FatalIncludeError(SyntaxError): pass ## # Default loader. This loader reads an included resource from disk. # # @param href Resource reference. # @param parse Parse mode. Either "xml" or "text". # @param encoding Optional text encoding (UTF-8 by default for "text"). # @return The expanded resource. If the parse mode is "xml", this # is an ElementTree instance. If the parse mode is "text", this # is a Unicode string. If the loader fails, it can return None # or raise an OSError exception. # @throws OSError If the loader fails to load the resource. def default_loader(href, parse, encoding=None): if parse == "xml": with open(href, 'rb') as file: data = ElementTree.parse(file).getroot() else: if not encoding: encoding = 'UTF-8' with open(href, 'r', encoding=encoding) as file: data = file.read() return data ## # Expand XInclude directives. # # @param elem Root element. # @param loader Optional resource loader. If omitted, it defaults # to {@link default_loader}. If given, it should be a callable # that implements the same interface as <b>default_loader</b>. # @throws FatalIncludeError If the function fails to include a given # resource, or if the tree contains malformed XInclude elements. # @throws OSError If the function fails to load a given resource. def include(elem, loader=None): if loader is None: loader = default_loader # look for xinclude elements i = 0 while i < len(elem): e = elem[i] if e.tag == XINCLUDE_INCLUDE: # process xinclude directive href = e.get("href") parse = e.get("parse", "xml") if parse == "xml": node = loader(href, parse) if node is None: raise FatalIncludeError( "cannot load %r as %r" % (href, parse) ) node = copy.copy(node) if e.tail: node.tail = (node.tail or "") + e.tail elem[i] = node elif parse == "text": text = loader(href, parse, e.get("encoding")) if text is None: raise FatalIncludeError( "cannot load %r as %r" % (href, parse) ) if i: node = elem[i-1] node.tail = (node.tail or "") + text + (e.tail or "") else: elem.text = (elem.text or "") + text + (e.tail or "") del elem[i] continue else: raise FatalIncludeError( "unknown parse type in xi:include tag (%r)" % parse ) elif e.tag == XINCLUDE_FALLBACK: raise FatalIncludeError( "xi:fallback tag must be child of xi:include (%r)" % e.tag ) else: include(e, loader) i = i + 1
5,151
144
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/etree/__init__.py
# $Id: __init__.py 3375 2008-02-13 08:05:08Z fredrik $ # elementtree package # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2008 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details.
1,604
34
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/expatbuilder.py
"""Facility to use the Expat parser to load a minidom instance from a string or file. This avoids all the overhead of SAX and pulldom to gain performance. """ # Warning! # # This module is tightly bound to the implementation details of the # minidom DOM and can't be used with other DOM implementations. This # is due, in part, to a lack of appropriate methods in the DOM (there is # no way to create Entity and Notation nodes via the DOM Level 2 # interface), and for performance. The latter is the cause of some fairly # cryptic code. # # Performance hacks: # # - .character_data_handler() has an extra case in which continuing # data is appended to an existing Text node; this can be a # speedup since pyexpat can break up character data into multiple # callbacks even though we set the buffer_text attribute on the # parser. This also gives us the advantage that we don't need a # separate normalization pass. # # - Determining that a node exists is done using an identity comparison # with None rather than a truth test; this avoids searching for and # calling any methods on the node object if it exists. (A rather # nice speedup is achieved this way as well!) from xml.dom import xmlbuilder, minidom, Node from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE from xml.parsers import expat from xml.dom.minidom import _append_child, _set_attribute_node from xml.dom.NodeFilter import NodeFilter TEXT_NODE = Node.TEXT_NODE CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE DOCUMENT_NODE = Node.DOCUMENT_NODE FILTER_ACCEPT = xmlbuilder.DOMBuilderFilter.FILTER_ACCEPT FILTER_REJECT = xmlbuilder.DOMBuilderFilter.FILTER_REJECT FILTER_SKIP = xmlbuilder.DOMBuilderFilter.FILTER_SKIP FILTER_INTERRUPT = xmlbuilder.DOMBuilderFilter.FILTER_INTERRUPT theDOMImplementation = minidom.getDOMImplementation() # Expat typename -> TypeInfo _typeinfo_map = { "CDATA": minidom.TypeInfo(None, "cdata"), "ENUM": minidom.TypeInfo(None, "enumeration"), "ENTITY": minidom.TypeInfo(None, "entity"), "ENTITIES": minidom.TypeInfo(None, "entities"), "ID": minidom.TypeInfo(None, "id"), "IDREF": minidom.TypeInfo(None, "idref"), "IDREFS": minidom.TypeInfo(None, "idrefs"), "NMTOKEN": minidom.TypeInfo(None, "nmtoken"), "NMTOKENS": minidom.TypeInfo(None, "nmtokens"), } class ElementInfo(object): __slots__ = '_attr_info', '_model', 'tagName' def __init__(self, tagName, model=None): self.tagName = tagName self._attr_info = [] self._model = model def __getstate__(self): return self._attr_info, self._model, self.tagName def __setstate__(self, state): self._attr_info, self._model, self.tagName = state def getAttributeType(self, aname): for info in self._attr_info: if info[1] == aname: t = info[-2] if t[0] == "(": return _typeinfo_map["ENUM"] else: return _typeinfo_map[info[-2]] return minidom._no_type def getAttributeTypeNS(self, namespaceURI, localName): return minidom._no_type def isElementContent(self): if self._model: type = self._model[0] return type not in (expat.model.XML_CTYPE_ANY, expat.model.XML_CTYPE_MIXED) else: return False def isEmpty(self): if self._model: return self._model[0] == expat.model.XML_CTYPE_EMPTY else: return False def isId(self, aname): for info in self._attr_info: if info[1] == aname: return info[-2] == "ID" return False def isIdNS(self, euri, ename, auri, aname): # not sure this is meaningful return self.isId((auri, aname)) def _intern(builder, s): return builder._intern_setdefault(s, s) def _parse_ns_name(builder, name): assert ' ' in name parts = name.split(' ') intern = builder._intern_setdefault if len(parts) == 3: uri, localname, prefix = parts prefix = intern(prefix, prefix) qname = "%s:%s" % (prefix, localname) qname = intern(qname, qname) localname = intern(localname, localname) elif len(parts) == 2: uri, localname = parts prefix = EMPTY_PREFIX qname = localname = intern(localname, localname) else: raise ValueError("Unsupported syntax: spaces in URIs not supported: %r" % name) return intern(uri, uri), localname, prefix, qname class ExpatBuilder: """Document builder that uses Expat to build a ParsedXML.DOM document instance.""" def __init__(self, options=None): if options is None: options = xmlbuilder.Options() self._options = options if self._options.filter is not None: self._filter = FilterVisibilityController(self._options.filter) else: self._filter = None # This *really* doesn't do anything in this case, so # override it with something fast & minimal. self._finish_start_element = id self._parser = None self.reset() def createParser(self): """Create a new parser object.""" return expat.ParserCreate() 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 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 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 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 def parseString(self, string): """Parse a document from a string, returning the document node.""" parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc def _setup_subset(self, buffer): """Load the internal subset if there might be one.""" if self.document.doctype: extractor = InternalSubsetExtractor() extractor.parseString(buffer) subset = extractor.getSubset() self.document.doctype.internalSubset = subset def start_doctype_decl_handler(self, doctypeName, systemId, publicId, has_internal_subset): doctype = self.document.implementation.createDocumentType( doctypeName, publicId, systemId) doctype.ownerDocument = self.document _append_child(self.document, doctype) self.document.doctype = doctype if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT: self.document.doctype = None del self.document.childNodes[-1] doctype = None self._parser.EntityDeclHandler = None self._parser.NotationDeclHandler = None if has_internal_subset: if doctype is not None: doctype.entities._seq = [] doctype.notations._seq = [] self._parser.CommentHandler = None self._parser.ProcessingInstructionHandler = None self._parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler def end_doctype_decl_handler(self): if self._options.comments: self._parser.CommentHandler = self.comment_handler self._parser.ProcessingInstructionHandler = self.pi_handler if not (self._elem_info or self._filter): self._finish_end_element = id def pi_handler(self, target, data): node = self.document.createProcessingInstruction(target, data) _append_child(self.curNode, node) if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: self.curNode.removeChild(node) def character_data_handler_cdata(self, data): childNodes = self.curNode.childNodes if self._cdata: if ( self._cdata_continue and childNodes[-1].nodeType == CDATA_SECTION_NODE): childNodes[-1].appendData(data) return node = self.document.createCDATASection(data) self._cdata_continue = True elif childNodes and childNodes[-1].nodeType == TEXT_NODE: node = childNodes[-1] value = node.data + data node.data = value return else: node = minidom.Text() node.data = data node.ownerDocument = self.document _append_child(self.curNode, node) def character_data_handler(self, data): childNodes = self.curNode.childNodes if childNodes and childNodes[-1].nodeType == TEXT_NODE: node = childNodes[-1] node.data = node.data + data return node = minidom.Text() node.data = node.data + data node.ownerDocument = self.document _append_child(self.curNode, node) def entity_decl_handler(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName): if is_parameter_entity: # we don't care about parameter entities for the DOM return if not self._options.entities: return node = self.document._create_entity(entityName, publicId, systemId, notationName) if value is not None: # internal entity # node *should* be readonly, but we'll cheat child = self.document.createTextNode(value) node.childNodes.append(child) self.document.doctype.entities._seq.append(node) if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: del self.document.doctype.entities._seq[-1] def notation_decl_handler(self, notationName, base, systemId, publicId): node = self.document._create_notation(notationName, publicId, systemId) self.document.doctype.notations._seq.append(node) if self._filter and self._filter.acceptNode(node) == FILTER_ACCEPT: del self.document.doctype.notations._seq[-1] def comment_handler(self, data): node = self.document.createComment(data) _append_child(self.curNode, node) if self._filter and self._filter.acceptNode(node) == FILTER_REJECT: self.curNode.removeChild(node) def start_cdata_section_handler(self): self._cdata = True self._cdata_continue = False def end_cdata_section_handler(self): self._cdata = False self._cdata_continue = False def external_entity_ref_handler(self, context, base, systemId, publicId): return 1 def first_element_handler(self, name, attributes): if self._filter is None and not self._elem_info: self._finish_end_element = id self.getParser().StartElementHandler = self.start_element_handler self.start_element_handler(name, attributes) def start_element_handler(self, name, attributes): node = self.document.createElement(name) _append_child(self.curNode, node) self.curNode = node if attributes: for i in range(0, len(attributes), 2): a = minidom.Attr(attributes[i], EMPTY_NAMESPACE, None, EMPTY_PREFIX) value = attributes[i+1] a.value = value a.ownerDocument = self.document _set_attribute_node(node, a) if node is not self.document.documentElement: self._finish_start_element(node) def _finish_start_element(self, node): if self._filter: # To be general, we'd have to call isSameNode(), but this # is sufficient for minidom: if node is self.document.documentElement: return filt = self._filter.startContainer(node) if filt == FILTER_REJECT: # ignore this node & all descendents Rejecter(self) elif filt == FILTER_SKIP: # ignore this node, but make it's children become # children of the parent node Skipper(self) else: return self.curNode = node.parentNode node.parentNode.removeChild(node) node.unlink() # If this ever changes, Namespaces.end_element_handler() needs to # be changed to match. # def end_element_handler(self, name): curNode = self.curNode self.curNode = curNode.parentNode self._finish_end_element(curNode) def _finish_end_element(self, curNode): info = self._elem_info.get(curNode.tagName) if info: self._handle_white_text_nodes(curNode, info) if self._filter: if curNode is self.document.documentElement: return if self._filter.acceptNode(curNode) == FILTER_REJECT: self.curNode.removeChild(curNode) curNode.unlink() def _handle_white_text_nodes(self, node, info): if (self._options.whitespace_in_element_content or not info.isElementContent()): return # We have element type information and should remove ignorable # whitespace; identify for text nodes which contain only # whitespace. L = [] for child in node.childNodes: if child.nodeType == TEXT_NODE and not child.data.strip(): L.append(child) # Remove ignorable whitespace from the tree. for child in L: node.removeChild(child) def element_decl_handler(self, name, model): info = self._elem_info.get(name) if info is None: self._elem_info[name] = ElementInfo(name, model) else: assert info._model is None info._model = model def attlist_decl_handler(self, elem, name, type, default, required): info = self._elem_info.get(elem) if info is None: info = ElementInfo(elem) self._elem_info[elem] = info info._attr_info.append( [None, name, None, None, default, 0, type, required]) def xml_decl_handler(self, version, encoding, standalone): self.document.version = version self.document.encoding = encoding # This is still a little ugly, thanks to the pyexpat API. ;-( if standalone >= 0: if standalone: self.document.standalone = True else: self.document.standalone = False # Don't include FILTER_INTERRUPT, since that's checked separately # where allowed. _ALLOWED_FILTER_RETURNS = (FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP) class FilterVisibilityController(object): """Wrapper around a DOMBuilderFilter which implements the checks to make the whatToShow filter attribute work.""" __slots__ = 'filter', def __init__(self, filter): self.filter = filter def startContainer(self, node): mask = self._nodetype_mask[node.nodeType] if self.filter.whatToShow & mask: val = self.filter.startContainer(node) if val == FILTER_INTERRUPT: raise ParseEscape if val not in _ALLOWED_FILTER_RETURNS: raise ValueError( "startContainer() returned illegal value: " + repr(val)) return val else: return FILTER_ACCEPT def acceptNode(self, node): mask = self._nodetype_mask[node.nodeType] if self.filter.whatToShow & mask: val = self.filter.acceptNode(node) if val == FILTER_INTERRUPT: raise ParseEscape if val == FILTER_SKIP: # move all child nodes to the parent, and remove this node parent = node.parentNode for child in node.childNodes[:]: parent.appendChild(child) # node is handled by the caller return FILTER_REJECT if val not in _ALLOWED_FILTER_RETURNS: raise ValueError( "acceptNode() returned illegal value: " + repr(val)) return val else: return FILTER_ACCEPT _nodetype_mask = { Node.ELEMENT_NODE: NodeFilter.SHOW_ELEMENT, Node.ATTRIBUTE_NODE: NodeFilter.SHOW_ATTRIBUTE, Node.TEXT_NODE: NodeFilter.SHOW_TEXT, Node.CDATA_SECTION_NODE: NodeFilter.SHOW_CDATA_SECTION, Node.ENTITY_REFERENCE_NODE: NodeFilter.SHOW_ENTITY_REFERENCE, Node.ENTITY_NODE: NodeFilter.SHOW_ENTITY, Node.PROCESSING_INSTRUCTION_NODE: NodeFilter.SHOW_PROCESSING_INSTRUCTION, Node.COMMENT_NODE: NodeFilter.SHOW_COMMENT, Node.DOCUMENT_NODE: NodeFilter.SHOW_DOCUMENT, Node.DOCUMENT_TYPE_NODE: NodeFilter.SHOW_DOCUMENT_TYPE, Node.DOCUMENT_FRAGMENT_NODE: NodeFilter.SHOW_DOCUMENT_FRAGMENT, Node.NOTATION_NODE: NodeFilter.SHOW_NOTATION, } class FilterCrutch(object): __slots__ = '_builder', '_level', '_old_start', '_old_end' def __init__(self, builder): self._level = 0 self._builder = builder parser = builder._parser self._old_start = parser.StartElementHandler self._old_end = parser.EndElementHandler parser.StartElementHandler = self.start_element_handler parser.EndElementHandler = self.end_element_handler class Rejecter(FilterCrutch): __slots__ = () def __init__(self, builder): FilterCrutch.__init__(self, builder) parser = builder._parser for name in ("ProcessingInstructionHandler", "CommentHandler", "CharacterDataHandler", "StartCdataSectionHandler", "EndCdataSectionHandler", "ExternalEntityRefHandler", ): setattr(parser, name, None) def start_element_handler(self, *args): self._level = self._level + 1 def end_element_handler(self, *args): if self._level == 0: # restore the old handlers parser = self._builder._parser self._builder.install(parser) parser.StartElementHandler = self._old_start parser.EndElementHandler = self._old_end else: self._level = self._level - 1 class Skipper(FilterCrutch): __slots__ = () def start_element_handler(self, *args): node = self._builder.curNode self._old_start(*args) if self._builder.curNode is not node: self._level = self._level + 1 def end_element_handler(self, *args): if self._level == 0: # We're popping back out of the node we're skipping, so we # shouldn't need to do anything but reset the handlers. self._builder._parser.StartElementHandler = self._old_start self._builder._parser.EndElementHandler = self._old_end self._builder = None else: self._level = self._level - 1 self._old_end(*args) # framework document used by the fragment builder. # Takes a string for the doctype, subset string, and namespace attrs string. _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID = \ "http://xml.python.org/entities/fragment-builder/internal" _FRAGMENT_BUILDER_TEMPLATE = ( '''\ <!DOCTYPE wrapper %%s [ <!ENTITY fragment-builder-internal SYSTEM "%s"> %%s ]> <wrapper %%s >&fragment-builder-internal;</wrapper>''' % _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID) class FragmentBuilder(ExpatBuilder): """Builder which constructs document fragments given XML source text and a context node. The context node is expected to provide information about the namespace declarations which are in scope at the start of the fragment. """ def __init__(self, context, options=None): if context.nodeType == DOCUMENT_NODE: self.originalDocument = context self.context = context else: self.originalDocument = context.ownerDocument self.context = context ExpatBuilder.__init__(self, options) def reset(self): ExpatBuilder.reset(self) self.fragment = None def parseFile(self, file): """Parse a document fragment from a file object, returning the fragment node.""" return self.parseString(file.read()) def parseString(self, string): """Parse a document fragment from a string, returning the fragment node.""" self._source = string parser = self.getParser() doctype = self.originalDocument.doctype ident = "" if doctype: subset = doctype.internalSubset or self._getDeclarations() if doctype.publicId: ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId)) elif doctype.systemId: ident = 'SYSTEM "%s"' % doctype.systemId else: subset = "" nsattrs = self._getNSattrs() # get ns decls from node's ancestors document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs) try: parser.Parse(document, 1) except: self.reset() raise fragment = self.fragment self.reset() ## self._parser = None return fragment def _getDeclarations(self): """Re-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string. """ doctype = self.context.ownerDocument.doctype s = "" if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = s + "\n " s = "%s<!NOTATION %s" % (s, notation.nodeName) if notation.publicId: s = '%s PUBLIC "%s"\n "%s">' \ % (s, notation.publicId, notation.systemId) else: s = '%s SYSTEM "%s">' % (s, notation.systemId) for i in range(doctype.entities.length): entity = doctype.entities.item(i) if s: s = s + "\n " s = "%s<!ENTITY %s" % (s, entity.nodeName) if entity.publicId: s = '%s PUBLIC "%s"\n "%s"' \ % (s, entity.publicId, entity.systemId) elif entity.systemId: s = '%s SYSTEM "%s"' % (s, entity.systemId) else: s = '%s "%s"' % (s, entity.firstChild.data) if entity.notationName: s = "%s NOTATION %s" % (s, entity.notationName) s = s + ">" return s def _getNSattrs(self): return "" def external_entity_ref_handler(self, context, base, systemId, publicId): if systemId == _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID: # this entref is the one that we made to put the subtree # in; all of our given input is parsed in here. old_document = self.document old_cur_node = self.curNode parser = self._parser.ExternalEntityParserCreate(context) # put the real document back, parse into the fragment to return self.document = self.originalDocument self.fragment = self.document.createDocumentFragment() self.curNode = self.fragment try: parser.Parse(self._source, 1) finally: self.curNode = old_cur_node self.document = old_document self._source = None return -1 else: return ExpatBuilder.external_entity_ref_handler( self, context, base, systemId, publicId) class Namespaces: """Mix-in class for builders; adds support for namespaces.""" def _initNamespaces(self): # list of (prefix, uri) ns declarations. Namespace attrs are # constructed from this and added to the element's attrs. self._ns_ordered_prefixes = [] def createParser(self): """Create a new namespace-handling parser.""" parser = expat.ParserCreate(namespace_separator=" ") parser.namespace_prefixes = True return parser def install(self, parser): """Insert the namespace-handlers onto the parser.""" ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = ( self.start_namespace_decl_handler) def start_namespace_decl_handler(self, prefix, uri): """Push this namespace declaration on our storage.""" self._ns_ordered_prefixes.append((prefix, uri)) def start_element_handler(self, name, attributes): if ' ' in name: uri, localname, prefix, qname = _parse_ns_name(self, name) else: uri = EMPTY_NAMESPACE qname = name localname = None prefix = EMPTY_PREFIX node = minidom.Element(qname, uri, prefix, localname) node.ownerDocument = self.document _append_child(self.curNode, node) self.curNode = node if self._ns_ordered_prefixes: for prefix, uri in self._ns_ordered_prefixes: if prefix: a = minidom.Attr(_intern(self, 'xmlns:' + prefix), XMLNS_NAMESPACE, prefix, "xmlns") else: a = minidom.Attr("xmlns", XMLNS_NAMESPACE, "xmlns", EMPTY_PREFIX) a.value = uri a.ownerDocument = self.document _set_attribute_node(node, a) del self._ns_ordered_prefixes[:] if attributes: node._ensure_attributes() _attrs = node._attrs _attrsNS = node._attrsNS for i in range(0, len(attributes), 2): aname = attributes[i] value = attributes[i+1] if ' ' in aname: uri, localname, prefix, qname = _parse_ns_name(self, aname) a = minidom.Attr(qname, uri, localname, prefix) _attrs[qname] = a _attrsNS[(uri, localname)] = a else: a = minidom.Attr(aname, EMPTY_NAMESPACE, aname, EMPTY_PREFIX) _attrs[aname] = a _attrsNS[(EMPTY_NAMESPACE, aname)] = a a.ownerDocument = self.document a.value = value a.ownerElement = node if __debug__: # This only adds some asserts to the original # end_element_handler(), so we only define this when -O is not # used. If changing one, be sure to check the other to see if # it needs to be changed as well. # def end_element_handler(self, name): curNode = self.curNode if ' ' in name: uri, localname, prefix, qname = _parse_ns_name(self, name) assert (curNode.namespaceURI == uri and curNode.localName == localname and curNode.prefix == prefix), \ "element stack messed up! (namespace)" else: assert curNode.nodeName == name, \ "element stack messed up - bad nodeName" assert curNode.namespaceURI == EMPTY_NAMESPACE, \ "element stack messed up - bad namespaceURI" self.curNode = curNode.parentNode self._finish_end_element(curNode) class ExpatBuilderNS(Namespaces, ExpatBuilder): """Document builder that supports namespaces.""" def reset(self): ExpatBuilder.reset(self) self._initNamespaces() class FragmentBuilderNS(Namespaces, FragmentBuilder): """Fragment builder that supports namespaces.""" def reset(self): FragmentBuilder.reset(self) self._initNamespaces() def _getNSattrs(self): """Return string of namespace attributes from this element and ancestors.""" # XXX This needs to be re-written to walk the ancestors of the # context to build up the namespace information from # declarations, elements, and attributes found in context. # Otherwise we have to store a bunch more data on the DOM # (though that *might* be more reliable -- not clear). attrs = "" context = self.context L = [] while context: if hasattr(context, '_ns_prefix_uri'): for prefix, uri in context._ns_prefix_uri.items(): # add every new NS decl from context to L and attrs string if prefix in L: continue L.append(prefix) if prefix: declname = "xmlns:" + prefix else: declname = "xmlns" if attrs: attrs = "%s\n %s='%s'" % (attrs, declname, uri) else: attrs = " %s='%s'" % (declname, uri) context = context.parentNode return attrs class ParseEscape(Exception): """Exception raised to short-circuit parsing in InternalSubsetExtractor.""" pass class InternalSubsetExtractor(ExpatBuilder): """XML processor which can rip out the internal document type subset.""" subset = None def getSubset(self): """Return the internal subset as a string.""" return self.subset def parseFile(self, file): try: ExpatBuilder.parseFile(self, file) except ParseEscape: pass def parseString(self, string): try: ExpatBuilder.parseString(self, string) except ParseEscape: pass def install(self, parser): parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.start_element_handler def start_doctype_decl_handler(self, name, publicId, systemId, has_internal_subset): if has_internal_subset: parser = self.getParser() self.subset = [] parser.DefaultHandler = self.subset.append parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler else: raise ParseEscape() def end_doctype_decl_handler(self): s = ''.join(self.subset).replace('\r\n', '\n').replace('\r', '\n') self.subset = s raise ParseEscape() def start_element_handler(self, name, attrs): raise ParseEscape() def parse(file, namespaces=True): """Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() if isinstance(file, str): with open(file, 'rb') as fp: result = builder.parseFile(fp) else: result = builder.parseFile(file) return result def parseString(string, namespaces=True): """Parse a document from a string, returning the resulting Document node. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() return builder.parseString(string) def parseFragment(file, context, namespaces=True): """Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) if isinstance(file, str): with open(file, 'rb') as fp: result = builder.parseFile(fp) else: result = builder.parseFile(file) return result def parseFragmentString(string, context, namespaces=True): """Parse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) return builder.parseString(string) def makeBuilder(options): """Create a builder based on an Options object.""" if options.namespaces: return ExpatBuilderNS(options) else: return ExpatBuilder(options)
35,756
966
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/NodeFilter.py
# This is the Python mapping for interface NodeFilter from # DOM2-Traversal-Range. It contains only constants. class NodeFilter: """ This is the DOM2 NodeFilter interface. It contains only constants. """ FILTER_ACCEPT = 1 FILTER_REJECT = 2 FILTER_SKIP = 3 SHOW_ALL = 0xFFFFFFFF SHOW_ELEMENT = 0x00000001 SHOW_ATTRIBUTE = 0x00000002 SHOW_TEXT = 0x00000004 SHOW_CDATA_SECTION = 0x00000008 SHOW_ENTITY_REFERENCE = 0x00000010 SHOW_ENTITY = 0x00000020 SHOW_PROCESSING_INSTRUCTION = 0x00000040 SHOW_COMMENT = 0x00000080 SHOW_DOCUMENT = 0x00000100 SHOW_DOCUMENT_TYPE = 0x00000200 SHOW_DOCUMENT_FRAGMENT = 0x00000400 SHOW_NOTATION = 0x00000800 def acceptNode(self, node): raise NotImplementedError
936
28
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/pulldom.py
import xml.sax import xml.sax.handler START_ELEMENT = "START_ELEMENT" END_ELEMENT = "END_ELEMENT" COMMENT = "COMMENT" START_DOCUMENT = "START_DOCUMENT" END_DOCUMENT = "END_DOCUMENT" PROCESSING_INSTRUCTION = "PROCESSING_INSTRUCTION" IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE" CHARACTERS = "CHARACTERS" class PullDOM(xml.sax.ContentHandler): _locator = None document = None def __init__(self, documentFactory=None): from xml.dom import XML_NAMESPACE self.documentFactory = documentFactory self.firstEvent = [None, None] self.lastEvent = self.firstEvent self.elementStack = [] self.push = self.elementStack.append try: self.pop = self.elementStack.pop except AttributeError: # use class' pop instead pass self._ns_contexts = [{XML_NAMESPACE:'xml'}] # contains uri -> prefix dicts self._current_context = self._ns_contexts[-1] self.pending_events = [] def pop(self): result = self.elementStack[-1] del self.elementStack[-1] return result def setDocumentLocator(self, locator): self._locator = locator def startPrefixMapping(self, prefix, uri): if not hasattr(self, '_xmlns_attrs'): self._xmlns_attrs = [] self._xmlns_attrs.append((prefix or 'xmlns', uri)) self._ns_contexts.append(self._current_context.copy()) self._current_context[uri] = prefix or None def endPrefixMapping(self, prefix): self._current_context = self._ns_contexts.pop() def startElementNS(self, name, tagName , attrs): # Retrieve xml namespace declaration attributes. xmlns_uri = 'http://www.w3.org/2000/xmlns/' xmlns_attrs = getattr(self, '_xmlns_attrs', None) if xmlns_attrs is not None: for aname, value in xmlns_attrs: attrs._attrs[(xmlns_uri, aname)] = value self._xmlns_attrs = [] uri, localname = name if uri: # When using namespaces, the reader may or may not # provide us with the original name. If not, create # *a* valid tagName from the current context. if tagName is None: prefix = self._current_context[uri] if prefix: tagName = prefix + ":" + localname else: tagName = localname if self.document: node = self.document.createElementNS(uri, tagName) else: node = self.buildDocument(uri, tagName) else: # When the tagname is not prefixed, it just appears as # localname if self.document: node = self.document.createElement(localname) else: node = self.buildDocument(None, localname) for aname,value in attrs.items(): a_uri, a_localname = aname if a_uri == xmlns_uri: if a_localname == 'xmlns': qname = a_localname else: qname = 'xmlns:' + a_localname attr = self.document.createAttributeNS(a_uri, qname) node.setAttributeNodeNS(attr) elif a_uri: prefix = self._current_context[a_uri] if prefix: qname = prefix + ":" + a_localname else: qname = a_localname attr = self.document.createAttributeNS(a_uri, qname) node.setAttributeNodeNS(attr) else: attr = self.document.createAttribute(a_localname) node.setAttributeNode(attr) attr.value = value self.lastEvent[1] = [(START_ELEMENT, node), None] self.lastEvent = self.lastEvent[1] self.push(node) def endElementNS(self, name, tagName): self.lastEvent[1] = [(END_ELEMENT, self.pop()), None] self.lastEvent = self.lastEvent[1] def startElement(self, name, attrs): if self.document: node = self.document.createElement(name) else: node = self.buildDocument(None, name) for aname,value in attrs.items(): attr = self.document.createAttribute(aname) attr.value = value node.setAttributeNode(attr) self.lastEvent[1] = [(START_ELEMENT, node), None] self.lastEvent = self.lastEvent[1] self.push(node) def endElement(self, name): self.lastEvent[1] = [(END_ELEMENT, self.pop()), None] self.lastEvent = self.lastEvent[1] def comment(self, s): if self.document: node = self.document.createComment(s) self.lastEvent[1] = [(COMMENT, node), None] self.lastEvent = self.lastEvent[1] else: event = [(COMMENT, s), None] self.pending_events.append(event) def processingInstruction(self, target, data): if self.document: node = self.document.createProcessingInstruction(target, data) self.lastEvent[1] = [(PROCESSING_INSTRUCTION, node), None] self.lastEvent = self.lastEvent[1] else: event = [(PROCESSING_INSTRUCTION, target, data), None] self.pending_events.append(event) def ignorableWhitespace(self, chars): node = self.document.createTextNode(chars) self.lastEvent[1] = [(IGNORABLE_WHITESPACE, node), None] self.lastEvent = self.lastEvent[1] def characters(self, chars): node = self.document.createTextNode(chars) self.lastEvent[1] = [(CHARACTERS, node), None] self.lastEvent = self.lastEvent[1] def startDocument(self): if self.documentFactory is None: import xml.dom.minidom self.documentFactory = xml.dom.minidom.Document.implementation def buildDocument(self, uri, tagname): # Can't do that in startDocument, since we need the tagname # XXX: obtain DocumentType node = self.documentFactory.createDocument(uri, tagname, None) self.document = node self.lastEvent[1] = [(START_DOCUMENT, node), None] self.lastEvent = self.lastEvent[1] self.push(node) # Put everything we have seen so far into the document for e in self.pending_events: if e[0][0] == PROCESSING_INSTRUCTION: _,target,data = e[0] n = self.document.createProcessingInstruction(target, data) e[0] = (PROCESSING_INSTRUCTION, n) elif e[0][0] == COMMENT: n = self.document.createComment(e[0][1]) e[0] = (COMMENT, n) else: raise AssertionError("Unknown pending event ",e[0][0]) self.lastEvent[1] = e self.lastEvent = e self.pending_events = None return node.firstChild def endDocument(self): self.lastEvent[1] = [(END_DOCUMENT, self.document), None] self.pop() def clear(self): "clear(): Explicitly release parsing structures" self.document = None class ErrorHandler: def warning(self, exception): print(exception) def error(self, exception): raise exception def fatalError(self, exception): raise exception class DOMEventStream: def __init__(self, stream, parser, bufsize): self.stream = stream self.parser = parser self.bufsize = bufsize if not hasattr(self.parser, 'feed'): self.getEvent = self._slurp self.reset() def reset(self): self.pulldom = PullDOM() # This content handler relies on namespace support self.parser.setFeature(xml.sax.handler.feature_namespaces, 1) self.parser.setContentHandler(self.pulldom) def __getitem__(self, pos): rc = self.getEvent() if rc: return rc raise IndexError def __next__(self): rc = self.getEvent() if rc: return rc raise StopIteration def __iter__(self): return self def expandNode(self, node): event = self.getEvent() parents = [node] while event: token, cur_node = event if cur_node is node: return if token != END_ELEMENT: parents[-1].appendChild(cur_node) if token == START_ELEMENT: parents.append(cur_node) elif token == END_ELEMENT: del parents[-1] event = self.getEvent() def getEvent(self): # use IncrementalParser interface, so we get the desired # pull effect if not self.pulldom.firstEvent[1]: self.pulldom.lastEvent = self.pulldom.firstEvent while not self.pulldom.firstEvent[1]: buf = self.stream.read(self.bufsize) if not buf: self.parser.close() return None self.parser.feed(buf) rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc def _slurp(self): """ Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers). """ self.parser.parse(self.stream) self.getEvent = self._emit return self._emit() def _emit(self): """ Fallback replacement for getEvent() that emits the events that _slurp() read previously. """ rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc def clear(self): """clear(): Explicitly release parsing objects""" self.pulldom.clear() del self.pulldom self.parser = None self.stream = None class SAX2DOM(PullDOM): def startElementNS(self, name, tagName , attrs): PullDOM.startElementNS(self, name, tagName, attrs) curNode = self.elementStack[-1] parentNode = self.elementStack[-2] parentNode.appendChild(curNode) def startElement(self, name, attrs): PullDOM.startElement(self, name, attrs) curNode = self.elementStack[-1] parentNode = self.elementStack[-2] parentNode.appendChild(curNode) def processingInstruction(self, target, data): PullDOM.processingInstruction(self, target, data) node = self.lastEvent[0][1] parentNode = self.elementStack[-1] parentNode.appendChild(node) def ignorableWhitespace(self, chars): PullDOM.ignorableWhitespace(self, chars) node = self.lastEvent[0][1] parentNode = self.elementStack[-1] parentNode.appendChild(node) def characters(self, chars): PullDOM.characters(self, chars) node = self.lastEvent[0][1] parentNode = self.elementStack[-1] parentNode.appendChild(node) default_bufsize = (2 ** 14) - 20 def parse(stream_or_string, parser=None, bufsize=None): if bufsize is None: bufsize = default_bufsize if isinstance(stream_or_string, str): stream = open(stream_or_string, 'rb') else: stream = stream_or_string if not parser: parser = xml.sax.make_parser() return DOMEventStream(stream, parser, bufsize) def parseString(string, parser=None): from io import StringIO bufsize = len(string) buf = StringIO(string) if not parser: parser = xml.sax.make_parser() return DOMEventStream(buf, parser, bufsize)
11,761
343
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/domreg.py
"""Registration facilities for DOM. This module should not be used directly. Instead, the functions getDOMImplementation and registerDOMImplementation should be imported from xml.dom.""" # This is a list of well-known implementations. Well-known names # should be published by posting to [email protected], and are # subsequently recorded in this file. import sys well_known_implementations = { 'minidom':'xml.dom.minidom', '4DOM': 'xml.dom.DOMImplementation', } # DOM implementations not officially registered should register # themselves with their registered = {} def registerDOMImplementation(name, factory): """registerDOMImplementation(name, factory) Register the factory function with the name. The factory function should return an object which implements the DOMImplementation interface. The factory function can either return the same object, or a new one (e.g. if that implementation supports some customization).""" registered[name] = factory 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 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 not sys.flags.ignore_environment and "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, str): 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 Exception: # typically ImportError, or AttributeError continue if _good_enough(dom, features): return dom raise ImportError("no suitable DOM implementation found") def _parse_feature_string(s): features = [] parts = s.split() i = 0 length = len(parts) while i < length: feature = parts[i] if feature[0] in "0123456789": raise ValueError("bad feature name: %r" % (feature,)) i = i + 1 version = None if i < length: v = parts[i] if v[0] in "0123456789": i = i + 1 version = v features.append((feature, version)) return tuple(features)
3,451
100
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/minicompat.py
"""Python version compatibility support for minidom. This module contains internal implementation details and should not be imported; use xml.dom.minidom instead. """ # This module should only be imported using "import *". # # The following names are defined: # # NodeList -- lightest possible NodeList implementation # # EmptyNodeList -- lightest possible NodeList that is guaranteed to # remain empty (immutable) # # StringTypes -- tuple of defined string types # # defproperty -- function used in conjunction with GetattrMagic; # using these together is needed to make them work # as efficiently as possible in both Python 2.2+ # and older versions. For example: # # class MyClass(GetattrMagic): # def _get_myattr(self): # return something # # defproperty(MyClass, "myattr", # "return some value") # # For Python 2.2 and newer, this will construct a # property object on the class, which avoids # needing to override __getattr__(). It will only # work for read-only attributes. # # For older versions of Python, inheriting from # GetattrMagic will use the traditional # __getattr__() hackery to achieve the same effect, # but less efficiently. # # defproperty() should be used for each version of # the relevant _get_<property>() function. __all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] import xml.dom StringTypes = (str,) class NodeList(list): __slots__ = () def item(self, index): if 0 <= index < len(self): return self[index] def _get_length(self): return len(self) def _set_length(self, value): raise xml.dom.NoModificationAllowedErr( "attempt to modify read-only attribute 'length'") length = property(_get_length, _set_length, doc="The number of nodes in the NodeList.") # For backward compatibility def __setstate__(self, state): if state is None: state = [] self[:] = state class EmptyNodeList(tuple): __slots__ = () def __add__(self, other): NL = NodeList() NL.extend(other) return NL def __radd__(self, other): NL = NodeList() NL.extend(other) return NL def item(self, index): return None def _get_length(self): return 0 def _set_length(self, value): raise xml.dom.NoModificationAllowedErr( "attempt to modify read-only attribute 'length'") length = property(_get_length, _set_length, doc="The number of nodes in the NodeList.") def defproperty(klass, name, doc): get = getattr(klass, ("_get_" + name)) def set(self, value, name=name): raise xml.dom.NoModificationAllowedErr( "attempt to modify read-only attribute " + repr(name)) assert not hasattr(klass, "_set_" + name), \ "expected not to find _set_" + name prop = property(get, set, doc=doc) setattr(klass, name, prop)
3,367
110
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/xmlbuilder.py
"""Implementation of the DOM Level 3 'LS-Load' feature.""" import copy import warnings import xml.dom from xml.dom.NodeFilter import NodeFilter __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] class Options: """Features object that has variables set for each DOMBuilder feature. The DOMBuilder class uses an instance of this class to pass settings to the ExpatBuilder class. """ # Note that the DOMBuilder class in LoadSave constrains which of these # values can be set using the DOM Level 3 LoadSave feature. namespaces = 1 namespace_declarations = True validation = False external_parameter_entities = True external_general_entities = True external_dtd_subset = True validate_if_schema = False validate = False datatype_normalization = False create_entity_ref_nodes = True entities = True whitespace_in_element_content = True cdata_sections = True comments = True charset_overrides_xml_encoding = True infoset = False supported_mediatypes_only = False errorHandler = None filter = None class DOMBuilder: entityResolver = None errorHandler = None filter = None ACTION_REPLACE = 1 ACTION_APPEND_AS_CHILDREN = 2 ACTION_INSERT_AFTER = 3 ACTION_INSERT_BEFORE = 4 _legal_actions = (ACTION_REPLACE, ACTION_APPEND_AS_CHILDREN, ACTION_INSERT_AFTER, ACTION_INSERT_BEFORE) def __init__(self): self._options = Options() def _get_entityResolver(self): return self.entityResolver def _set_entityResolver(self, entityResolver): self.entityResolver = entityResolver def _get_errorHandler(self): return self.errorHandler def _set_errorHandler(self, errorHandler): self.errorHandler = errorHandler def _get_filter(self): return self.filter def _set_filter(self, filter): self.filter = filter def setFeature(self, name, state): if self.supportsFeature(name): state = state and 1 or 0 try: settings = self._settings[(_name_xform(name), state)] except KeyError: raise xml.dom.NotSupportedErr( "unsupported feature: %r" % (name,)) else: for name, value in settings: setattr(self._options, name, value) else: raise xml.dom.NotFoundErr("unknown feature: " + repr(name)) def supportsFeature(self, name): return hasattr(self._options, _name_xform(name)) def canSetFeature(self, name, state): key = (_name_xform(name), state and 1 or 0) return key in self._settings # This dictionary maps from (feature,value) to a list of # (option,value) pairs that should be set on the Options object. # If a (feature,value) setting is not in this dictionary, it is # not supported by the DOMBuilder. # _settings = { ("namespace_declarations", 0): [ ("namespace_declarations", 0)], ("namespace_declarations", 1): [ ("namespace_declarations", 1)], ("validation", 0): [ ("validation", 0)], ("external_general_entities", 0): [ ("external_general_entities", 0)], ("external_general_entities", 1): [ ("external_general_entities", 1)], ("external_parameter_entities", 0): [ ("external_parameter_entities", 0)], ("external_parameter_entities", 1): [ ("external_parameter_entities", 1)], ("validate_if_schema", 0): [ ("validate_if_schema", 0)], ("create_entity_ref_nodes", 0): [ ("create_entity_ref_nodes", 0)], ("create_entity_ref_nodes", 1): [ ("create_entity_ref_nodes", 1)], ("entities", 0): [ ("create_entity_ref_nodes", 0), ("entities", 0)], ("entities", 1): [ ("entities", 1)], ("whitespace_in_element_content", 0): [ ("whitespace_in_element_content", 0)], ("whitespace_in_element_content", 1): [ ("whitespace_in_element_content", 1)], ("cdata_sections", 0): [ ("cdata_sections", 0)], ("cdata_sections", 1): [ ("cdata_sections", 1)], ("comments", 0): [ ("comments", 0)], ("comments", 1): [ ("comments", 1)], ("charset_overrides_xml_encoding", 0): [ ("charset_overrides_xml_encoding", 0)], ("charset_overrides_xml_encoding", 1): [ ("charset_overrides_xml_encoding", 1)], ("infoset", 0): [], ("infoset", 1): [ ("namespace_declarations", 0), ("validate_if_schema", 0), ("create_entity_ref_nodes", 0), ("entities", 0), ("cdata_sections", 0), ("datatype_normalization", 1), ("whitespace_in_element_content", 1), ("comments", 1), ("charset_overrides_xml_encoding", 1)], ("supported_mediatypes_only", 0): [ ("supported_mediatypes_only", 0)], ("namespaces", 0): [ ("namespaces", 0)], ("namespaces", 1): [ ("namespaces", 1)], } def getFeature(self, name): xname = _name_xform(name) try: return getattr(self._options, xname) except AttributeError: if name == "infoset": options = self._options return (options.datatype_normalization and options.whitespace_in_element_content and options.comments and options.charset_overrides_xml_encoding and not (options.namespace_declarations or options.validate_if_schema or options.create_entity_ref_nodes or options.entities or options.cdata_sections)) raise xml.dom.NotFoundErr("feature %s not known" % repr(name)) def parseURI(self, uri): if self.entityResolver: input = self.entityResolver.resolveEntity(None, uri) else: input = DOMEntityResolver().resolveEntity(None, uri) return self.parse(input) def parse(self, input): options = copy.copy(self._options) options.filter = self.filter options.errorHandler = self.errorHandler fp = input.byteStream if fp is None and options.systemId: import urllib.request fp = urllib.request.urlopen(input.systemId) return self._parse_bytestream(fp, options) def parseWithContext(self, input, cnode, action): if action not in self._legal_actions: raise ValueError("not a legal action") raise NotImplementedError("Haven't written this yet...") def _parse_bytestream(self, stream, options): import xml.dom.expatbuilder builder = xml.dom.expatbuilder.makeBuilder(options) return builder.parseFile(stream) def _name_xform(name): return name.lower().replace('-', '_') class DOMEntityResolver(object): __slots__ = '_opener', def resolveEntity(self, publicId, systemId): assert systemId is not None source = DOMInputSource() source.publicId = publicId source.systemId = systemId source.byteStream = self._get_opener().open(systemId) # determine the encoding if the transport provided it source.encoding = self._guess_media_encoding(source) # determine the base URI is we can import posixpath, urllib.parse parts = urllib.parse.urlparse(systemId) scheme, netloc, path, params, query, fragment = parts # XXX should we check the scheme here as well? if path and not path.endswith("/"): path = posixpath.dirname(path) + "/" parts = scheme, netloc, path, params, query, fragment source.baseURI = urllib.parse.urlunparse(parts) return source def _get_opener(self): try: return self._opener except AttributeError: self._opener = self._create_opener() return self._opener def _create_opener(self): import urllib.request return urllib.request.build_opener() def _guess_media_encoding(self, source): info = source.byteStream.info() if "Content-Type" in info: for param in info.getplist(): if param.startswith("charset="): return param.split("=", 1)[1].lower() class DOMInputSource(object): __slots__ = ('byteStream', 'characterStream', 'stringData', 'encoding', 'publicId', 'systemId', 'baseURI') def __init__(self): self.byteStream = None self.characterStream = None self.stringData = None self.encoding = None self.publicId = None self.systemId = None self.baseURI = None def _get_byteStream(self): return self.byteStream def _set_byteStream(self, byteStream): self.byteStream = byteStream def _get_characterStream(self): return self.characterStream def _set_characterStream(self, characterStream): self.characterStream = characterStream def _get_stringData(self): return self.stringData def _set_stringData(self, data): self.stringData = data def _get_encoding(self): return self.encoding def _set_encoding(self, encoding): self.encoding = encoding def _get_publicId(self): return self.publicId def _set_publicId(self, publicId): self.publicId = publicId def _get_systemId(self): return self.systemId def _set_systemId(self, systemId): self.systemId = systemId def _get_baseURI(self): return self.baseURI def _set_baseURI(self, uri): self.baseURI = uri class DOMBuilderFilter: """Element filter which can be used to tailor construction of a DOM instance. """ # There's really no need for this class; concrete implementations # should just implement the endElement() and startElement() # methods as appropriate. Using this makes it easy to only # implement one of them. FILTER_ACCEPT = 1 FILTER_REJECT = 2 FILTER_SKIP = 3 FILTER_INTERRUPT = 4 whatToShow = NodeFilter.SHOW_ALL def _get_whatToShow(self): return self.whatToShow def acceptNode(self, element): return self.FILTER_ACCEPT def startContainer(self, element): return self.FILTER_ACCEPT del NodeFilter class _AsyncDeprecatedProperty: def warn(self, cls): clsname = cls.__name__ warnings.warn( "{cls}.async is deprecated; use {cls}.async_".format(cls=clsname), DeprecationWarning) def __get__(self, instance, cls): self.warn(cls) if instance is not None: return instance.async_ return False def __set__(self, instance, value): self.warn(type(instance)) setattr(instance, 'async_', value) class DocumentLS: """Mixin to create documents that conform to the load/save spec.""" async_ = False locals()['async'] = _AsyncDeprecatedProperty() # Avoid DeprecationWarning def _get_async(self): return False def _set_async(self, flag): if flag: raise xml.dom.NotSupportedErr( "asynchronous document loading is not supported") def abort(self): # What does it mean to "clear" a document? Does the # documentElement disappear? raise NotImplementedError( "haven't figured out what this means yet") def load(self, uri): raise NotImplementedError("haven't written this yet") def loadXML(self, source): raise NotImplementedError("haven't written this yet") def saveXML(self, snode): if snode is None: snode = self elif snode.ownerDocument is not self: raise xml.dom.WrongDocumentErr() return snode.toxml() del _AsyncDeprecatedProperty class DOMImplementationLS: MODE_SYNCHRONOUS = 1 MODE_ASYNCHRONOUS = 2 def createDOMBuilder(self, mode, schemaType): if schemaType is not None: raise xml.dom.NotSupportedErr( "schemaType not yet supported") if mode == self.MODE_SYNCHRONOUS: return DOMBuilder() if mode == self.MODE_ASYNCHRONOUS: raise xml.dom.NotSupportedErr( "asynchronous builders are not supported") raise ValueError("unknown value for mode") def createDOMWriter(self): raise NotImplementedError( "the writer interface hasn't been written yet!") def createDOMInputSource(self): return DOMInputSource()
12,996
411
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/__init__.py
"""W3C Document Object Model implementation for Python. The Python mapping of the Document Object Model is documented in the Python Library Reference in the section on the xml.dom package. This package contains the following modules: minidom -- A simple implementation of the Level 1 DOM with namespace support added (based on the Level 2 specification) and other minor Level 2 functionality. pulldom -- DOM builder supporting on-demand tree-building for selected subtrees of the document. """ class Node: """Class giving the NodeType constants.""" __slots__ = () # DOM implementations may use this as a base class for their own # Node implementations. If they don't, the constants defined here # should still be used as the canonical definitions as they match # the values given in the W3C recommendation. Client code can # safely refer to these values in all tests of Node.nodeType # values. ELEMENT_NODE = 1 ATTRIBUTE_NODE = 2 TEXT_NODE = 3 CDATA_SECTION_NODE = 4 ENTITY_REFERENCE_NODE = 5 ENTITY_NODE = 6 PROCESSING_INSTRUCTION_NODE = 7 COMMENT_NODE = 8 DOCUMENT_NODE = 9 DOCUMENT_TYPE_NODE = 10 DOCUMENT_FRAGMENT_NODE = 11 NOTATION_NODE = 12 #ExceptionCode INDEX_SIZE_ERR = 1 DOMSTRING_SIZE_ERR = 2 HIERARCHY_REQUEST_ERR = 3 WRONG_DOCUMENT_ERR = 4 INVALID_CHARACTER_ERR = 5 NO_DATA_ALLOWED_ERR = 6 NO_MODIFICATION_ALLOWED_ERR = 7 NOT_FOUND_ERR = 8 NOT_SUPPORTED_ERR = 9 INUSE_ATTRIBUTE_ERR = 10 INVALID_STATE_ERR = 11 SYNTAX_ERR = 12 INVALID_MODIFICATION_ERR = 13 NAMESPACE_ERR = 14 INVALID_ACCESS_ERR = 15 VALIDATION_ERR = 16 class DOMException(Exception): """Abstract base class for DOM exceptions. Exceptions with specific codes are specializations of this class.""" def __init__(self, *args, **kw): if self.__class__ is DOMException: raise RuntimeError( "DOMException should not be instantiated directly") Exception.__init__(self, *args, **kw) def _get_code(self): return self.code class IndexSizeErr(DOMException): code = INDEX_SIZE_ERR class DomstringSizeErr(DOMException): code = DOMSTRING_SIZE_ERR class HierarchyRequestErr(DOMException): code = HIERARCHY_REQUEST_ERR class WrongDocumentErr(DOMException): code = WRONG_DOCUMENT_ERR class InvalidCharacterErr(DOMException): code = INVALID_CHARACTER_ERR class NoDataAllowedErr(DOMException): code = NO_DATA_ALLOWED_ERR class NoModificationAllowedErr(DOMException): code = NO_MODIFICATION_ALLOWED_ERR class NotFoundErr(DOMException): code = NOT_FOUND_ERR class NotSupportedErr(DOMException): code = NOT_SUPPORTED_ERR class InuseAttributeErr(DOMException): code = INUSE_ATTRIBUTE_ERR class InvalidStateErr(DOMException): code = INVALID_STATE_ERR class SyntaxErr(DOMException): code = SYNTAX_ERR class InvalidModificationErr(DOMException): code = INVALID_MODIFICATION_ERR class NamespaceErr(DOMException): code = NAMESPACE_ERR class InvalidAccessErr(DOMException): code = INVALID_ACCESS_ERR class ValidationErr(DOMException): code = VALIDATION_ERR class UserDataHandler: """Class giving the operation constants for UserDataHandler.handle().""" # Based on DOM Level 3 (WD 9 April 2002) NODE_CLONED = 1 NODE_IMPORTED = 2 NODE_DELETED = 3 NODE_RENAMED = 4 XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/" XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml" EMPTY_NAMESPACE = None EMPTY_PREFIX = None from .domreg import getDOMImplementation, registerDOMImplementation
4,019
141
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xml/dom/minidom.py
"""Simple implementation of the Level 1 DOM. Namespaces and other minor Level 2 features are also supported. parse("foo.xml") parseString("<foo><bar/></foo>") Todo: ===== * convenience methods for getting elements and text. * more testing * bring some of the writer and linearizer code into conformance with this interface * SAX 2 namespaces """ import io import xml.dom from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg from xml.dom.minicompat import * from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS # This is used by the ID-cache invalidation checks; the list isn't # actually complete, since the nodes being checked will never be the # DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is # the node being added or removed, not the node being modified.) # _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE, xml.dom.Node.ENTITY_REFERENCE_NODE) class Node(xml.dom.Node): namespaceURI = None # this is non-null only for elements and attributes parentNode = None ownerDocument = None nextSibling = None previousSibling = None prefix = EMPTY_PREFIX # non-null only for NS elements and attributes def __bool__(self): return True def toxml(self, encoding=None): return self.toprettyxml("", "", encoding) def toprettyxml(self, indent="\t", newl="\n", encoding=None): if encoding is None: writer = io.StringIO() else: writer = io.TextIOWrapper(io.BytesIO(), encoding=encoding, errors="xmlcharrefreplace", newline='\n') if self.nodeType == Node.DOCUMENT_NODE: # Can pass encoding only to document, to put it into XML header self.writexml(writer, "", indent, newl, encoding) else: self.writexml(writer, "", indent, newl) if encoding is None: return writer.getvalue() else: return writer.detach().getvalue() def hasChildNodes(self): return bool(self.childNodes) def _get_childNodes(self): return self.childNodes def _get_firstChild(self): if self.childNodes: return self.childNodes[0] def _get_lastChild(self): if self.childNodes: return self.childNodes[-1] def insertBefore(self, newChild, refChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(newChild.childNodes): self.insertBefore(c, refChild) ### The DOM does not clearly specify what to return in this case return newChild if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: try: index = self.childNodes.index(refChild) except ValueError: raise xml.dom.NotFoundErr() if newChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None newChild.parentNode = self return newChild def appendChild(self, node): if node.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(node.childNodes): self.appendChild(c) ### The DOM does not clearly specify what to return in this case return node if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) elif node.nodeType in _nodeTypes_with_children: _clear_id_cache(self) if node.parentNode is not None: node.parentNode.removeChild(node) _append_child(self, node) node.nextSibling = None return node def replaceChild(self, newChild, oldChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: refChild = oldChild.nextSibling self.removeChild(oldChild) return self.insertBefore(newChild, refChild) if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild is oldChild: return if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) try: index = self.childNodes.index(oldChild) except ValueError: raise xml.dom.NotFoundErr() self.childNodes[index] = newChild newChild.parentNode = self oldChild.parentNode = None if (newChild.nodeType in _nodeTypes_with_children or oldChild.nodeType in _nodeTypes_with_children): _clear_id_cache(self) newChild.nextSibling = oldChild.nextSibling newChild.previousSibling = oldChild.previousSibling oldChild.nextSibling = None oldChild.previousSibling = None if newChild.previousSibling: newChild.previousSibling.nextSibling = newChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild return oldChild def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() if oldChild.nextSibling is not None: oldChild.nextSibling.previousSibling = oldChild.previousSibling if oldChild.previousSibling is not None: oldChild.previousSibling.nextSibling = oldChild.nextSibling oldChild.nextSibling = oldChild.previousSibling = None if oldChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) oldChild.parentNode = None return oldChild def normalize(self): L = [] for child in self.childNodes: if child.nodeType == Node.TEXT_NODE: if not child.data: # empty text node; discard if L: L[-1].nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = child.previousSibling child.unlink() elif L and L[-1].nodeType == child.nodeType: # collapse text node node = L[-1] node.data = node.data + child.data node.nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = node child.unlink() else: L.append(child) else: L.append(child) if child.nodeType == Node.ELEMENT_NODE: child.normalize() self.childNodes[:] = L def cloneNode(self, deep): return _clone_node(self, deep, self.ownerDocument or self) def isSupported(self, feature, version): return self.ownerDocument.implementation.hasFeature(feature, version) def _get_localName(self): # Overridden in Element and Attr where localName can be Non-Null return None # Node interfaces from Level 3 (WD 9 April 2002) def isSameNode(self, other): return self is other def getInterface(self, feature): if self.isSupported(feature, None): return self else: return None # The "user data" functions use a dictionary that is only present # if some user data has been set, so be careful not to assume it # exists. def getUserData(self, key): try: return self._user_data[key][0] except (AttributeError, KeyError): return None def setUserData(self, key, data, handler): old = None try: d = self._user_data except AttributeError: d = {} self._user_data = d if key in d: old = d[key][0] if data is None: # ignore handlers passed for None handler = None if old is not None: del d[key] else: d[key] = (data, handler) return old def _call_user_data_handler(self, operation, src, dst): if hasattr(self, "_user_data"): for key, (data, handler) in list(self._user_data.items()): if handler is not None: handler.handle(operation, key, data, src, dst) # minidom-specific API: def unlink(self): self.parentNode = self.ownerDocument = None if self.childNodes: for child in self.childNodes: child.unlink() self.childNodes = NodeList() self.previousSibling = None self.nextSibling = None # A Node is its own context manager, to ensure that an unlink() call occurs. # This is similar to how a file object works. def __enter__(self): return self def __exit__(self, et, ev, tb): self.unlink() defproperty(Node, "firstChild", doc="First child node, or None.") defproperty(Node, "lastChild", doc="Last child node, or None.") defproperty(Node, "localName", doc="Namespace-local name of this node.") def _append_child(self, node): # fast path with less checks; usable by DOM builders if careful childNodes = self.childNodes if childNodes: last = childNodes[-1] node.previousSibling = last last.nextSibling = node childNodes.append(node) node.parentNode = self def _in_document(node): # return True iff node is part of a document tree while node is not None: if node.nodeType == Node.DOCUMENT_NODE: return True node = node.parentNode return False def _write_data(writer, data): "Writes datachars to writer." if data: data = data.replace("&", "&amp;").replace("<", "&lt;"). \ replace("\"", "&quot;").replace(">", "&gt;") writer.write(data) def _get_elements_by_tagName_helper(parent, name, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE and \ (name == "*" or node.tagName == name): rc.append(node) _get_elements_by_tagName_helper(node, name, rc) return rc def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.localName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc) return rc class DocumentFragment(Node): nodeType = Node.DOCUMENT_FRAGMENT_NODE nodeName = "#document-fragment" nodeValue = None attributes = None parentNode = None _child_node_types = (Node.ELEMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.NOTATION_NODE) def __init__(self): self.childNodes = NodeList() class Attr(Node): __slots__=('_name', '_value', 'namespaceURI', '_prefix', 'childNodes', '_localName', 'ownerDocument', 'ownerElement') nodeType = Node.ATTRIBUTE_NODE attributes = None specified = False _is_id = False _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None, prefix=None): self.ownerElement = None self._name = qName self.namespaceURI = namespaceURI self._prefix = prefix self.childNodes = NodeList() # Add the single child node that represents the value of the attr self.childNodes.append(Text()) # nodeValue and value are set elsewhere def _get_localName(self): try: return self._localName except AttributeError: return self.nodeName.split(":", 1)[-1] def _get_specified(self): return self.specified def _get_name(self): return self._name def _set_name(self, value): self._name = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) nodeName = name = property(_get_name, _set_name) def _get_value(self): return self._value def _set_value(self, value): self._value = value self.childNodes[0].data = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) self.childNodes[0].data = value nodeValue = value = property(_get_value, _set_value) def _get_prefix(self): return self._prefix def _set_prefix(self, prefix): nsuri = self.namespaceURI if prefix == "xmlns": if nsuri and nsuri != XMLNS_NAMESPACE: raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix for the wrong namespace") self._prefix = prefix if prefix is None: newName = self.localName else: newName = "%s:%s" % (prefix, self.localName) if self.ownerElement: _clear_id_cache(self.ownerElement) self.name = newName prefix = property(_get_prefix, _set_prefix) def unlink(self): # This implementation does not call the base implementation # since most of that is not needed, and the expense of the # method call is not warranted. We duplicate the removal of # children, but that's all we needed from the base class. elem = self.ownerElement if elem is not None: del elem._attrs[self.nodeName] del elem._attrsNS[(self.namespaceURI, self.localName)] if self._is_id: self._is_id = False elem._magic_id_nodes -= 1 self.ownerDocument._magic_id_count -= 1 for child in self.childNodes: child.unlink() del self.childNodes[:] def _get_isId(self): if self._is_id: return True doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return False info = doc._get_elem_info(elem) if info is None: return False if self.namespaceURI: return info.isIdNS(self.namespaceURI, self.localName) else: return info.isId(self.nodeName) def _get_schemaType(self): doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return _no_type info = doc._get_elem_info(elem) if info is None: return _no_type if self.namespaceURI: return info.getAttributeTypeNS(self.namespaceURI, self.localName) else: return info.getAttributeType(self.nodeName) defproperty(Attr, "isId", doc="True if this attribute is an ID.") defproperty(Attr, "localName", doc="Namespace-local name of this attribute.") defproperty(Attr, "schemaType", doc="Schema type for this attribute.") class NamedNodeMap(object): """The attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. Ordering is imposed artificially and does not reflect the order of attributes as found in an input document. """ __slots__ = ('_attrs', '_attrsNS', '_ownerElement') def __init__(self, attrs, attrsNS, ownerElement): self._attrs = attrs self._attrsNS = attrsNS self._ownerElement = ownerElement def _get_length(self): return len(self._attrs) def item(self, index): try: return self[list(self._attrs.keys())[index]] except IndexError: return None def items(self): L = [] for node in self._attrs.values(): L.append((node.nodeName, node.value)) return L def itemsNS(self): L = [] for node in self._attrs.values(): L.append(((node.namespaceURI, node.localName), node.value)) return L def __contains__(self, key): if isinstance(key, str): return key in self._attrs else: return key in self._attrsNS def keys(self): return self._attrs.keys() def keysNS(self): return self._attrsNS.keys() def values(self): return self._attrs.values() def get(self, name, value=None): return self._attrs.get(name, value) __len__ = _get_length def _cmp(self, other): if self._attrs is getattr(other, "_attrs", None): return 0 else: return (id(self) > id(other)) - (id(self) < id(other)) def __eq__(self, other): return self._cmp(other) == 0 def __ge__(self, other): return self._cmp(other) >= 0 def __gt__(self, other): return self._cmp(other) > 0 def __le__(self, other): return self._cmp(other) <= 0 def __lt__(self, other): return self._cmp(other) < 0 def __getitem__(self, attname_or_tuple): if isinstance(attname_or_tuple, tuple): return self._attrsNS[attname_or_tuple] else: return self._attrs[attname_or_tuple] # same as set def __setitem__(self, attname, value): if isinstance(value, str): try: node = self._attrs[attname] except KeyError: node = Attr(attname) node.ownerDocument = self._ownerElement.ownerDocument self.setNamedItem(node) node.value = value else: if not isinstance(value, Attr): raise TypeError("value must be a string or Attr object") node = value self.setNamedItem(node) def getNamedItem(self, name): try: return self._attrs[name] except KeyError: return None def getNamedItemNS(self, namespaceURI, localName): try: return self._attrsNS[(namespaceURI, localName)] except KeyError: return None def removeNamedItem(self, name): n = self.getNamedItem(name) if n is not None: _clear_id_cache(self._ownerElement) del self._attrs[n.nodeName] del self._attrsNS[(n.namespaceURI, n.localName)] if hasattr(n, 'ownerElement'): n.ownerElement = None return n else: raise xml.dom.NotFoundErr() def removeNamedItemNS(self, namespaceURI, localName): n = self.getNamedItemNS(namespaceURI, localName) if n is not None: _clear_id_cache(self._ownerElement) del self._attrsNS[(n.namespaceURI, n.localName)] del self._attrs[n.nodeName] if hasattr(n, 'ownerElement'): n.ownerElement = None return n else: raise xml.dom.NotFoundErr() def setNamedItem(self, node): if not isinstance(node, Attr): raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) old = self._attrs.get(node.name) if old: old.unlink() self._attrs[node.name] = node self._attrsNS[(node.namespaceURI, node.localName)] = node node.ownerElement = self._ownerElement _clear_id_cache(node.ownerElement) return old def setNamedItemNS(self, node): return self.setNamedItem(node) def __delitem__(self, attname_or_tuple): node = self[attname_or_tuple] _clear_id_cache(node.ownerElement) node.unlink() def __getstate__(self): return self._attrs, self._attrsNS, self._ownerElement def __setstate__(self, state): self._attrs, self._attrsNS, self._ownerElement = state defproperty(NamedNodeMap, "length", doc="Number of nodes in the NamedNodeMap.") AttributeList = NamedNodeMap class TypeInfo(object): __slots__ = 'namespace', 'name' def __init__(self, namespace, name): self.namespace = namespace self.name = name def __repr__(self): if self.namespace: return "<%s %r (from %r)>" % (self.__class__.__name__, self.name, self.namespace) else: return "<%s %r>" % (self.__class__.__name__, self.name) def _get_name(self): return self.name def _get_namespace(self): return self.namespace _no_type = TypeInfo(None, None) class Element(Node): __slots__=('ownerDocument', 'parentNode', 'tagName', 'nodeName', 'prefix', 'namespaceURI', '_localName', 'childNodes', '_attrs', '_attrsNS', 'nextSibling', 'previousSibling') nodeType = Node.ELEMENT_NODE nodeValue = None schemaType = _no_type _magic_id_nodes = 0 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, localName=None): self.parentNode = None self.tagName = self.nodeName = tagName self.prefix = prefix self.namespaceURI = namespaceURI self.childNodes = NodeList() self.nextSibling = self.previousSibling = None # Attribute dictionaries are lazily created # attributes are double-indexed: # tagName -> Attribute # URI,localName -> Attribute # in the future: consider lazy generation # of attribute objects this is too tricky # for now because of headaches with # namespaces. self._attrs = None self._attrsNS = None def _ensure_attributes(self): if self._attrs is None: self._attrs = {} self._attrsNS = {} def _get_localName(self): try: return self._localName except AttributeError: return self.tagName.split(":", 1)[-1] def _get_tagName(self): return self.tagName def unlink(self): if self._attrs is not None: for attr in list(self._attrs.values()): attr.unlink() self._attrs = None self._attrsNS = None Node.unlink(self) def getAttribute(self, attname): if self._attrs is None: return "" try: return self._attrs[attname].value except KeyError: return "" def getAttributeNS(self, namespaceURI, localName): if self._attrsNS is None: return "" try: return self._attrsNS[(namespaceURI, localName)].value except KeyError: return "" def setAttribute(self, attname, value): attr = self.getAttributeNode(attname) if attr is None: attr = Attr(attname) attr.value = value # also sets nodeValue attr.ownerDocument = self.ownerDocument self.setAttributeNode(attr) elif value != attr.value: attr.value = value if attr.isId: _clear_id_cache(self) def setAttributeNS(self, namespaceURI, qualifiedName, value): prefix, localname = _nssplit(qualifiedName) attr = self.getAttributeNodeNS(namespaceURI, localname) if attr is None: attr = Attr(qualifiedName, namespaceURI, localname, prefix) attr.value = value attr.ownerDocument = self.ownerDocument self.setAttributeNode(attr) else: if value != attr.value: attr.value = value if attr.isId: _clear_id_cache(self) if attr.prefix != prefix: attr.prefix = prefix attr.nodeName = qualifiedName def getAttributeNode(self, attrname): if self._attrs is None: return None return self._attrs.get(attrname) def getAttributeNodeNS(self, namespaceURI, localName): if self._attrsNS is None: return None return self._attrsNS.get((namespaceURI, localName)) def setAttributeNode(self, attr): if attr.ownerElement not in (None, self): raise xml.dom.InuseAttributeErr("attribute node already owned") self._ensure_attributes() old1 = self._attrs.get(attr.name, None) if old1 is not None: self.removeAttributeNode(old1) old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None) if old2 is not None and old2 is not old1: self.removeAttributeNode(old2) _set_attribute_node(self, attr) if old1 is not attr: # It might have already been part of this node, in which case # it doesn't represent a change, and should not be returned. return old1 if old2 is not attr: return old2 setAttributeNodeNS = setAttributeNode def removeAttribute(self, name): if self._attrsNS is None: raise xml.dom.NotFoundErr() try: attr = self._attrs[name] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNS(self, namespaceURI, localName): if self._attrsNS is None: raise xml.dom.NotFoundErr() try: attr = self._attrsNS[(namespaceURI, localName)] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNode(self, node): if node is None: raise xml.dom.NotFoundErr() try: self._attrs[node.name] except KeyError: raise xml.dom.NotFoundErr() _clear_id_cache(self) node.unlink() # Restore this since the node is still useful and otherwise # unlinked node.ownerDocument = self.ownerDocument removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name): if self._attrs is None: return False return name in self._attrs def hasAttributeNS(self, namespaceURI, localName): if self._attrsNS is None: return False return (namespaceURI, localName) in self._attrsNS def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def __repr__(self): return "<DOM Element: %s at %#x>" % (self.tagName, id(self)) def writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(" %s=\"" % a_name) _write_data(writer, attrs[a_name].value) writer.write("\"") if self.childNodes: writer.write(">") if (len(self.childNodes) == 1 and self.childNodes[0].nodeType == Node.TEXT_NODE): self.childNodes[0].writexml(writer, '', '', '') else: writer.write(newl) for node in self.childNodes: node.writexml(writer, indent+addindent, addindent, newl) writer.write(indent) writer.write("</%s>%s" % (self.tagName, newl)) else: writer.write("/>%s"%(newl)) def _get_attributes(self): self._ensure_attributes() return NamedNodeMap(self._attrs, self._attrsNS, self) def hasAttributes(self): if self._attrs: return True else: return False # DOM Level 3 attributes, based on the 22 Oct 2002 draft def setIdAttribute(self, name): idAttr = self.getAttributeNode(name) self.setIdAttributeNode(idAttr) def setIdAttributeNS(self, namespaceURI, localName): idAttr = self.getAttributeNodeNS(namespaceURI, localName) self.setIdAttributeNode(idAttr) def setIdAttributeNode(self, idAttr): if idAttr is None or not self.isSameNode(idAttr.ownerElement): raise xml.dom.NotFoundErr() if _get_containing_entref(self) is not None: raise xml.dom.NoModificationAllowedErr() if not idAttr._is_id: idAttr._is_id = True self._magic_id_nodes += 1 self.ownerDocument._magic_id_count += 1 _clear_id_cache(self) defproperty(Element, "attributes", doc="NamedNodeMap of attributes on the element.") defproperty(Element, "localName", doc="Namespace-local name of this element.") def _set_attribute_node(element, attr): _clear_id_cache(element) element._ensure_attributes() element._attrs[attr.name] = attr element._attrsNS[(attr.namespaceURI, attr.localName)] = attr # This creates a circular reference, but Element.unlink() # breaks the cycle since the references to the attribute # dictionaries are tossed. attr.ownerElement = element class Childless: """Mixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. """ __slots__ = () attributes = None childNodes = EmptyNodeList() firstChild = None lastChild = None def _get_firstChild(self): return None def _get_lastChild(self): return None def appendChild(self, node): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes cannot have children") def hasChildNodes(self): return False def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") def removeChild(self, oldChild): raise xml.dom.NotFoundErr( self.nodeName + " nodes do not have children") def normalize(self): # For childless nodes, normalize() has nothing to do. pass def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") class ProcessingInstruction(Childless, Node): nodeType = Node.PROCESSING_INSTRUCTION_NODE __slots__ = ('target', 'data') def __init__(self, target, data): self.target = target self.data = data # nodeValue is an alias for data def _get_nodeValue(self): return self.data def _set_nodeValue(self, value): self.data = value nodeValue = property(_get_nodeValue, _set_nodeValue) # nodeName is an alias for target def _get_nodeName(self): return self.target def _set_nodeName(self, value): self.target = value nodeName = property(_get_nodeName, _set_nodeName) def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl)) class CharacterData(Childless, Node): __slots__=('_data', 'ownerDocument','parentNode', 'previousSibling', 'nextSibling') def __init__(self): self.ownerDocument = self.parentNode = None self.previousSibling = self.nextSibling = None self._data = '' Node.__init__(self) def _get_length(self): return len(self.data) __len__ = _get_length def _get_data(self): return self._data def _set_data(self, data): self._data = data data = nodeValue = property(_get_data, _set_data) def __repr__(self): data = self.data if len(data) > 10: dotdotdot = "..." else: dotdotdot = "" return '<DOM %s node "%r%s">' % ( self.__class__.__name__, data[0:10], dotdotdot) def substringData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") return self.data[offset:offset+count] def appendData(self, arg): self.data = self.data + arg def insertData(self, offset, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if arg: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset:]) def deleteData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = self.data[:offset] + self.data[offset+count:] def replaceData(self, offset, count, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset+count:]) defproperty(CharacterData, "length", doc="Length of the string data.") class Text(CharacterData): __slots__ = () nodeType = Node.TEXT_NODE nodeName = "#text" attributes = None def splitText(self, offset): if offset < 0 or offset > len(self.data): raise xml.dom.IndexSizeErr("illegal offset value") newText = self.__class__() newText.data = self.data[offset:] newText.ownerDocument = self.ownerDocument next = self.nextSibling if self.parentNode and self in self.parentNode.childNodes: if next is None: self.parentNode.appendChild(newText) else: self.parentNode.insertBefore(newText, next) self.data = self.data[:offset] return newText def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "%s%s%s" % (indent, self.data, newl)) # DOM Level 3 (WD 9 April 2002) def _get_wholeText(self): L = [self.data] n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.insert(0, n.data) n = n.previousSibling else: break n = self.nextSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.append(n.data) n = n.nextSibling else: break return ''.join(L) def replaceWholeText(self, content): # XXX This needs to be seriously changed if minidom ever # supports EntityReference nodes. parent = self.parentNode n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.previousSibling parent.removeChild(n) n = next else: break n = self.nextSibling if not content: parent.removeChild(self) while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.nextSibling parent.removeChild(n) n = next else: break if content: self.data = content return self else: return None def _get_isWhitespaceInElementContent(self): if self.data.strip(): return False elem = _get_containing_element(self) if elem is None: return False info = self.ownerDocument._get_elem_info(elem) if info is None: return False else: return info.isElementContent() defproperty(Text, "isWhitespaceInElementContent", doc="True iff this text node contains only whitespace" " and is in element content.") defproperty(Text, "wholeText", doc="The text of all logically-adjacent text nodes.") def _get_containing_element(node): c = node.parentNode while c is not None: if c.nodeType == Node.ELEMENT_NODE: return c c = c.parentNode return None def _get_containing_entref(node): c = node.parentNode while c is not None: if c.nodeType == Node.ENTITY_REFERENCE_NODE: return c c = c.parentNode return None class Comment(CharacterData): nodeType = Node.COMMENT_NODE nodeName = "#comment" def __init__(self, data): CharacterData.__init__(self) self._data = data def writexml(self, writer, indent="", addindent="", newl=""): if "--" in self.data: raise ValueError("'--' is not allowed in a comment node") writer.write("%s<!--%s-->%s" % (indent, self.data, newl)) class CDATASection(Text): __slots__ = () nodeType = Node.CDATA_SECTION_NODE nodeName = "#cdata-section" def writexml(self, writer, indent="", addindent="", newl=""): if self.data.find("]]>") >= 0: raise ValueError("']]>' not allowed in a CDATA section") writer.write("<![CDATA[%s]]>" % self.data) class ReadOnlySequentialNamedNodeMap(object): __slots__ = '_seq', def __init__(self, seq=()): # seq should be a list or tuple self._seq = seq def __len__(self): return len(self._seq) def _get_length(self): return len(self._seq) def getNamedItem(self, name): for n in self._seq: if n.nodeName == name: return n def getNamedItemNS(self, namespaceURI, localName): for n in self._seq: if n.namespaceURI == namespaceURI and n.localName == localName: return n def __getitem__(self, name_or_tuple): if isinstance(name_or_tuple, tuple): node = self.getNamedItemNS(*name_or_tuple) else: node = self.getNamedItem(name_or_tuple) if node is None: raise KeyError(name_or_tuple) return node def item(self, index): if index < 0: return None try: return self._seq[index] except IndexError: return None def removeNamedItem(self, name): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def removeNamedItemNS(self, namespaceURI, localName): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItem(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItemNS(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def __getstate__(self): return [self._seq] def __setstate__(self, state): self._seq = state[0] defproperty(ReadOnlySequentialNamedNodeMap, "length", doc="Number of entries in the NamedNodeMap.") class Identified: """Mix-in class that supports the publicId and systemId attributes.""" __slots__ = 'publicId', 'systemId' def _identified_mixin_init(self, publicId, systemId): self.publicId = publicId self.systemId = systemId def _get_publicId(self): return self.publicId def _get_systemId(self): return self.systemId class DocumentType(Identified, Childless, Node): nodeType = Node.DOCUMENT_TYPE_NODE nodeValue = None name = None publicId = None systemId = None internalSubset = None def __init__(self, qualifiedName): self.entities = ReadOnlySequentialNamedNodeMap() self.notations = ReadOnlySequentialNamedNodeMap() if qualifiedName: prefix, localname = _nssplit(qualifiedName) self.name = localname self.nodeName = self.name def _get_internalSubset(self): return self.internalSubset def cloneNode(self, deep): if self.ownerDocument is None: # it's ok clone = DocumentType(None) clone.name = self.name clone.nodeName = self.name operation = xml.dom.UserDataHandler.NODE_CLONED if deep: clone.entities._seq = [] clone.notations._seq = [] for n in self.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) clone.notations._seq.append(notation) n._call_user_data_handler(operation, n, notation) for e in self.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version clone.entities._seq.append(entity) e._call_user_data_handler(operation, e, entity) self._call_user_data_handler(operation, self, clone) return clone else: return None def writexml(self, writer, indent="", addindent="", newl=""): writer.write("<!DOCTYPE ") writer.write(self.name) if self.publicId: writer.write("%s PUBLIC '%s'%s '%s'" % (newl, self.publicId, newl, self.systemId)) elif self.systemId: writer.write("%s SYSTEM '%s'" % (newl, self.systemId)) if self.internalSubset is not None: writer.write(" [") writer.write(self.internalSubset) writer.write("]") writer.write(">"+newl) class Entity(Identified, Node): attributes = None nodeType = Node.ENTITY_NODE nodeValue = None actualEncoding = None encoding = None version = None def __init__(self, name, publicId, systemId, notation): self.nodeName = name self.notationName = notation self.childNodes = NodeList() self._identified_mixin_init(publicId, systemId) def _get_actualEncoding(self): return self.actualEncoding def _get_encoding(self): return self.encoding def _get_version(self): return self.version def appendChild(self, newChild): raise xml.dom.HierarchyRequestErr( "cannot append children to an entity node") def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( "cannot insert children below an entity node") def removeChild(self, oldChild): raise xml.dom.HierarchyRequestErr( "cannot remove children from an entity node") def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( "cannot replace children of an entity node") class Notation(Identified, Childless, Node): nodeType = Node.NOTATION_NODE nodeValue = None def __init__(self, name, publicId, systemId): self.nodeName = name self._identified_mixin_init(publicId, systemId) class DOMImplementation(DOMImplementationLS): _features = [("core", "1.0"), ("core", "2.0"), ("core", None), ("xml", "1.0"), ("xml", "2.0"), ("xml", None), ("ls-load", "3.0"), ("ls-load", None), ] def hasFeature(self, feature, version): if version == "": version = None return (feature.lower(), version) in self._features def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr( "doctype object owned by another DOM tree") doc = self._create_document() add_root_element = not (namespaceURI is None and qualifiedName is None and doctype is None) if not qualifiedName and add_root_element: # The spec is unclear what to raise here; SyntaxErr # would be the other obvious candidate. Since Xerces raises # InvalidCharacterErr, and since SyntaxErr is not listed # for createDocument, that seems to be the better choice. # XXX: need to check for illegal characters here and in # createElement. # DOM Level III clears this up when talking about the return value # of this function. If namespaceURI, qName and DocType are # Null the document is returned without a document element # Otherwise if doctype or namespaceURI are not None # Then we go back to the above problem raise xml.dom.InvalidCharacterErr("Element with no name") if add_root_element: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr( "illegal use of prefix without namespaces") element = doc.createElementNS(namespaceURI, qualifiedName) if doctype: doc.appendChild(doctype) doc.appendChild(element) if doctype: doctype.parentNode = doctype.ownerDocument = doc doc.doctype = doctype doc.implementation = self return doc def createDocumentType(self, qualifiedName, publicId, systemId): doctype = DocumentType(qualifiedName) doctype.publicId = publicId doctype.systemId = systemId return doctype # DOM Level 3 (WD 9 April 2002) def getInterface(self, feature): if self.hasFeature(feature, None): return self else: return None # internal def _create_document(self): return Document() class ElementInfo(object): """Object that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing using information available to it. """ __slots__ = 'tagName', def __init__(self, name): self.tagName = name def getAttributeType(self, aname): return _no_type def getAttributeTypeNS(self, namespaceURI, localName): return _no_type def isElementContent(self): return False def isEmpty(self): """Returns true iff this element is declared to have an EMPTY content model.""" return False def isId(self, aname): """Returns true iff the named attribute is a DTD-style ID.""" return False def isIdNS(self, namespaceURI, localName): """Returns true iff the identified attribute is a DTD-style ID.""" return False def __getstate__(self): return self.tagName def __setstate__(self, state): self.tagName = state def _clear_id_cache(node): if node.nodeType == Node.DOCUMENT_NODE: node._id_cache.clear() node._id_search_stack = None elif _in_document(node): node.ownerDocument._id_cache.clear() node.ownerDocument._id_search_stack= None class Document(Node, DocumentLS): __slots__ = ('_elem_info', 'doctype', '_id_search_stack', 'childNodes', '_id_cache') _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE) implementation = DOMImplementation() nodeType = Node.DOCUMENT_NODE nodeName = "#document" nodeValue = None attributes = None parentNode = None previousSibling = nextSibling = None # Document attributes from Level 3 (WD 9 April 2002) actualEncoding = None encoding = None standalone = None version = None strictErrorChecking = False errorHandler = None documentURI = None _magic_id_count = 0 def __init__(self): self.doctype = None self.childNodes = NodeList() # mapping of (namespaceURI, localName) -> ElementInfo # and tagName -> ElementInfo self._elem_info = {} self._id_cache = {} self._id_search_stack = None def _get_elem_info(self, element): if element.namespaceURI: key = element.namespaceURI, element.localName else: key = element.tagName return self._elem_info.get(key) def _get_actualEncoding(self): return self.actualEncoding def _get_doctype(self): return self.doctype def _get_documentURI(self): return self.documentURI def _get_encoding(self): return self.encoding def _get_errorHandler(self): return self.errorHandler def _get_standalone(self): return self.standalone def _get_strictErrorChecking(self): return self.strictErrorChecking def _get_version(self): return self.version def appendChild(self, node): if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) if node.parentNode is not None: # This needs to be done before the next test since this # may *be* the document element, in which case it should # end up re-ordered to the end. node.parentNode.removeChild(node) if node.nodeType == Node.ELEMENT_NODE \ and self._get_documentElement(): raise xml.dom.HierarchyRequestErr( "two document elements disallowed") return Node.appendChild(self, node) def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() oldChild.nextSibling = oldChild.previousSibling = None oldChild.parentNode = None if self.documentElement is oldChild: self.documentElement = None return oldChild def _get_documentElement(self): for node in self.childNodes: if node.nodeType == Node.ELEMENT_NODE: return node def unlink(self): if self.doctype is not None: self.doctype.unlink() self.doctype = None Node.unlink(self) def cloneNode(self, deep): if not deep: return None clone = self.implementation.createDocument(None, None, None) clone.encoding = self.encoding clone.standalone = self.standalone clone.version = self.version for n in self.childNodes: childclone = _clone_node(n, deep, clone) assert childclone.ownerDocument.isSameNode(clone) clone.childNodes.append(childclone) if childclone.nodeType == Node.DOCUMENT_NODE: assert clone.documentElement is None elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE: assert clone.doctype is None clone.doctype = childclone childclone.parentNode = clone self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED, self, clone) return clone def createDocumentFragment(self): d = DocumentFragment() d.ownerDocument = self return d def createElement(self, tagName): e = Element(tagName) e.ownerDocument = self return e def createTextNode(self, data): if not isinstance(data, str): raise TypeError("node contents must be a string") t = Text() t.data = data t.ownerDocument = self return t def createCDATASection(self, data): if not isinstance(data, str): raise TypeError("node contents must be a string") c = CDATASection() c.data = data c.ownerDocument = self return c def createComment(self, data): c = Comment(data) c.ownerDocument = self return c def createProcessingInstruction(self, target, data): p = ProcessingInstruction(target, data) p.ownerDocument = self return p def createAttribute(self, qName): a = Attr(qName) a.ownerDocument = self a.value = "" return a def createElementNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) e = Element(qualifiedName, namespaceURI, prefix) e.ownerDocument = self return e def createAttributeNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) a = Attr(qualifiedName, namespaceURI, localName, prefix) a.ownerDocument = self a.value = "" return a # A couple of implementation-specific helpers to create node types # not supported by the W3C DOM specs: def _create_entity(self, name, publicId, systemId, notationName): e = Entity(name, publicId, systemId, notationName) e.ownerDocument = self return e def _create_notation(self, name, publicId, systemId): n = Notation(name, publicId, systemId) n.ownerDocument = self return n def getElementById(self, id): if id in self._id_cache: return self._id_cache[id] if not (self._elem_info or self._magic_id_count): return None stack = self._id_search_stack if stack is None: # we never searched before, or the cache has been cleared stack = [self.documentElement] self._id_search_stack = stack elif not stack: # Previous search was completed and cache is still valid; # no matching node. return None result = None while stack: node = stack.pop() # add child elements to stack for continued searching stack.extend([child for child in node.childNodes if child.nodeType in _nodeTypes_with_children]) # check this node info = self._get_elem_info(node) if info: # We have to process all ID attributes before # returning in order to get all the attributes set to # be IDs using Element.setIdAttribute*(). for attr in node.attributes.values(): if attr.namespaceURI: if info.isIdNS(attr.namespaceURI, attr.localName): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif info.isId(attr.name): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node elif node._magic_id_nodes == 1: break elif node._magic_id_nodes: for attr in node.attributes.values(): if attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node if result is not None: break return result def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def isSupported(self, feature, version): return self.implementation.hasFeature(feature, version) def importNode(self, node, deep): if node.nodeType == Node.DOCUMENT_NODE: raise xml.dom.NotSupportedErr("cannot import document nodes") elif node.nodeType == Node.DOCUMENT_TYPE_NODE: raise xml.dom.NotSupportedErr("cannot import document type nodes") return _clone_node(node, deep, self) def writexml(self, writer, indent="", addindent="", newl="", encoding=None): if encoding is None: writer.write('<?xml version="1.0" ?>'+newl) else: writer.write('<?xml version="1.0" encoding="%s"?>%s' % ( encoding, newl)) for node in self.childNodes: node.writexml(writer, indent, addindent, newl) # DOM Level 3 (WD 9 April 2002) def renameNode(self, n, namespaceURI, name): if n.ownerDocument is not self: raise xml.dom.WrongDocumentErr( "cannot rename nodes from other documents;\n" "expected %s,\nfound %s" % (self, n.ownerDocument)) if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): raise xml.dom.NotSupportedErr( "renameNode() only applies to element and attribute nodes") if namespaceURI != EMPTY_NAMESPACE: if ':' in name: prefix, localName = name.split(':', 1) if ( prefix == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE): raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix") else: if ( name == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE and n.nodeType == Node.ATTRIBUTE_NODE): raise xml.dom.NamespaceErr( "illegal use of the 'xmlns' attribute") prefix = None localName = name else: prefix = None localName = None if n.nodeType == Node.ATTRIBUTE_NODE: element = n.ownerElement if element is not None: is_id = n._is_id element.removeAttributeNode(n) else: element = None n.prefix = prefix n._localName = localName n.namespaceURI = namespaceURI n.nodeName = name if n.nodeType == Node.ELEMENT_NODE: n.tagName = name else: # attribute node n.name = name if element is not None: element.setAttributeNode(n) if is_id: element.setIdAttributeNode(n) # It's not clear from a semantic perspective whether we should # call the user data handlers for the NODE_RENAMED event since # we're re-using the existing node. The draft spec has been # interpreted as meaning "no, don't call the handler unless a # new node is created." return n defproperty(Document, "documentElement", doc="Top-level element of this document.") def _clone_node(node, deep, newOwnerDocument): """ Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode """ if node.ownerDocument.isSameNode(newOwnerDocument): operation = xml.dom.UserDataHandler.NODE_CLONED else: operation = xml.dom.UserDataHandler.NODE_IMPORTED if node.nodeType == Node.ELEMENT_NODE: clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName) for attr in node.attributes.values(): clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) a.specified = attr.specified if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: clone = newOwnerDocument.createDocumentFragment() if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.TEXT_NODE: clone = newOwnerDocument.createTextNode(node.data) elif node.nodeType == Node.CDATA_SECTION_NODE: clone = newOwnerDocument.createCDATASection(node.data) elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: clone = newOwnerDocument.createProcessingInstruction(node.target, node.data) elif node.nodeType == Node.COMMENT_NODE: clone = newOwnerDocument.createComment(node.data) elif node.nodeType == Node.ATTRIBUTE_NODE: clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName) clone.specified = True clone.value = node.value elif node.nodeType == Node.DOCUMENT_TYPE_NODE: assert node.ownerDocument is not newOwnerDocument operation = xml.dom.UserDataHandler.NODE_IMPORTED clone = newOwnerDocument.implementation.createDocumentType( node.name, node.publicId, node.systemId) clone.ownerDocument = newOwnerDocument if deep: clone.entities._seq = [] clone.notations._seq = [] for n in node.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) notation.ownerDocument = newOwnerDocument clone.notations._seq.append(notation) if hasattr(n, '_call_user_data_handler'): n._call_user_data_handler(operation, n, notation) for e in node.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version entity.ownerDocument = newOwnerDocument clone.entities._seq.append(entity) if hasattr(e, '_call_user_data_handler'): e._call_user_data_handler(operation, e, entity) else: # Note the cloning of Document and DocumentType nodes is # implementation specific. minidom handles those cases # directly in the cloneNode() methods. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) # Check for _call_user_data_handler() since this could conceivably # used with other DOM implementations (one of the FourThought # DOMs, perhaps?). if hasattr(node, '_call_user_data_handler'): node._call_user_data_handler(operation, node, clone) return clone def _nssplit(qualifiedName): fields = qualifiedName.split(':', 1) if len(fields) == 2: return fields else: return (None, fields[0]) def _do_pulldom_parse(func, args, kwargs): events = func(*args, **kwargs) toktype, rootNode = events.getEvent() events.expandNode(rootNode) events.clear() return rootNode def parse(file, parser=None, bufsize=None): """Parse a file into a DOM by filename or file object.""" if parser is None and not bufsize: from xml.dom import expatbuilder return expatbuilder.parse(file) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parse, (file,), {'parser': parser, 'bufsize': bufsize}) def parseString(string, parser=None): """Parse a file into a DOM from a string.""" if parser is None: from xml.dom import expatbuilder return expatbuilder.parseString(string) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parseString, (string,), {'parser': parser}) def getDOMImplementation(features=None): if features: if isinstance(features, str): features = domreg._parse_feature_string(features) for f, v in features: if not Document.implementation.hasFeature(f, v): return None return Document.implementation
66,819
1,982
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/collections/abc.py
from _collections_abc import * from _collections_abc import __all__ if __name__ == 'PYOBJ.COM': AsyncGenerator = 0 AsyncIterable = 0 AsyncIterator = 0 Awaitable = 0 ByteString = 0 Callable = 0 Collection = 0 Container = 0 Coroutine = 0 Generator = 0 Hashable = 0 ItemsView = 0 Iterable = 0 Iterator = 0 KeysView = 0 Mapping = 0 MappingView = 0 MutableMapping = 0 MutableSequence = 0 MutableSet = 0 Reversible = 0 Sequence = 0 Set = 0 Sized = 0 ValuesView = 0
560
30
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/collections/__init__.py
'''This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, and tuple. * namedtuple factory function for creating tuple subclasses with named fields * deque list-like container with fast appends and pops on either end * ChainMap dict-like class for creating a single view of multiple mappings * Counter dict subclass for counting hashable objects * OrderedDict dict subclass that remembers the order entries were added * defaultdict dict subclass that calls a factory function to supply missing values * UserDict wrapper around dictionary objects for easier dict subclassing * UserList wrapper around list objects for easier list subclassing * UserString wrapper around string objects for easier string subclassing ''' __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserString', 'Counter', 'OrderedDict', 'ChainMap'] # For backwards compatibility, continue to make the collections ABCs # available through the collections module. But don't mandate it, in # cases where we're compiling with PYOBJ.COM. try: from _collections_abc import * import _collections_abc __all__ += _collections_abc.__all__ except ImportError: pass from operator import itemgetter as _itemgetter, eq as _eq from keyword import iskeyword as _iskeyword import sys as _sys import heapq as _heapq from _weakref import proxy as _proxy from itertools import repeat as _repeat, chain as _chain, starmap as _starmap from reprlib import recursive_repr as _recursive_repr try: from _collections import deque except ImportError: pass else: MutableSequence.register(deque) try: from _collections import defaultdict except ImportError: pass ################################################################################ ### OrderedDict ################################################################################ class _OrderedDictKeysView(KeysView): def __reversed__(self): yield from reversed(self._mapping) class _OrderedDictItemsView(ItemsView): def __reversed__(self): for key in reversed(self._mapping): yield (key, self._mapping[key]) class _OrderedDictValuesView(ValuesView): def __reversed__(self): for key in reversed(self._mapping): yield self._mapping[key] class _Link(object): __slots__ = 'prev', 'next', 'key', '__weakref__' class OrderedDict(dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. # Big-O running times for all methods are the same as regular dictionaries. # The internal self.__map dict maps keys to links in a doubly linked list. # The circular doubly linked list starts and ends with a sentinel element. # The sentinel element never gets deleted (this simplifies the algorithm). # The sentinel is in self.__hardroot with a weakref proxy in self.__root. # The prev links are weakref proxies (to prevent circular references). # Individual links are kept alive by the hard reference in self.__map. # Those hard references disappear when a key is deleted from an OrderedDict. def __init__(*args, **kwds): '''Initialize an ordered dictionary. The signature is the same as regular dictionaries. Keyword argument order is preserved. ''' if not args: raise TypeError("descriptor '__init__' of 'OrderedDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__hardroot = _Link() self.__root = root = _proxy(self.__hardroot) root.prev = root.next = root self.__map = {} self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link at the end of the linked list, # and the inherited dictionary is updated with the new key/value pair. if key not in self: self.__map[key] = link = Link() root = self.__root last = root.prev link.prev, link.next, link.key = last, root, key last.next = link root.prev = proxy(link) dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which gets # removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link = self.__map.pop(key) link_prev = link.prev link_next = link.next link_prev.next = link_next link_next.prev = link_prev link.prev = None link.next = None def __iter__(self): 'od.__iter__() <==> iter(od)' # Traverse the linked list in order. root = self.__root curr = root.next while curr is not root: yield curr.key curr = curr.next def __reversed__(self): 'od.__reversed__() <==> reversed(od)' # Traverse the linked list in reverse order. root = self.__root curr = root.prev while curr is not root: yield curr.key curr = curr.prev def clear(self): 'od.clear() -> None. Remove all items from od.' root = self.__root root.prev = root.next = root self.__map.clear() dict.clear(self) def popitem(self, last=True): '''Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root.prev link_prev = link.prev link_prev.next = root root.prev = link_prev else: link = root.next link_next = link.next root.next = link_next link_next.prev = root key = link.key del self.__map[key] value = dict.pop(self, key) return key, value def move_to_end(self, key, last=True): '''Move an existing element to the end (or beginning if last==False). Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(key). ''' link = self.__map[key] link_prev = link.prev link_next = link.next soft_link = link_next.prev link_prev.next = link_next link_next.prev = link_prev root = self.__root if last: last = root.prev link.prev = last link.next = root root.prev = soft_link last.next = link else: first = root.next link.prev = root link.next = first first.prev = soft_link root.next = link def __sizeof__(self): sizeof = _sys.getsizeof n = len(self) + 1 # number of links including root size = sizeof(self.__dict__) # instance dictionary size += sizeof(self.__map) * 2 # internal dict and inherited dict size += sizeof(self.__hardroot) * n # link objects size += sizeof(self.__root) * n # proxy objects return size update = __update = MutableMapping.update def keys(self): "D.keys() -> a set-like object providing a view on D's keys" return _OrderedDictKeysView(self) def items(self): "D.items() -> a set-like object providing a view on D's items" return _OrderedDictItemsView(self) def values(self): "D.values() -> an object providing a view on D's values" return _OrderedDictValuesView(self) __ne__ = MutableMapping.__ne__ __marker = object() def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default def setdefault(self, key, default=None): 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' if key in self: return self[key] self[key] = default return default @_recursive_repr() def __repr__(self): 'od.__repr__() <==> repr(od)' if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self.items())) def __reduce__(self): 'Return state information for pickling' inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) return self.__class__, (), inst_dict or None, None, iter(self.items()) def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. If not specified, the value defaults to None. ''' self = cls() for key in iterable: self[key] = value return self def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return dict.__eq__(self, other) and all(map(_eq, self, other)) return dict.__eq__(self, other) try: from _collections import OrderedDict except ImportError: # Leave the pure Python version in place. pass ################################################################################ ### namedtuple ################################################################################ _class_template = """\ from builtins import property as _property, tuple as _tuple from operator import itemgetter as _itemgetter from collections import OrderedDict class {typename}(tuple): '{typename}({arg_list})' __slots__ = () _fields = {field_names!r} def __new__(_cls, {arg_list}): 'Create new instance of {typename}({arg_list})' return _tuple.__new__(_cls, ({arg_list})) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new {typename} object from a sequence or iterable' result = new(cls, iterable) if len(result) != {num_fields:d}: raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result)) return result def _replace(_self, **kwds): 'Return a new {typename} object replacing specified fields with new values' result = _self._make(map(kwds.pop, {field_names!r}, _self)) if kwds: raise ValueError('Got unexpected field names: %r' % list(kwds)) return result def __repr__(self): 'Return a nicely formatted representation string' return self.__class__.__name__ + '({repr_fmt})' % self def _asdict(self): 'Return a new OrderedDict which maps field names to their values.' return OrderedDict(zip(self._fields, self)) def __getnewargs__(self): 'Return self as a plain tuple. Used by copy and pickle.' return tuple(self) {field_defs} """ _repr_template = '{name}=%r' _field_template = '''\ {name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}') ''' def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """ # Validate the field names. At the user's option, either generate an error # message or automatically replace the field name with a valid name. if isinstance(field_names, str): field_names = field_names.replace(',', ' ').split() field_names = list(map(str, field_names)) typename = str(typename) if rename: seen = set() for index, name in enumerate(field_names): if (not name.isidentifier() or _iskeyword(name) or name.startswith('_') or name in seen): field_names[index] = '_%d' % index seen.add(name) for name in [typename] + field_names: if type(name) is not str: raise TypeError('Type names and field names must be strings') if not name.isidentifier(): raise ValueError('Type names and field names must be valid ' 'identifiers: %r' % name) if _iskeyword(name): raise ValueError('Type names and field names cannot be a ' 'keyword: %r' % name) seen = set() for name in field_names: if name.startswith('_') and not rename: raise ValueError('Field names cannot start with an underscore: ' '%r' % name) if name in seen: raise ValueError('Encountered duplicate field name: %r' % name) seen.add(name) # Fill-in the class template class_definition = _class_template.format( typename = typename, field_names = tuple(field_names), num_fields = len(field_names), arg_list = repr(tuple(field_names)).replace("'", "")[1:-1], repr_fmt = ', '.join(_repr_template.format(name=name) for name in field_names), field_defs = '\n'.join(_field_template.format(index=index, name=name) for index, name in enumerate(field_names)) ) # Execute the template string in a temporary namespace and support # tracing utilities by setting a value for frame.f_globals['__name__'] namespace = dict(__name__='namedtuple_%s' % typename) exec(class_definition, namespace) result = namespace[typename] result._source = class_definition if verbose: print(result._source) # For pickling to work, the __module__ variable needs to be set to the frame # where the named tuple is created. Bypass this step in environments where # sys._getframe is not defined (Jython for example) or sys._getframe is not # defined for arguments greater than 0 (IronPython), or where the user has # specified a particular module. if module is None: try: module = _sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass if module is not None: result.__module__ = module return result ######################################################################## ### Counter ######################################################################## def _count_elements(mapping, iterable): 'Tally elements from the iterable.' mapping_get = mapping.get for elem in iterable: mapping[elem] = mapping_get(elem, 0) + 1 try: # Load C helper function if available from _collections import _count_elements except ImportError: pass class Counter(dict): '''Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # three most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15 >>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's count >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0 >>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9 >>> c.clear() # empty the counter >>> c Counter() Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared: >>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)] ''' # References: # http://en.wikipedia.org/wiki/Multiset # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm # http://code.activestate.com/recipes/259174/ # Knuth, TAOCP Vol. II section 4.6.3 def __init__(*args, **kwds): '''Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args ''' if not args: raise TypeError("descriptor '__init__' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) super(Counter, self).__init__() self.update(*args, **kwds) def __missing__(self, key): 'The count of elements not in the Counter is zero.' # Needed so that self[missing_item] does not raise KeyError return 0 def most_common(self, n=None): '''List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] ''' # Emulate Bag.sortedByCount from Smalltalk if n is None: return sorted(self.items(), key=_itemgetter(1), reverse=True) return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) def elements(self): '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it. ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. return _chain.from_iterable(_starmap(_repeat, self.items())) # Override dict methods where necessary @classmethod def fromkeys(cls, iterable, v=None): # There is no equivalent method for counters because setting v=1 # means that no element can have a count greater than one. raise NotImplementedError( 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') def update(*args, **kwds): '''Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 ''' # The regular dict.update() operation makes no sense here because the # replace behavior results in the some of original untouched counts # being mixed-in with all of the other counts for a mismash that # doesn't have a straight-forward interpretation in most counting # contexts. Instead, we implement straight-addition. Both the inputs # and outputs are allowed to contain zero and negative counts. if not args: raise TypeError("descriptor 'update' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) iterable = args[0] if args else None if iterable is not None: if isinstance(iterable, Mapping): if self: self_get = self.get for elem, count in iterable.items(): self[elem] = count + self_get(elem, 0) else: super(Counter, self).update(iterable) # fast path when counter is empty else: _count_elements(self, iterable) if kwds: self.update(kwds) def subtract(*args, **kwds): '''Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1 ''' if not args: raise TypeError("descriptor 'subtract' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) iterable = args[0] if args else None if iterable is not None: self_get = self.get if isinstance(iterable, Mapping): for elem, count in iterable.items(): self[elem] = self_get(elem, 0) - count else: for elem in iterable: self[elem] = self_get(elem, 0) - 1 if kwds: self.subtract(kwds) def copy(self): 'Return a shallow copy.' return self.__class__(self) def __reduce__(self): return self.__class__, (dict(self),) def __delitem__(self, elem): 'Like dict.__delitem__() but does not raise KeyError for missing values.' if elem in self: super().__delitem__(elem) def __repr__(self): if not self: return '%s()' % self.__class__.__name__ try: items = ', '.join(map('%r: %r'.__mod__, self.most_common())) return '%s({%s})' % (self.__class__.__name__, items) except TypeError: # handle case where values are not orderable return '{0}({1!r})'.format(self.__class__.__name__, dict(self)) # Multiset-style mathematical operations discussed in: # Knuth TAOCP Volume II section 4.6.3 exercise 19 # and at http://en.wikipedia.org/wiki/Multiset # # Outputs guaranteed to only include positive counts. # # To strip negative and zero counts, add-in an empty counter: # c += Counter() def __add__(self, other): '''Add counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): newcount = count + other[elem] if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0: result[elem] = count return result def __sub__(self, other): ''' Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): newcount = count - other[elem] if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count < 0: result[elem] = 0 - count return result def __or__(self, other): '''Union is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc') Counter({'b': 3, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): other_count = other[elem] newcount = other_count if count < other_count else count if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0: result[elem] = count return result def __and__(self, other): ''' Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): other_count = other[elem] newcount = count if count < other_count else other_count if newcount > 0: result[elem] = newcount return result def __pos__(self): 'Adds an empty counter, effectively stripping negative and zero counts' result = Counter() for elem, count in self.items(): if count > 0: result[elem] = count return result def __neg__(self): '''Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts. ''' result = Counter() for elem, count in self.items(): if count < 0: result[elem] = 0 - count return result def _keep_positive(self): '''Internal method to strip elements with a negative or zero count''' nonpositive = [elem for elem, count in self.items() if not count > 0] for elem in nonpositive: del self[elem] return self def __iadd__(self, other): '''Inplace add from another counter, keeping only positive counts. >>> c = Counter('abbb') >>> c += Counter('bcc') >>> c Counter({'b': 4, 'c': 2, 'a': 1}) ''' for elem, count in other.items(): self[elem] += count return self._keep_positive() def __isub__(self, other): '''Inplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') >>> c Counter({'b': 2, 'a': 1}) ''' for elem, count in other.items(): self[elem] -= count return self._keep_positive() def __ior__(self, other): '''Inplace union is the maximum of value from either counter. >>> c = Counter('abbb') >>> c |= Counter('bcc') >>> c Counter({'b': 3, 'c': 2, 'a': 1}) ''' for elem, other_count in other.items(): count = self[elem] if other_count > count: self[elem] = other_count return self._keep_positive() def __iand__(self, other): '''Inplace intersection is the minimum of corresponding counts. >>> c = Counter('abbb') >>> c &= Counter('bcc') >>> c Counter({'b': 1}) ''' for elem, count in self.items(): other_count = other[elem] if other_count < count: self[elem] = other_count return self._keep_positive() ######################################################################## ### ChainMap ######################################################################## class ChainMap(MutableMapping): ''' A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can be accessed or updated using the *maps* attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping. ''' def __init__(self, *maps): '''Initialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. ''' self.maps = list(maps) or [{}] # always at least one map def __missing__(self, key): raise KeyError(key) def __getitem__(self, key): for mapping in self.maps: try: return mapping[key] # can't use 'key in mapping' with defaultdict except KeyError: pass return self.__missing__(key) # support subclasses that define __missing__ def get(self, key, default=None): return self[key] if key in self else default def __len__(self): return len(set().union(*self.maps)) # reuses stored hash values if possible def __iter__(self): return iter(set().union(*self.maps)) def __contains__(self, key): return any(key in m for m in self.maps) def __bool__(self): return any(self.maps) @_recursive_repr() def __repr__(self): return '{0.__class__.__name__}({1})'.format( self, ', '.join(map(repr, self.maps))) @classmethod def fromkeys(cls, iterable, *args): 'Create a ChainMap with a single dict created from the iterable.' return cls(dict.fromkeys(iterable, *args)) def copy(self): 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' return self.__class__(self.maps[0].copy(), *self.maps[1:]) __copy__ = copy def new_child(self, m=None): # like Django's Context.push() '''New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used. ''' if m is None: m = {} return self.__class__(m, *self.maps) @property def parents(self): # like Django's Context.pop() 'New ChainMap from maps[1:].' return self.__class__(*self.maps[1:]) def __setitem__(self, key, value): self.maps[0][key] = value def __delitem__(self, key): try: del self.maps[0][key] except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except KeyError: raise KeyError('No keys found in the first mapping.') def pop(self, key, *args): 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' try: return self.maps[0].pop(key, *args) except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def clear(self): 'Clear maps[0], leaving maps[1:] intact.' self.maps[0].clear() ################################################################################ ### UserDict ################################################################################ class UserDict(MutableMapping): # Start by filling-out the abstract methods def __init__(*args, **kwargs): if not args: raise TypeError("descriptor '__init__' of 'UserDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) if args: dict = args[0] elif 'dict' in kwargs: dict = kwargs.pop('dict') import warnings warnings.warn("Passing 'dict' as keyword argument is deprecated", DeprecationWarning, stacklevel=2) else: dict = None self.data = {} if dict is not None: self.update(dict) if len(kwargs): self.update(kwargs) def __len__(self): return len(self.data) def __getitem__(self, key): if key in self.data: return self.data[key] if hasattr(self.__class__, "__missing__"): return self.__class__.__missing__(self, key) raise KeyError(key) def __setitem__(self, key, item): self.data[key] = item def __delitem__(self, key): del self.data[key] def __iter__(self): return iter(self.data) # Modify __contains__ to work correctly when __missing__ is present def __contains__(self, key): return key in self.data # Now, add the methods in dicts but not in MutableMapping def __repr__(self): return repr(self.data) def copy(self): if self.__class__ is UserDict: return UserDict(self.data.copy()) import copy data = self.data try: self.data = {} c = copy.copy(self) finally: self.data = data c.update(self) return c @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d ################################################################################ ### UserList ################################################################################ class UserList(MutableSequence): """A more or less complete user-defined wrapper around list objects.""" def __init__(self, initlist=None): self.data = [] if initlist is not None: # XXX should this accept an arbitrary sequence? if type(initlist) == type(self.data): self.data[:] = initlist elif isinstance(initlist, UserList): self.data[:] = initlist.data[:] else: self.data = list(initlist) def __repr__(self): return repr(self.data) def __lt__(self, other): return self.data < self.__cast(other) def __le__(self, other): return self.data <= self.__cast(other) def __eq__(self, other): return self.data == self.__cast(other) def __gt__(self, other): return self.data > self.__cast(other) def __ge__(self, other): return self.data >= self.__cast(other) def __cast(self, other): return other.data if isinstance(other, UserList) else other def __contains__(self, item): return item in self.data def __len__(self): return len(self.data) def __getitem__(self, i): return self.data[i] def __setitem__(self, i, item): self.data[i] = item def __delitem__(self, i): del self.data[i] def __add__(self, other): if isinstance(other, UserList): return self.__class__(self.data + other.data) elif isinstance(other, type(self.data)): return self.__class__(self.data + other) return self.__class__(self.data + list(other)) def __radd__(self, other): if isinstance(other, UserList): return self.__class__(other.data + self.data) elif isinstance(other, type(self.data)): return self.__class__(other + self.data) return self.__class__(list(other) + self.data) def __iadd__(self, other): if isinstance(other, UserList): self.data += other.data elif isinstance(other, type(self.data)): self.data += other else: self.data += list(other) return self def __mul__(self, n): return self.__class__(self.data*n) __rmul__ = __mul__ def __imul__(self, n): self.data *= n return self def append(self, item): self.data.append(item) def insert(self, i, item): self.data.insert(i, item) def pop(self, i=-1): return self.data.pop(i) def remove(self, item): self.data.remove(item) def clear(self): self.data.clear() def copy(self): return self.__class__(self) def count(self, item): return self.data.count(item) def index(self, item, *args): return self.data.index(item, *args) def reverse(self): self.data.reverse() def sort(self, *args, **kwds): self.data.sort(*args, **kwds) def extend(self, other): if isinstance(other, UserList): self.data.extend(other.data) else: self.data.extend(other) ################################################################################ ### UserString ################################################################################ class UserString(Sequence): def __init__(self, seq): if isinstance(seq, str): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] else: self.data = str(seq) def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) def __int__(self): return int(self.data) def __float__(self): return float(self.data) def __complex__(self): return complex(self.data) def __hash__(self): return hash(self.data) def __getnewargs__(self): return (self.data[:],) def __eq__(self, string): if isinstance(string, UserString): return self.data == string.data return self.data == string def __lt__(self, string): if isinstance(string, UserString): return self.data < string.data return self.data < string def __le__(self, string): if isinstance(string, UserString): return self.data <= string.data return self.data <= string def __gt__(self, string): if isinstance(string, UserString): return self.data > string.data return self.data > string def __ge__(self, string): if isinstance(string, UserString): return self.data >= string.data return self.data >= string def __contains__(self, char): if isinstance(char, UserString): char = char.data return char in self.data def __len__(self): return len(self.data) def __getitem__(self, index): return self.__class__(self.data[index]) def __add__(self, other): if isinstance(other, UserString): return self.__class__(self.data + other.data) elif isinstance(other, str): return self.__class__(self.data + other) return self.__class__(self.data + str(other)) def __radd__(self, other): if isinstance(other, str): return self.__class__(other + self.data) return self.__class__(str(other) + self.data) def __mul__(self, n): return self.__class__(self.data*n) __rmul__ = __mul__ def __mod__(self, args): return self.__class__(self.data % args) def __rmod__(self, format): return self.__class__(format % args) # the following methods are defined in alphabetical order: def capitalize(self): return self.__class__(self.data.capitalize()) def casefold(self): return self.__class__(self.data.casefold()) def center(self, width, *args): return self.__class__(self.data.center(width, *args)) def count(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.count(sub, start, end) def encode(self, encoding=None, errors=None): # XXX improve this? if encoding: if errors: return self.__class__(self.data.encode(encoding, errors)) return self.__class__(self.data.encode(encoding)) return self.__class__(self.data.encode()) def endswith(self, suffix, start=0, end=_sys.maxsize): return self.data.endswith(suffix, start, end) def expandtabs(self, tabsize=8): return self.__class__(self.data.expandtabs(tabsize)) def find(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.find(sub, start, end) def format(self, *args, **kwds): return self.data.format(*args, **kwds) def format_map(self, mapping): return self.data.format_map(mapping) def index(self, sub, start=0, end=_sys.maxsize): return self.data.index(sub, start, end) def isalpha(self): return self.data.isalpha() def isalnum(self): return self.data.isalnum() def isdecimal(self): return self.data.isdecimal() def isdigit(self): return self.data.isdigit() def isidentifier(self): return self.data.isidentifier() def islower(self): return self.data.islower() def isnumeric(self): return self.data.isnumeric() def isprintable(self): return self.data.isprintable() def isspace(self): return self.data.isspace() def istitle(self): return self.data.istitle() def isupper(self): return self.data.isupper() def join(self, seq): return self.data.join(seq) def ljust(self, width, *args): return self.__class__(self.data.ljust(width, *args)) def lower(self): return self.__class__(self.data.lower()) def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) maketrans = str.maketrans def partition(self, sep): return self.data.partition(sep) def replace(self, old, new, maxsplit=-1): if isinstance(old, UserString): old = old.data if isinstance(new, UserString): new = new.data return self.__class__(self.data.replace(old, new, maxsplit)) def rfind(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.rfind(sub, start, end) def rindex(self, sub, start=0, end=_sys.maxsize): return self.data.rindex(sub, start, end) def rjust(self, width, *args): return self.__class__(self.data.rjust(width, *args)) def rpartition(self, sep): return self.data.rpartition(sep) def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars)) def split(self, sep=None, maxsplit=-1): return self.data.split(sep, maxsplit) def rsplit(self, sep=None, maxsplit=-1): return self.data.rsplit(sep, maxsplit) def splitlines(self, keepends=False): return self.data.splitlines(keepends) def startswith(self, prefix, start=0, end=_sys.maxsize): return self.data.startswith(prefix, start, end) def strip(self, chars=None): return self.__class__(self.data.strip(chars)) def swapcase(self): return self.__class__(self.data.swapcase()) def title(self): return self.__class__(self.data.title()) def translate(self, *args): return self.__class__(self.data.translate(*args)) def upper(self): return self.__class__(self.data.upper()) def zfill(self, width): return self.__class__(self.data.zfill(width)) if __name__ == 'PYOBJ.COM': import _collections
45,980
1,251
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/concurrent/__init__.py
# This directory is a Python package.
38
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/concurrent/futures/_base.py
# Copyright 2009 Brian Quinlan. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. __author__ = 'Brian Quinlan ([email protected])' import collections import logging import threading import time FIRST_COMPLETED = 'FIRST_COMPLETED' FIRST_EXCEPTION = 'FIRST_EXCEPTION' ALL_COMPLETED = 'ALL_COMPLETED' _AS_COMPLETED = '_AS_COMPLETED' # Possible future states (for internal use by the futures package). PENDING = 'PENDING' RUNNING = 'RUNNING' # The future was cancelled by the user... CANCELLED = 'CANCELLED' # ...and _Waiter.add_cancelled() was called by a worker. CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED' FINISHED = 'FINISHED' _FUTURE_STATES = [ PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED ] _STATE_TO_DESCRIPTION_MAP = { PENDING: "pending", RUNNING: "running", CANCELLED: "cancelled", CANCELLED_AND_NOTIFIED: "cancelled", FINISHED: "finished" } # Logger for internal use by the futures package. LOGGER = logging.getLogger("concurrent.futures") class Error(Exception): """Base class for all future-related exceptions.""" pass class CancelledError(Error): """The Future was cancelled.""" pass class TimeoutError(Error): """The operation exceeded the given deadline.""" pass class _Waiter(object): """Provides the event that wait() and as_completed() block on.""" def __init__(self): self.event = threading.Event() self.finished_futures = [] def add_result(self, future): self.finished_futures.append(future) def add_exception(self, future): self.finished_futures.append(future) def add_cancelled(self, future): self.finished_futures.append(future) class _AsCompletedWaiter(_Waiter): """Used by as_completed().""" def __init__(self): super(_AsCompletedWaiter, self).__init__() self.lock = threading.Lock() def add_result(self, future): with self.lock: super(_AsCompletedWaiter, self).add_result(future) self.event.set() def add_exception(self, future): with self.lock: super(_AsCompletedWaiter, self).add_exception(future) self.event.set() def add_cancelled(self, future): with self.lock: super(_AsCompletedWaiter, self).add_cancelled(future) self.event.set() class _FirstCompletedWaiter(_Waiter): """Used by wait(return_when=FIRST_COMPLETED).""" def add_result(self, future): super().add_result(future) self.event.set() def add_exception(self, future): super().add_exception(future) self.event.set() def add_cancelled(self, future): super().add_cancelled(future) self.event.set() class _AllCompletedWaiter(_Waiter): """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).""" def __init__(self, num_pending_calls, stop_on_exception): self.num_pending_calls = num_pending_calls self.stop_on_exception = stop_on_exception self.lock = threading.Lock() super().__init__() def _decrement_pending_calls(self): with self.lock: self.num_pending_calls -= 1 if not self.num_pending_calls: self.event.set() def add_result(self, future): super().add_result(future) self._decrement_pending_calls() def add_exception(self, future): super().add_exception(future) if self.stop_on_exception: self.event.set() else: self._decrement_pending_calls() def add_cancelled(self, future): super().add_cancelled(future) self._decrement_pending_calls() class _AcquireFutures(object): """A context manager that does an ordered acquire of Future conditions.""" def __init__(self, futures): self.futures = sorted(futures, key=id) def __enter__(self): for future in self.futures: future._condition.acquire() def __exit__(self, *args): for future in self.futures: future._condition.release() def _create_and_install_waiters(fs, return_when): if return_when == _AS_COMPLETED: waiter = _AsCompletedWaiter() elif return_when == FIRST_COMPLETED: waiter = _FirstCompletedWaiter() else: pending_count = sum( f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs) if return_when == FIRST_EXCEPTION: waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True) elif return_when == ALL_COMPLETED: waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False) else: raise ValueError("Invalid return condition: %r" % return_when) for f in fs: f._waiters.append(waiter) return waiter def _yield_finished_futures(fs, waiter, ref_collect): """ Iterate on the list *fs*, yielding finished futures one by one in reverse order. Before yielding a future, *waiter* is removed from its waiters and the future is removed from each set in the collection of sets *ref_collect*. The aim of this function is to avoid keeping stale references after the future is yielded and before the iterator resumes. """ while fs: f = fs[-1] for futures_set in ref_collect: futures_set.remove(f) with f._condition: f._waiters.remove(waiter) del f # Careful not to keep a reference to the popped value yield fs.pop() def as_completed(fs, timeout=None): """An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to iterate over. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator that yields the given Futures as they complete (finished or cancelled). If any given Futures are duplicated, they will be returned once. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. """ if timeout is not None: end_time = timeout + time.monotonic() fs = set(fs) total_futures = len(fs) with _AcquireFutures(fs): finished = set( f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) pending = fs - finished waiter = _create_and_install_waiters(fs, _AS_COMPLETED) finished = list(finished) try: yield from _yield_finished_futures(finished, waiter, ref_collect=(fs,)) while pending: if timeout is None: wait_timeout = None else: wait_timeout = end_time - time.monotonic() if wait_timeout < 0: raise TimeoutError( '%d (of %d) futures unfinished' % ( len(pending), total_futures)) waiter.event.wait(wait_timeout) with waiter.lock: finished = waiter.finished_futures waiter.finished_futures = [] waiter.event.clear() # reverse to keep finishing order finished.reverse() yield from _yield_finished_futures(finished, waiter, ref_collect=(fs, pending)) finally: # Remove waiter from unfinished futures for f in fs: with f._condition: f._waiters.remove(waiter) DoneAndNotDoneFutures = collections.namedtuple( 'DoneAndNotDoneFutures', 'done not_done') def wait(fs, timeout=None, return_when=ALL_COMPLETED): """Wait for the futures in the given sequence to complete. Args: fs: The sequence of Futures (possibly created by different Executors) to wait upon. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. return_when: Indicates when this function should return. The options are: FIRST_COMPLETED - Return when any future finishes or is cancelled. FIRST_EXCEPTION - Return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED. ALL_COMPLETED - Return when all futures finish or are cancelled. Returns: A named 2-tuple of sets. The first set, named 'done', contains the futures that completed (is finished or cancelled) before the wait completed. The second set, named 'not_done', contains uncompleted futures. """ with _AcquireFutures(fs): done = set(f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) not_done = set(fs) - done if (return_when == FIRST_COMPLETED) and done: return DoneAndNotDoneFutures(done, not_done) elif (return_when == FIRST_EXCEPTION) and done: if any(f for f in done if not f.cancelled() and f.exception() is not None): return DoneAndNotDoneFutures(done, not_done) if len(done) == len(fs): return DoneAndNotDoneFutures(done, not_done) waiter = _create_and_install_waiters(fs, return_when) waiter.event.wait(timeout) for f in fs: with f._condition: f._waiters.remove(waiter) done.update(waiter.finished_futures) return DoneAndNotDoneFutures(done, set(fs) - done) class Future(object): """Represents the result of an asynchronous computation.""" def __init__(self): """Initializes the future. Should not be called by clients.""" self._condition = threading.Condition() self._state = PENDING self._result = None self._exception = None self._waiters = [] self._done_callbacks = [] def _invoke_callbacks(self): for callback in self._done_callbacks: try: callback(self) except Exception: LOGGER.exception('exception calling callback for %r', self) def __repr__(self): with self._condition: if self._state == FINISHED: if self._exception: return '<%s at %#x state=%s raised %s>' % ( self.__class__.__name__, id(self), _STATE_TO_DESCRIPTION_MAP[self._state], self._exception.__class__.__name__) else: return '<%s at %#x state=%s returned %s>' % ( self.__class__.__name__, id(self), _STATE_TO_DESCRIPTION_MAP[self._state], self._result.__class__.__name__) return '<%s at %#x state=%s>' % ( self.__class__.__name__, id(self), _STATE_TO_DESCRIPTION_MAP[self._state]) def cancel(self): """Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed. """ with self._condition: if self._state in [RUNNING, FINISHED]: return False if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: return True self._state = CANCELLED self._condition.notify_all() self._invoke_callbacks() return True def cancelled(self): """Return True if the future was cancelled.""" with self._condition: return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED] def running(self): """Return True if the future is currently executing.""" with self._condition: return self._state == RUNNING def done(self): """Return True of the future was cancelled or finished executing.""" with self._condition: return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED] def __get_result(self): if self._exception: raise self._exception else: return self._result def add_done_callback(self, fn): """Attaches a callable that will be called when the future finishes. Args: fn: A callable that will be called with this future as its only argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or been cancelled then the callable will be called immediately. These callables are called in the order that they were added. """ with self._condition: if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]: self._done_callbacks.append(fn) return fn(self) def result(self, timeout=None): """Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. Raises: CancelledError: If the future was cancelled. TimeoutError: If the future didn't finish executing before the given timeout. Exception: If the call raised then that exception will be raised. """ with self._condition: if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self.__get_result() self._condition.wait(timeout) if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self.__get_result() else: raise TimeoutError() def exception(self, timeout=None): """Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn't done. If None, then there is no limit on the wait time. Returns: The exception raised by the call that the future represents or None if the call completed without raising. Raises: CancelledError: If the future was cancelled. TimeoutError: If the future didn't finish executing before the given timeout. """ with self._condition: if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self._exception self._condition.wait(timeout) if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: raise CancelledError() elif self._state == FINISHED: return self._exception else: raise TimeoutError() # The following methods should only be used by Executors and in tests. def set_running_or_notify_cancel(self): """Mark the future as running or process any cancel notifications. Should only be used by Executor implementations and unit tests. If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is returned. If the future was not cancelled then it is put in the running state (future calls to running() will return True) and True is returned. This method should be called by Executor implementations before executing the work associated with this future. If this method returns False then the work should not be executed. Returns: False if the Future was cancelled, True otherwise. Raises: RuntimeError: if this method was already called or if set_result() or set_exception() was called. """ with self._condition: if self._state == CANCELLED: self._state = CANCELLED_AND_NOTIFIED for waiter in self._waiters: waiter.add_cancelled(self) # self._condition.notify_all() is not necessary because # self.cancel() triggers a notification. return False elif self._state == PENDING: self._state = RUNNING return True else: LOGGER.critical('Future %s in unexpected state: %s', id(self), self._state) raise RuntimeError('Future in unexpected state') def set_result(self, result): """Sets the return value of work associated with the future. Should only be used by Executor implementations and unit tests. """ with self._condition: self._result = result self._state = FINISHED for waiter in self._waiters: waiter.add_result(self) self._condition.notify_all() self._invoke_callbacks() def set_exception(self, exception): """Sets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests. """ with self._condition: self._exception = exception self._state = FINISHED for waiter in self._waiters: waiter.add_exception(self) self._condition.notify_all() self._invoke_callbacks() class Executor(object): """This is an abstract base class for concrete asynchronous executors.""" def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call. """ raise NotImplementedError() def map(self, fn, *iterables, timeout=None, chunksize=1): """Returns an iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. chunksize: The size of the chunks the iterable will be broken into before being passed to a child process. This argument is only used by ProcessPoolExecutor; it is ignored by ThreadPoolExecutor. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. Exception: If fn(*args) raises for any values. """ if timeout is not None: end_time = timeout + time.monotonic() fs = [self.submit(fn, *args) for args in zip(*iterables)] # Yield must be hidden in closure so that the futures are submitted # before the first iterator value is required. def result_iterator(): try: # reverse to keep finishing order fs.reverse() while fs: # Careful not to keep a reference to the popped future if timeout is None: yield fs.pop().result() else: yield fs.pop().result(end_time - time.monotonic()) finally: for future in fs: future.cancel() return result_iterator() def shutdown(self, wait=True): """Clean-up the resources associated with the Executor. It is safe to call this method several times. Otherwise, no other methods can be called after this one. Args: wait: If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed. """ pass def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.shutdown(wait=True) return False
21,235
613
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/concurrent/futures/thread.py
# Copyright 2009 Brian Quinlan. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Implements ThreadPoolExecutor.""" __author__ = 'Brian Quinlan ([email protected])' import atexit from concurrent.futures import _base import itertools import queue import threading import weakref import os # Workers are created as daemon threads. This is done to allow the interpreter # to exit when there are still idle threads in a ThreadPoolExecutor's thread # pool (i.e. shutdown() was not called). However, allowing workers to die with # the interpreter has two undesirable properties: # - The workers would still be running during interpreter shutdown, # meaning that they would fail in unpredictable ways. # - The workers could be killed while evaluating a work item, which could # be bad if the callable being evaluated has external side-effects e.g. # writing to a file. # # To work around this problem, an exit handler is installed which tells the # workers to exit when their work queues are empty and then waits until the # threads finish. _threads_queues = weakref.WeakKeyDictionary() _shutdown = False def _python_exit(): global _shutdown _shutdown = True items = list(_threads_queues.items()) for t, q in items: q.put(None) for t, q in items: t.join() atexit.register(_python_exit) class _WorkItem(object): def __init__(self, future, fn, args, kwargs): self.future = future self.fn = fn self.args = args self.kwargs = kwargs def run(self): if not self.future.set_running_or_notify_cancel(): return try: result = self.fn(*self.args, **self.kwargs) except BaseException as exc: self.future.set_exception(exc) # Break a reference cycle with the exception 'exc' self = None else: self.future.set_result(result) def _worker(executor_reference, work_queue): try: while True: work_item = work_queue.get(block=True) if work_item is not None: work_item.run() # Delete references to object. See issue16284 del work_item continue executor = executor_reference() # Exit if: # - The interpreter is shutting down OR # - The executor that owns the worker has been collected OR # - The executor that owns the worker has been shutdown. if _shutdown or executor is None or executor._shutdown: # Notice other workers work_queue.put(None) return del executor except BaseException: _base.LOGGER.critical('Exception in worker', exc_info=True) class ThreadPoolExecutor(_base.Executor): # Used to assign unique thread names when thread_name_prefix is not supplied. _counter = itertools.count().__next__ def __init__(self, max_workers=None, thread_name_prefix=''): """Initializes a new ThreadPoolExecutor instance. Args: max_workers: The maximum number of threads that can be used to execute the given calls. thread_name_prefix: An optional name prefix to give our threads. """ if max_workers is None: # Use this number because ThreadPoolExecutor is often # used to overlap I/O instead of CPU work. max_workers = (os.cpu_count() or 1) * 5 if max_workers <= 0: raise ValueError("max_workers must be greater than 0") self._max_workers = max_workers self._work_queue = queue.Queue() self._threads = set() self._shutdown = False self._shutdown_lock = threading.Lock() self._thread_name_prefix = (thread_name_prefix or ("ThreadPoolExecutor-%d" % self._counter())) def submit(self, fn, *args, **kwargs): with self._shutdown_lock: if self._shutdown: raise RuntimeError('cannot schedule new futures after shutdown') f = _base.Future() w = _WorkItem(f, fn, args, kwargs) self._work_queue.put(w) self._adjust_thread_count() return f submit.__doc__ = _base.Executor.submit.__doc__ def _adjust_thread_count(self): # When the executor gets lost, the weakref callback will wake up # the worker threads. def weakref_cb(_, q=self._work_queue): q.put(None) # TODO(bquinlan): Should avoid creating new threads if there are more # idle threads than items in the work queue. num_threads = len(self._threads) if num_threads < self._max_workers: thread_name = '%s_%d' % (self._thread_name_prefix or self, num_threads) t = threading.Thread(name=thread_name, target=_worker, args=(weakref.ref(self, weakref_cb), self._work_queue)) t.daemon = True t.start() self._threads.add(t) _threads_queues[t] = self._work_queue def shutdown(self, wait=True): with self._shutdown_lock: self._shutdown = True self._work_queue.put(None) if wait: for t in self._threads: t.join() shutdown.__doc__ = _base.Executor.shutdown.__doc__
5,511
154
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/concurrent/futures/process.py
# Copyright 2009 Brian Quinlan. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Implements ProcessPoolExecutor. The follow diagram and text describe the data-flow through the system: |======================= In-process =====================|== Out-of-process ==| +----------+ +----------+ +--------+ +-----------+ +---------+ | | => | Work Ids | => | | => | Call Q | => | | | | +----------+ | | +-----------+ | | | | | ... | | | | ... | | | | | | 6 | | | | 5, call() | | | | | | 7 | | | | ... | | | | Process | | ... | | Local | +-----------+ | Process | | Pool | +----------+ | Worker | | #1..n | | Executor | | Thread | | | | | +----------- + | | +-----------+ | | | | <=> | Work Items | <=> | | <= | Result Q | <= | | | | +------------+ | | +-----------+ | | | | | 6: call() | | | | ... | | | | | | future | | | | 4, result | | | | | | ... | | | | 3, except | | | +----------+ +------------+ +--------+ +-----------+ +---------+ Executor.submit() called: - creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict - adds the id of the _WorkItem to the "Work Ids" queue Local worker thread: - reads work ids from the "Work Ids" queue and looks up the corresponding WorkItem from the "Work Items" dict: if the work item has been cancelled then it is simply removed from the dict, otherwise it is repackaged as a _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). - reads _ResultItems from "Result Q", updates the future stored in the "Work Items" dict and deletes the dict entry Process #1..n: - reads _CallItems from "Call Q", executes the calls, and puts the resulting _ResultItems in "Result Q" """ __author__ = 'Brian Quinlan ([email protected])' import atexit import os from concurrent.futures import _base import queue from queue import Full import multiprocessing from multiprocessing import SimpleQueue from multiprocessing.connection import wait import threading import weakref from functools import partial import itertools import traceback # Workers are created as daemon threads and processes. This is done to allow the # interpreter to exit when there are still idle processes in a # ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However, # allowing workers to die with the interpreter has two undesirable properties: # - The workers would still be running during interpreter shutdown, # meaning that they would fail in unpredictable ways. # - The workers could be killed while evaluating a work item, which could # be bad if the callable being evaluated has external side-effects e.g. # writing to a file. # # To work around this problem, an exit handler is installed which tells the # workers to exit when their work queues are empty and then waits until the # threads/processes finish. _threads_queues = weakref.WeakKeyDictionary() _shutdown = False def _python_exit(): global _shutdown _shutdown = True items = list(_threads_queues.items()) for t, q in items: q.put(None) for t, q in items: t.join() # Controls how many more calls than processes will be queued in the call queue. # A smaller number will mean that processes spend more time idle waiting for # work while a larger number will make Future.cancel() succeed less frequently # (Futures in the call queue cannot be cancelled). EXTRA_QUEUED_CALLS = 1 # Hack to embed stringification of remote traceback in local traceback class _RemoteTraceback(Exception): def __init__(self, tb): self.tb = tb def __str__(self): return self.tb class _ExceptionWithTraceback: def __init__(self, exc, tb): tb = traceback.format_exception(type(exc), exc, tb) tb = ''.join(tb) self.exc = exc self.tb = '\n"""\n%s"""' % tb def __reduce__(self): return _rebuild_exc, (self.exc, self.tb) def _rebuild_exc(exc, tb): exc.__cause__ = _RemoteTraceback(tb) return exc class _WorkItem(object): def __init__(self, future, fn, args, kwargs): self.future = future self.fn = fn self.args = args self.kwargs = kwargs class _ResultItem(object): def __init__(self, work_id, exception=None, result=None): self.work_id = work_id self.exception = exception self.result = result class _CallItem(object): def __init__(self, work_id, fn, args, kwargs): self.work_id = work_id self.fn = fn self.args = args self.kwargs = kwargs def _get_chunks(*iterables, chunksize): """ Iterates over zip()ed iterables in chunks. """ it = zip(*iterables) while True: chunk = tuple(itertools.islice(it, chunksize)) if not chunk: return yield chunk def _process_chunk(fn, chunk): """ Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. This function is run in a separate process. """ return [fn(*args) for args in chunk] def _process_worker(call_queue, result_queue): """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. Args: call_queue: A multiprocessing.Queue of _CallItems that will be read and evaluated by the worker. result_queue: A multiprocessing.Queue of _ResultItems that will written to by the worker. shutdown: A multiprocessing.Event that will be set as a signal to the worker that it should exit when call_queue is empty. """ while True: call_item = call_queue.get(block=True) if call_item is None: # Wake up queue management thread result_queue.put(os.getpid()) return try: r = call_item.fn(*call_item.args, **call_item.kwargs) except BaseException as e: exc = _ExceptionWithTraceback(e, e.__traceback__) result_queue.put(_ResultItem(call_item.work_id, exception=exc)) else: result_queue.put(_ResultItem(call_item.work_id, result=r)) def _add_call_item_to_queue(pending_work_items, work_ids, call_queue): """Fills call_queue with _WorkItems from pending_work_items. This function never blocks. Args: pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids are consumed and the corresponding _WorkItems from pending_work_items are transformed into _CallItems and put in call_queue. call_queue: A multiprocessing.Queue that will be filled with _CallItems derived from _WorkItems. """ while True: if call_queue.full(): return try: work_id = work_ids.get(block=False) except queue.Empty: return else: work_item = pending_work_items[work_id] if work_item.future.set_running_or_notify_cancel(): call_queue.put(_CallItem(work_id, work_item.fn, work_item.args, work_item.kwargs), block=True) else: del pending_work_items[work_id] continue def _queue_management_worker(executor_reference, processes, pending_work_items, work_ids_queue, call_queue, result_queue): """Manages the communication between this process and the worker processes. This function is run in a local thread. Args: executor_reference: A weakref.ref to the ProcessPoolExecutor that owns this thread. Used to determine if the ProcessPoolExecutor has been garbage collected and that this function can exit. process: A list of the multiprocessing.Process instances used as workers. pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). call_queue: A multiprocessing.Queue that will be filled with _CallItems derived from _WorkItems for processing by the process workers. result_queue: A multiprocessing.Queue of _ResultItems generated by the process workers. """ executor = None def shutting_down(): return _shutdown or executor is None or executor._shutdown_thread def shutdown_worker(): # This is an upper bound nb_children_alive = sum(p.is_alive() for p in processes.values()) for i in range(0, nb_children_alive): call_queue.put_nowait(None) # Release the queue's resources as soon as possible. call_queue.close() # If .join() is not called on the created processes then # some multiprocessing.Queue methods may deadlock on Mac OS X. for p in processes.values(): p.join() reader = result_queue._reader while True: _add_call_item_to_queue(pending_work_items, work_ids_queue, call_queue) sentinels = [p.sentinel for p in processes.values()] assert sentinels ready = wait([reader] + sentinels) if reader in ready: result_item = reader.recv() else: # Mark the process pool broken so that submits fail right now. executor = executor_reference() if executor is not None: executor._broken = True executor._shutdown_thread = True executor = None # All futures in flight must be marked failed for work_id, work_item in pending_work_items.items(): work_item.future.set_exception( BrokenProcessPool( "A process in the process pool was " "terminated abruptly while the future was " "running or pending." )) # Delete references to object. See issue16284 del work_item pending_work_items.clear() # Terminate remaining workers forcibly: the queues or their # locks may be in a dirty state and block forever. for p in processes.values(): p.terminate() shutdown_worker() return if isinstance(result_item, int): # Clean shutdown of a worker using its PID # (avoids marking the executor broken) assert shutting_down() p = processes.pop(result_item) p.join() if not processes: shutdown_worker() return elif result_item is not None: work_item = pending_work_items.pop(result_item.work_id, None) # work_item can be None if another process terminated (see above) if work_item is not None: if result_item.exception: work_item.future.set_exception(result_item.exception) else: work_item.future.set_result(result_item.result) # Delete references to object. See issue16284 del work_item # Check whether we should start shutting down. executor = executor_reference() # No more work items can be added if: # - The interpreter is shutting down OR # - The executor that owns this worker has been collected OR # - The executor that owns this worker has been shutdown. if shutting_down(): try: # Since no new work items can be added, it is safe to shutdown # this thread if there are no pending work items. if not pending_work_items: shutdown_worker() return except Full: # This is not a problem: we will eventually be woken up (in # result_queue.get()) and be able to send a sentinel again. pass executor = None _system_limits_checked = False _system_limited = None def _check_system_limits(): global _system_limits_checked, _system_limited if _system_limits_checked: if _system_limited: raise NotImplementedError(_system_limited) _system_limits_checked = True try: nsems_max = os.sysconf("SC_SEM_NSEMS_MAX") except (AttributeError, ValueError): # sysconf not available or setting not available return if nsems_max == -1: # indetermined limit, assume that limit is determined # by available memory only return if nsems_max >= 256: # minimum number of semaphores available # according to POSIX return _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max raise NotImplementedError(_system_limited) def _chain_from_iterable_of_lists(iterable): """ Specialized implementation of itertools.chain.from_iterable. Each item in *iterable* should be a list. This function is careful not to keep references to yielded objects. """ for element in iterable: element.reverse() while element: yield element.pop() class BrokenProcessPool(RuntimeError): """ Raised when a process in a ProcessPoolExecutor terminated abruptly while a future was in the running state. """ class ProcessPoolExecutor(_base.Executor): def __init__(self, max_workers=None): """Initializes a new ProcessPoolExecutor instance. Args: max_workers: The maximum number of processes that can be used to execute the given calls. If None or not given then as many worker processes will be created as the machine has processors. """ _check_system_limits() if max_workers is None: self._max_workers = os.cpu_count() or 1 else: if max_workers <= 0: raise ValueError("max_workers must be greater than 0") self._max_workers = max_workers # Make the call queue slightly larger than the number of processes to # prevent the worker processes from idling. But don't make it too big # because futures in the call queue cannot be cancelled. self._call_queue = multiprocessing.Queue(self._max_workers + EXTRA_QUEUED_CALLS) # Killed worker processes can produce spurious "broken pipe" # tracebacks in the queue's own worker thread. But we detect killed # processes anyway, so silence the tracebacks. self._call_queue._ignore_epipe = True self._result_queue = SimpleQueue() self._work_ids = queue.Queue() self._queue_management_thread = None # Map of pids to processes self._processes = {} # Shutdown is a two-step process. self._shutdown_thread = False self._shutdown_lock = threading.Lock() self._broken = False self._queue_count = 0 self._pending_work_items = {} def _start_queue_management_thread(self): # When the executor gets lost, the weakref callback will wake up # the queue management thread. def weakref_cb(_, q=self._result_queue): q.put(None) if self._queue_management_thread is None: # Start the processes so that their sentinels are known. self._adjust_process_count() self._queue_management_thread = threading.Thread( target=_queue_management_worker, args=(weakref.ref(self, weakref_cb), self._processes, self._pending_work_items, self._work_ids, self._call_queue, self._result_queue)) self._queue_management_thread.daemon = True self._queue_management_thread.start() _threads_queues[self._queue_management_thread] = self._result_queue def _adjust_process_count(self): for _ in range(len(self._processes), self._max_workers): p = multiprocessing.Process( target=_process_worker, args=(self._call_queue, self._result_queue)) p.start() self._processes[p.pid] = p def submit(self, fn, *args, **kwargs): with self._shutdown_lock: if self._broken: raise BrokenProcessPool('A child process terminated ' 'abruptly, the process pool is not usable anymore') if self._shutdown_thread: raise RuntimeError('cannot schedule new futures after shutdown') f = _base.Future() w = _WorkItem(f, fn, args, kwargs) self._pending_work_items[self._queue_count] = w self._work_ids.put(self._queue_count) self._queue_count += 1 # Wake up queue management thread self._result_queue.put(None) self._start_queue_management_thread() return f submit.__doc__ = _base.Executor.submit.__doc__ def map(self, fn, *iterables, timeout=None, chunksize=1): """Returns an iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. chunksize: If greater than one, the iterables will be chopped into chunks of size chunksize and submitted to the process pool. If set to one, the items in the list will be sent one at a time. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. Exception: If fn(*args) raises for any values. """ if chunksize < 1: raise ValueError("chunksize must be >= 1.") results = super().map(partial(_process_chunk, fn), _get_chunks(*iterables, chunksize=chunksize), timeout=timeout) return _chain_from_iterable_of_lists(results) def shutdown(self, wait=True): with self._shutdown_lock: self._shutdown_thread = True if self._queue_management_thread: # Wake up queue management thread self._result_queue.put(None) if wait: self._queue_management_thread.join() # To reduce the risk of opening too many files, remove references to # objects that use file descriptors. self._queue_management_thread = None self._call_queue = None self._result_queue = None self._processes = None shutdown.__doc__ = _base.Executor.shutdown.__doc__ atexit.register(_python_exit)
20,492
516
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/concurrent/futures/__init__.py
# Copyright 2009 Brian Quinlan. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Execute computations asynchronously using threads or processes.""" __author__ = 'Brian Quinlan ([email protected])' from concurrent.futures._base import (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed) from concurrent.futures.process import ProcessPoolExecutor from concurrent.futures.thread import ThreadPoolExecutor
800
19
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/case.py
"""Test case implementation""" import sys import functools import difflib import logging import pprint import re import warnings import collections import contextlib import traceback from . import result from .util import (strclass, safe_repr, _count_diff_all_purpose, _count_diff_hashable, _common_shorten_repr) __unittest = True _subtest_msg_sentinel = object() DIFF_OMITTED = ('\nDiff is %s characters long. ' 'Set self.maxDiff to None to see it.') class SkipTest(Exception): """ Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. """ class _ShouldStop(Exception): """ The test should stop. """ class _UnexpectedSuccess(Exception): """ The test was supposed to fail, but it didn't! """ class _Outcome(object): def __init__(self, result=None): self.expecting_failure = False self.result = result self.result_supports_subtests = hasattr(result, "addSubTest") self.success = True self.skipped = [] self.expectedFailure = None self.errors = [] @contextlib.contextmanager def testPartExecutor(self, test_case, isTest=False): old_success = self.success self.success = True try: yield except KeyboardInterrupt: raise except SkipTest as e: self.success = False self.skipped.append((test_case, str(e))) except _ShouldStop: pass except: exc_info = sys.exc_info() if self.expecting_failure: self.expectedFailure = exc_info else: self.success = False self.errors.append((test_case, exc_info)) # explicitly break a reference cycle: # exc_info -> frame -> exc_info exc_info = None else: if self.result_supports_subtests and self.success: self.errors.append((test_case, None)) finally: self.success = self.success and old_success def _id(obj): return obj def skip(reason): """ Unconditionally skip a test. """ def decorator(test_item): if not isinstance(test_item, type): @functools.wraps(test_item) def skip_wrapper(*args, **kwargs): raise SkipTest(reason) test_item = skip_wrapper test_item.__unittest_skip__ = True test_item.__unittest_skip_why__ = reason return test_item return decorator def skipIf(condition, reason): """ Skip a test if the condition is true. """ if condition: return skip(reason) return _id def skipUnless(condition, reason): """ Skip a test unless the condition is true. """ if not condition: return skip(reason) return _id def expectedFailure(test_item): test_item.__unittest_expecting_failure__ = True return test_item def _is_subtype(expected, basetype): if isinstance(expected, tuple): return all(_is_subtype(e, basetype) for e in expected) return isinstance(expected, type) and issubclass(expected, basetype) class _BaseTestCaseContext: def __init__(self, test_case): self.test_case = test_case def _raiseFailure(self, standardMsg): msg = self.test_case._formatMessage(self.msg, standardMsg) raise self.test_case.failureException(msg) class _AssertRaisesBaseContext(_BaseTestCaseContext): def __init__(self, expected, test_case, expected_regex=None): _BaseTestCaseContext.__init__(self, test_case) self.expected = expected self.test_case = test_case if expected_regex is not None: expected_regex = re.compile(expected_regex) self.expected_regex = expected_regex self.obj_name = None self.msg = None def handle(self, name, args, kwargs): """ If args is empty, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If args is not empty, call a callable passing positional and keyword arguments. """ try: if not _is_subtype(self.expected, self._base_type): raise TypeError('%s() arg 1 must be %s' % (name, self._base_type_str)) if args and args[0] is None: warnings.warn("callable is None", DeprecationWarning, 3) args = () if not args: self.msg = kwargs.pop('msg', None) if kwargs: warnings.warn('%r is an invalid keyword argument for ' 'this function' % next(iter(kwargs)), DeprecationWarning, 3) return self callable_obj, *args = args try: self.obj_name = callable_obj.__name__ except AttributeError: self.obj_name = str(callable_obj) with self: callable_obj(*args, **kwargs) finally: # bpo-23890: manually break a reference cycle self = None class _AssertRaisesContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertRaises* methods.""" _base_type = BaseException _base_type_str = 'an exception type or tuple of exception types' def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) if self.obj_name: self._raiseFailure("{} not raised by {}".format(exc_name, self.obj_name)) else: self._raiseFailure("{} not raised".format(exc_name)) else: traceback.clear_frames(tb) if not issubclass(exc_type, self.expected): # let unexpected exceptions pass through return False # store exception, without traceback, for later retrieval self.exception = exc_value.with_traceback(None) if self.expected_regex is None: return True expected_regex = self.expected_regex if not expected_regex.search(str(exc_value)): self._raiseFailure('"{}" does not match "{}"'.format( expected_regex.pattern, str(exc_value))) return True class _AssertWarnsContext(_AssertRaisesBaseContext): """A context manager used to implement TestCase.assertWarns* methods.""" _base_type = Warning _base_type_str = 'a warning type or tuple of warning types' def __enter__(self): # The __warningregistry__'s need to be in a pristine state for tests # to work properly. for v in sys.modules.values(): if getattr(v, '__warningregistry__', None): v.__warningregistry__ = {} self.warnings_manager = warnings.catch_warnings(record=True) self.warnings = self.warnings_manager.__enter__() warnings.simplefilter("always", self.expected) return self def __exit__(self, exc_type, exc_value, tb): self.warnings_manager.__exit__(exc_type, exc_value, tb) if exc_type is not None: # let unexpected exceptions pass through return try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) first_matching = None for m in self.warnings: w = m.message if not isinstance(w, self.expected): continue if first_matching is None: first_matching = w if (self.expected_regex is not None and not self.expected_regex.search(str(w))): continue # store warning for later retrieval self.warning = w self.filename = m.filename self.lineno = m.lineno return # Now we simply try to choose a helpful failure message if first_matching is not None: self._raiseFailure('"{}" does not match "{}"'.format( self.expected_regex.pattern, str(first_matching))) if self.obj_name: self._raiseFailure("{} not triggered by {}".format(exc_name, self.obj_name)) else: self._raiseFailure("{} not triggered".format(exc_name)) _LoggingWatcher = collections.namedtuple("_LoggingWatcher", ["records", "output"]) class _CapturingHandler(logging.Handler): """ A logging handler capturing all (raw and formatted) logging output. """ def __init__(self): logging.Handler.__init__(self) self.watcher = _LoggingWatcher([], []) def flush(self): pass def emit(self, record): self.watcher.records.append(record) msg = self.format(record) self.watcher.output.append(msg) class _AssertLogsContext(_BaseTestCaseContext): """A context manager used to implement TestCase.assertLogs().""" LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s" def __init__(self, test_case, logger_name, level): _BaseTestCaseContext.__init__(self, test_case) self.logger_name = logger_name if level: self.level = logging._nameToLevel.get(level, level) else: self.level = logging.INFO self.msg = None def __enter__(self): if isinstance(self.logger_name, logging.Logger): logger = self.logger = self.logger_name else: logger = self.logger = logging.getLogger(self.logger_name) formatter = logging.Formatter(self.LOGGING_FORMAT) handler = _CapturingHandler() handler.setFormatter(formatter) self.watcher = handler.watcher self.old_handlers = logger.handlers[:] self.old_level = logger.level self.old_propagate = logger.propagate logger.handlers = [handler] logger.setLevel(self.level) logger.propagate = False return handler.watcher def __exit__(self, exc_type, exc_value, tb): self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if len(self.watcher.records) == 0: self._raiseFailure( "no logs of level {} or higher triggered on {}" .format(logging.getLevelName(self.level), self.logger.name)) class TestCase(object): """A class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute. Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively. If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run. When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in *addition* to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required. """ failureException = AssertionError longMessage = True maxDiff = 80*8 # If a string is longer than _diffThreshold, use normal comparison instead # of difflib. See #11763. _diffThreshold = 2**16 # Attribute used by TestSuite for classSetUp _classSetupFailed = False 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._outcome = None self._testMethodDoc = 'No test' try: testMethod = getattr(self, methodName) except AttributeError: if methodName != 'runTest': # we allow instantiation with no explicit method name # but not an *incorrect* or missing method name raise ValueError("no such test method in %s: %s" % (self.__class__, methodName)) else: self._testMethodDoc = testMethod.__doc__ self._cleanups = [] self._subtest = None # 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') self.addTypeEqualityFunc(str, 'assertMultiLineEqual') def addTypeEqualityFunc(self, typeobj, function): """Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. Args: typeobj: The data type to call this function on when both values are of the same type in assertEqual(). function: The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal. """ self._type_equality_funcs[typeobj] = function def addCleanup(self, function, *args, **kwargs): """Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown).""" self._cleanups.append((function, args, kwargs)) def setUp(self): "Hook method for setting up the test fixture before exercising it." pass def tearDown(self): "Hook method for deconstructing the test fixture after testing it." pass @classmethod def setUpClass(cls): "Hook method for setting up class fixture before running tests in the class." @classmethod def tearDownClass(cls): "Hook method for deconstructing the class fixture after running all tests in the class." def countTestCases(self): return 1 def defaultTestResult(self): return result.TestResult() 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 def id(self): return "%s.%s" % (strclass(self.__class__), self._testMethodName) def __eq__(self, other): if type(self) is not type(other): return NotImplemented return self._testMethodName == other._testMethodName def __hash__(self): return hash((type(self), self._testMethodName)) def __str__(self): return "%s (%s)" % (self._testMethodName, strclass(self.__class__)) def __repr__(self): return "<%s testMethod=%s>" % \ (strclass(self.__class__), self._testMethodName) def _addSkip(self, result, test_case, reason): addSkip = getattr(result, 'addSkip', None) if addSkip is not None: addSkip(test_case, reason) else: warnings.warn("TestResult has no addSkip method, skips not reported", RuntimeWarning, 2) result.addSuccess(test_case) @contextlib.contextmanager def subTest(self, msg=_subtest_msg_sentinel, **params): """Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed. """ if self._outcome is None or not self._outcome.result_supports_subtests: yield return parent = self._subtest if parent is None: params_map = collections.ChainMap(params) else: params_map = parent.params.new_child(params) self._subtest = _SubTest(self, msg, params_map) try: with self._outcome.testPartExecutor(self._subtest, isTest=True): yield if not self._outcome.success: result = self._outcome.result if result is not None and result.failfast: raise _ShouldStop elif self._outcome.expectedFailure: # If the test is expecting a failure, we really want to # stop now and register the expected failure. raise _ShouldStop finally: self._subtest = parent def _feedErrorsToResult(self, result, errors): for test, exc_info in errors: if isinstance(test, _SubTest): result.addSubTest(test.test_case, test, exc_info) elif exc_info is not None: if issubclass(exc_info[0], self.failureException): result.addFailure(test, exc_info) else: result.addError(test, exc_info) def _addExpectedFailure(self, result, exc_info): try: addExpectedFailure = result.addExpectedFailure except AttributeError: warnings.warn("TestResult has no addExpectedFailure method, reporting as passes", RuntimeWarning) result.addSuccess(self) else: addExpectedFailure(self, exc_info) def _addUnexpectedSuccess(self, result): try: addUnexpectedSuccess = result.addUnexpectedSuccess except AttributeError: warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure", RuntimeWarning) # We need to pass an actual exception and traceback to addFailure, # otherwise the legacy result can choke. try: raise _UnexpectedSuccess from None except _UnexpectedSuccess: result.addFailure(self, sys.exc_info()) else: addUnexpectedSuccess(self) def run(self, result=None): orig_result = result if result is None: result = self.defaultTestResult() startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: startTestRun() result.startTest(self) testMethod = getattr(self, self._testMethodName) if (getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. try: skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) self._addSkip(result, self, skip_why) finally: result.stopTest(self) return expecting_failure_method = getattr(testMethod, "__unittest_expecting_failure__", False) expecting_failure_class = getattr(self, "__unittest_expecting_failure__", False) expecting_failure = expecting_failure_class or expecting_failure_method outcome = _Outcome(result) try: self._outcome = outcome with outcome.testPartExecutor(self): self.setUp() if outcome.success: outcome.expecting_failure = expecting_failure with outcome.testPartExecutor(self, isTest=True): testMethod() outcome.expecting_failure = False with outcome.testPartExecutor(self): self.tearDown() self.doCleanups() for test, reason in outcome.skipped: self._addSkip(result, test, reason) self._feedErrorsToResult(result, outcome.errors) if outcome.success: if expecting_failure: if outcome.expectedFailure: self._addExpectedFailure(result, outcome.expectedFailure) else: self._addUnexpectedSuccess(result) else: result.addSuccess(self) return result finally: result.stopTest(self) if orig_result is None: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() # explicitly break reference cycles: # outcome.errors -> frame -> outcome -> outcome.errors # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure outcome.errors.clear() outcome.expectedFailure = None # clear the outcome, no more needed self._outcome = None def doCleanups(self): """Execute all cleanup functions. Normally called for you after tearDown.""" outcome = self._outcome or _Outcome() while self._cleanups: function, args, kwargs = self._cleanups.pop() with outcome.testPartExecutor(self): function(*args, **kwargs) # return this for backwards compatibility # even though we no longer us it internally return outcome.success def __call__(self, *args, **kwds): return self.run(*args, **kwds) 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) def skipTest(self, reason): """Skip this test.""" raise SkipTest(reason) def fail(self, msg=None): """Fail immediately, with the given message.""" raise self.failureException(msg) 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) 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) 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)) def assertRaises(self, expected_exception, *args, **kwargs): """Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertRaises(SomeException): do_something() An optional keyword argument 'msg' can be provided when assertRaises is used as a context object. The context manager keeps a reference to the exception as the 'exception' attribute. This allows you to inspect the exception after the assertion:: with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3) """ context = _AssertRaisesContext(expected_exception, self) try: return context.handle('assertRaises', args, kwargs) finally: # bpo-23890: manually break a reference cycle context = None def assertWarns(self, expected_warning, *args, **kwargs): """Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertWarns(SomeWarning): do_something() An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm: do_something() the_warning = cm.warning self.assertEqual(the_warning.some_attribute, 147) """ context = _AssertWarnsContext(expected_warning, self) return context.handle('assertWarns', args, kwargs) def assertLogs(self, logger=None, level=None): """Fail unless a log message of level *level* or higher is emitted on *logger_name* or its children. If omitted, *level* defaults to INFO and *logger* defaults to the root logger. This method must be used as a context manager, and will yield a recording object with two attributes: `output` and `records`. At the end of the context manager, the `output` attribute will be a list of the matching formatted log messages and the `records` attribute will be a list of the corresponding LogRecord objects. Example:: with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) """ return _AssertLogsContext(self, logger, level) 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, str): asserter = getattr(self, asserter) return asserter return self._baseAssertEqual def _baseAssertEqual(self, first, second, msg=None): """The default assertEqual implementation, not type specific.""" if not first == second: standardMsg = '%s != %s' % _common_shorten_repr(first, second) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) 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) 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) 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 difference 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 significant 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) 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 difference 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 significant 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) 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 differing = '%ss differ: %s != %s\n' % ( (seq_type_name.capitalize(),) + _common_shorten_repr(seq1, seq2)) for i in range(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,) + _common_shorten_repr(item1, 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) def _truncateMessage(self, message, diff): max_diff = self.maxDiff if max_diff is None or len(diff) <= max_diff: return message + diff return message + (DIFF_OMITTED % len(diff)) def assertListEqual(self, list1, list2, msg=None): """A list-specific equality assertion. Args: list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(list1, list2, msg, seq_type=list) def assertTupleEqual(self, tuple1, tuple2, msg=None): """A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of differences. """ self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) 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 as e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError as e: self.fail('first argument does not support set difference: %s' % e) try: difference2 = set2.difference(set1) except TypeError as e: self.fail('invalid type when attempting set difference: %s' % e) except AttributeError as 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)) 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)) 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)) 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)) 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)) def assertDictEqual(self, d1, d2, msg=None): self.assertIsInstance(d1, dict, 'First argument is not a dictionary') self.assertIsInstance(d2, dict, 'Second argument is not a dictionary') if d1 != d2: standardMsg = '%s != %s' % _common_shorten_repr(d1, d2) diff = ('\n' + '\n'.join(difflib.ndiff( pprint.pformat(d1).splitlines(), pprint.pformat(d2).splitlines()))) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertDictContainsSubset(self, subset, dictionary, msg=None): """Checks whether dictionary is a superset of subset.""" warnings.warn('assertDictContainsSubset is deprecated', DeprecationWarning) missing = [] mismatched = [] for key, value in subset.items(): if key not in dictionary: missing.append(key) elif value != dictionary[key]: mismatched.append('%s, expected: %s, actual: %s' % (safe_repr(key), safe_repr(value), safe_repr(dictionary[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)) def assertCountEqual(self, first, second, msg=None): """An unordered sequence comparison asserting that the same elements, regardless of order. If the same element occurs more than once, it verifies that the elements occur the same number of times. self.assertEqual(Counter(list(first)), Counter(list(second))) Example: - [0, 1, 1] and [1, 0, 1] compare equal. - [0, 0, 1] and [0, 1] compare unequal. """ first_seq, second_seq = list(first), list(second) 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) def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" self.assertIsInstance(first, str, 'First argument is not a string') self.assertIsInstance(second, str, '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(keepends=True) secondlines = second.splitlines(keepends=True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % _common_shorten_repr(first, second) diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) 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)) 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)) 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)) 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)) 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)) def assertIsNotNone(self, obj, msg=None): """Included for symmetry with assertIsNone.""" if obj is None: standardMsg = 'unexpectedly None' self.fail(self._formatMessage(msg, standardMsg)) 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)) def assertNotIsInstance(self, obj, cls, msg=None): """Included for symmetry with assertIsInstance.""" if isinstance(obj, cls): standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls) self.fail(self._formatMessage(msg, standardMsg)) def assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs): """Asserts that the message in a raised exception matches a regex. Args: expected_exception: Exception class expected to be raised. expected_regex: Regex (re pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager. """ context = _AssertRaisesContext(expected_exception, self, expected_regex) return context.handle('assertRaisesRegex', args, kwargs) def assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs): """Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches. Args: expected_warning: Warning class expected to be triggered. expected_regex: Regex (re pattern object or string) expected to be found in error message. args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager. """ context = _AssertWarnsContext(expected_warning, self, expected_regex) return context.handle('assertWarnsRegex', args, kwargs) def assertRegex(self, text, expected_regex, msg=None): """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regex, (str, bytes)): assert expected_regex, "expected_regex must not be empty." expected_regex = re.compile(expected_regex) if not expected_regex.search(text): standardMsg = "Regex didn't match: %r not found in %r" % ( expected_regex.pattern, text) # _formatMessage ensures the longMessage option is respected msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertNotRegex(self, text, unexpected_regex, msg=None): """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regex, (str, bytes)): unexpected_regex = re.compile(unexpected_regex) match = unexpected_regex.search(text) if match: standardMsg = 'Regex matched: %r matches %r in %r' % ( text[match.start() : match.end()], unexpected_regex.pattern, text) # _formatMessage ensures the longMessage option is respected msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def _deprecate(original_func): def deprecated_func(*args, **kwargs): warnings.warn( 'Please use {0} instead.'.format(original_func.__name__), DeprecationWarning, 2) return original_func(*args, **kwargs) return deprecated_func # see #9424 failUnlessEqual = assertEquals = _deprecate(assertEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failUnless = assert_ = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) assertRaisesRegexp = _deprecate(assertRaisesRegex) assertRegexpMatches = _deprecate(assertRegex) assertNotRegexpMatches = _deprecate(assertNotRegex) class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the unittest framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): super(FunctionTestCase, self).__init__() self._setUpFunc = setUp self._tearDownFunc = tearDown self._testFunc = testFunc self._description = description def setUp(self): if self._setUpFunc is not None: self._setUpFunc() def tearDown(self): if self._tearDownFunc is not None: self._tearDownFunc() def runTest(self): self._testFunc() def id(self): return self._testFunc.__name__ def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self._setUpFunc == other._setUpFunc and \ self._tearDownFunc == other._tearDownFunc and \ self._testFunc == other._testFunc and \ self._description == other._description def __hash__(self): return hash((type(self), self._setUpFunc, self._tearDownFunc, self._testFunc, self._description)) def __str__(self): return "%s (%s)" % (strclass(self.__class__), self._testFunc.__name__) def __repr__(self): return "<%s tec=%s>" % (strclass(self.__class__), self._testFunc) def shortDescription(self): if self._description is not None: return self._description doc = self._testFunc.__doc__ return doc and doc.split("\n")[0].strip() or None class _SubTest(TestCase): def __init__(self, test_case, message, params): super().__init__() self._message = message self.test_case = test_case self.params = params self.failureException = test_case.failureException def runTest(self): raise NotImplementedError("subtests cannot be run directly") def _subDescription(self): parts = [] if self._message is not _subtest_msg_sentinel: parts.append("[{}]".format(self._message)) if self.params: params_desc = ', '.join( "{}={!r}".format(k, v) for (k, v) in sorted(self.params.items())) parts.append("({})".format(params_desc)) return " ".join(parts) or '(<subtest>)' def id(self): return "{} {}".format(self.test_case.id(), self._subDescription()) def shortDescription(self): """Returns a one-line description of the subtest, or None if no description has been provided. """ return self.test_case.shortDescription() def __str__(self): return "{} {}".format(self.test_case, self._subDescription())
56,986
1,430
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/signals.py
import signal import weakref from functools import wraps __unittest = True class _InterruptHandler(object): def __init__(self, default_handler): self.called = False self.original_handler = default_handler if isinstance(default_handler, int): if default_handler == signal.SIG_DFL: # Pretend it's signal.default_int_handler instead. default_handler = signal.default_int_handler elif default_handler == signal.SIG_IGN: # Not quite the same thing as SIG_IGN, but the closest we # can make it: do nothing. def default_handler(unused_signum, unused_frame): pass else: raise TypeError("expected SIGINT signal handler to be " "signal.SIG_IGN, signal.SIG_DFL, or a " "callable object") self.default_handler = default_handler def __call__(self, signum, frame): installed_handler = signal.getsignal(signal.SIGINT) if installed_handler is not self: # if we aren't the installed handler, then delegate immediately # to the default handler self.default_handler(signum, frame) if self.called: self.default_handler(signum, frame) self.called = True for result in _results.keys(): result.stop() _results = weakref.WeakKeyDictionary() def registerResult(result): _results[result] = 1 def removeResult(result): return bool(_results.pop(result, None)) _interrupt_handler = None def installHandler(): global _interrupt_handler if _interrupt_handler is None: default_handler = signal.getsignal(signal.SIGINT) _interrupt_handler = _InterruptHandler(default_handler) signal.signal(signal.SIGINT, _interrupt_handler) def removeHandler(method=None): if method is not None: @wraps(method) def inner(*args, **kwargs): initial = signal.getsignal(signal.SIGINT) removeHandler() try: return method(*args, **kwargs) finally: signal.signal(signal.SIGINT, initial) return inner global _interrupt_handler if _interrupt_handler is not None: signal.signal(signal.SIGINT, _interrupt_handler.original_handler)
2,403
72
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/loader.py
"""Loading unittests.""" import os import re import sys import traceback import types import functools import warnings from fnmatch import fnmatch from . import case, suite, util __unittest = True # what about .pyc (etc) # we would need to avoid loading the same tests multiple times # from '.py', *and* '.pyc' VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) class _FailedTest(case.TestCase): _testMethodName = None def __init__(self, method_name, exception): self._exception = exception super(_FailedTest, self).__init__(method_name) def __getattr__(self, name): if name != self._testMethodName: return super(_FailedTest, self).__getattr__(name) def testFailure(): raise self._exception return testFailure def _make_failed_import_test(name, suiteClass): message = 'Failed to import test module: %s\n%s' % ( name, traceback.format_exc()) return _make_failed_test(name, ImportError(message), suiteClass, message) def _make_failed_load_tests(name, exception, suiteClass): message = 'Failed to call load_tests:\n%s' % (traceback.format_exc(),) return _make_failed_test( name, exception, suiteClass, message) def _make_failed_test(methodname, exception, suiteClass, message): test = _FailedTest(methodname, exception) return suiteClass((test,)), message def _make_skipped_test(methodname, exception, suiteClass): @case.skip(str(exception)) def testSkipped(self): pass attrs = {methodname: testSkipped} TestClass = type("ModuleSkipped", (case.TestCase,), attrs) return suiteClass((TestClass(methodname),)) def _jython_aware_splitext(path): if path.lower().endswith('$py.class'): return path[:-9] return os.path.splitext(path)[0] class TestLoader(object): """ This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite """ testMethodPrefix = 'test' sortTestMethodsUsing = staticmethod(util.three_way_cmp) suiteClass = suite.TestSuite _top_level_dir = None def __init__(self): super(TestLoader, self).__init__() self.errors = [] # Tracks packages which we have called into via load_tests, to # avoid infinite re-entrancy. self._loading_packages = set() def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all test 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 # XXX After Python 3.5, remove backward compatibility hacks for # use_load_tests deprecation via *args and **kws. See issue 16662. def loadTestsFromModule(self, module, *args, pattern=None, **kws): """Return a suite of all test cases contained in the given module""" # This method used to take an undocumented and unofficial # use_load_tests argument. For backward compatibility, we still # accept the argument (which can also be the first position) but we # ignore it and issue a deprecation warning if it's present. if len(args) > 0 or 'use_load_tests' in kws: warnings.warn('use_load_tests is deprecated and ignored', DeprecationWarning) kws.pop('use_load_tests', None) if len(args) > 1: # Complain about the number of arguments, but don't forget the # required `module` argument. complaint = len(args) + 1 raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(complaint)) if len(kws) != 0: # Since the keyword arguments are unsorted (see PEP 468), just # pick the alphabetically sorted first argument to complain about, # if multiple were given. At least the error message will be # predictable. complaint = sorted(kws)[0] raise TypeError("loadTestsFromModule() got an unexpected keyword argument '{}'".format(complaint)) 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 load_tests is not None: try: return load_tests(self, tests, pattern) except Exception as e: error_case, error_message = _make_failed_load_tests( module.__name__, e, self.suiteClass) self.errors.append(error_message) return error_case return tests def loadTestsFromName(self, name, module=None): """Return a suite of all test 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('.') error_case, error_message = None, None if module is None: parts_copy = parts[:] while parts_copy: try: module_name = '.'.join(parts_copy) module = __import__(module_name) break except ImportError: next_attribute = parts_copy.pop() # Last error so we can give it to the user if needed. error_case, error_message = _make_failed_import_test( next_attribute, self.suiteClass) if not parts_copy: # Even the top level import failed: report that error. self.errors.append(error_message) return error_case parts = parts[1:] obj = module for part in parts: try: parent, obj = obj, getattr(obj, part) except AttributeError as e: # We can't traverse some part of the name. if (getattr(obj, '__path__', None) is not None and error_case is not None): # This is a package (no __path__ per importlib docs), and we # encountered an error importing something. We cannot tell # the difference between package.WrongNameTestClass and # package.wrong_module_name so we just report the # ImportError - it is more informative. self.errors.append(error_message) return error_case else: # Otherwise, we signal that an AttributeError has occurred. error_case, error_message = _make_failed_test( part, e, self.suiteClass, 'Failed to access attribute:\n%s' % ( traceback.format_exc(),)) self.errors.append(error_message) return error_case 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.FunctionType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): name = parts[-1] inst = parent(name) # static methods follow a different path if not isinstance(getattr(inst, name), types.FunctionType): return self.suiteClass([inst]) elif isinstance(obj, suite.TestSuite): return obj if callable(obj): 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) def loadTestsFromNames(self, names, module=None): """Return a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. """ suites = [self.loadTestsFromName(name, module) for name in names] return self.suiteClass(suites) 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 \ callable(getattr(testCaseClass, attrname)) testFnNames = list(filter(isTestMethod, dir(testCaseClass))) if self.sortTestMethodsUsing: testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing)) return testFnNames 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 and return all tests found within 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) unless the package has already had load_tests called from the same discovery invocation, in which case the package module object is not scanned for tests - this ensures that when a package uses discover to further discover child tests that infinite recursion does not happen. 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(). Paths are sorted before being imported to ensure reproducible execution order even on filesystems with non-alphabetical ordering like ext3/4. """ 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 is_namespace = False tests = [] 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_py = not os.path.isfile(os.path.join(start_dir, '__init__.py')) is_not_importable_pyc = not os.path.isfile(os.path.join(start_dir, '__init__.pyc')) is_not_importable = is_not_importable_py and is_not_importable_pyc 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] try: start_dir = os.path.abspath( os.path.dirname((the_module.__file__))) except AttributeError: # look for namespace packages try: spec = the_module.__spec__ except AttributeError: spec = None if spec and spec.loader is None: if spec.submodule_search_locations is not None: is_namespace = True for path in the_module.__path__: if (not set_implicit_top and not path.startswith(top_level_dir)): continue self._top_level_dir = \ (path.split(the_module.__name__ .replace(".", os.path.sep))[0]) tests.extend(self._find_tests(path, pattern, namespace=True)) elif the_module.__name__ in sys.builtin_module_names: # builtin module raise TypeError('Can not use builtin modules ' 'as dotted module names') from None else: raise TypeError( 'don\'t know how to discover from {!r}' .format(the_module)) from None if set_implicit_top: if not is_namespace: self._top_level_dir = \ self._get_directory_containing_module(top_part) sys.path.remove(top_level_dir) else: sys.path.remove(top_level_dir) if is_not_importable: raise ImportError('Start directory is not importable: %r' % start_dir) if not is_namespace: tests = list(self._find_tests(start_dir, pattern)) return self.suiteClass(tests) def _get_directory_containing_module(self, module_name): module = sys.modules[module_name] full_path = os.path.abspath(module.__file__) if os.path.basename(full_path).lower().startswith('__init__.py'): return os.path.dirname(os.path.dirname(full_path)) else: # here we have been given a module rather than a package - so # all we can do is search the *same* directory the module is in # should an exception be raised instead return os.path.dirname(full_path) def _get_name_from_path(self, path): if path == self._top_level_dir: return '.' path = _jython_aware_splitext(os.path.normpath(path)) _relpath = os.path.relpath(path, self._top_level_dir) assert not os.path.isabs(_relpath), "Path must be within the project" assert not _relpath.startswith('..'), "Path must be within the project" name = _relpath.replace(os.path.sep, '.') return name def _get_module_from_name(self, name): __import__(name) return sys.modules[name] def _match_path(self, path, full_path, pattern): # override this method to use alternative matching strategy return fnmatch(path, pattern) def _find_tests(self, start_dir, pattern, namespace=False): """Used by discovery. Yields test suites it loads.""" # Handle the __init__ in this package name = self._get_name_from_path(start_dir) # name is '.' when start_dir == top_level_dir (and top_level_dir is by # definition not a package). if name != '.' and name not in self._loading_packages: # name is in self._loading_packages while we have called into # loadTestsFromModule with name. tests, should_recurse = self._find_test_path( start_dir, pattern, namespace) if tests is not None: yield tests if not should_recurse: # Either an error occurred, or load_tests was used by the # package. return # Handle the contents. paths = sorted(os.listdir(start_dir)) for path in paths: full_path = os.path.join(start_dir, path) tests, should_recurse = self._find_test_path( full_path, pattern, namespace) if tests is not None: yield tests if should_recurse: # we found a package that didn't use load_tests. name = self._get_name_from_path(full_path) self._loading_packages.add(name) try: yield from self._find_tests(full_path, pattern, namespace) finally: self._loading_packages.discard(name) def _find_test_path(self, full_path, pattern, namespace=False): """Used by discovery. Loads tests from a single file, or a directories' __init__.py when passed the directory. Returns a tuple (None_or_tests_from_file, should_recurse). """ basename = os.path.basename(full_path) if os.path.isfile(full_path): if not VALID_MODULE_NAME.match(basename): # valid Python identifiers only return None, False if not self._match_path(basename, full_path, pattern): return None, False # if the test file matches, load it name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) except case.SkipTest as e: return _make_skipped_test(name, e, self.suiteClass), False except: error_case, error_message = \ _make_failed_import_test(name, self.suiteClass) self.errors.append(error_message) return error_case, False else: mod_file = os.path.abspath( getattr(module, '__file__', full_path)) realpath = _jython_aware_splitext( os.path.realpath(mod_file)) fullpath_noext = _jython_aware_splitext( os.path.realpath(full_path)) if realpath.lower() != fullpath_noext.lower(): module_dir = os.path.dirname(realpath) mod_name = _jython_aware_splitext( os.path.basename(full_path)) 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)) return self.loadTestsFromModule(module, pattern=pattern), False elif os.path.isdir(full_path): if (not namespace and not os.path.isfile(os.path.join(full_path, '__init__.py'))): return None, False load_tests = None tests = None name = self._get_name_from_path(full_path) try: package = self._get_module_from_name(name) except case.SkipTest as e: return _make_skipped_test(name, e, self.suiteClass), False except: error_case, error_message = \ _make_failed_import_test(name, self.suiteClass) self.errors.append(error_message) return error_case, False else: load_tests = getattr(package, 'load_tests', None) # Mark this package as being in load_tests (possibly ;)) self._loading_packages.add(name) try: tests = self.loadTestsFromModule(package, pattern=pattern) if load_tests is not None: # loadTestsFromModule(package) has loaded tests for us. return tests, False return tests, True finally: self._loading_packages.discard(name) else: return None, False defaultTestLoader = TestLoader() def _makeLoader(prefix, sortUsing, suiteClass=None): loader = TestLoader() loader.sortTestMethodsUsing = sortUsing loader.testMethodPrefix = prefix if suiteClass: loader.suiteClass = suiteClass return loader def getTestCaseNames(testCaseClass, prefix, sortUsing=util.three_way_cmp): return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) def makeSuite(testCaseClass, prefix='test', sortUsing=util.three_way_cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase( testCaseClass) def findTestCases(module, prefix='test', sortUsing=util.three_way_cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(\ module)
22,410
511
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/runner.py
"""Running tests""" import sys import time import warnings from . import result from .signals import registerResult __unittest = True class _WritelnDecorator(object): """Used to decorate file-like objects with a handy 'writeln' method""" def __init__(self,stream): self.stream = stream def __getattr__(self, attr): if attr in ('stream', '__getstate__'): raise AttributeError(attr) return getattr(self.stream,attr) def writeln(self, arg=None): if arg: self.write(arg) self.write('\n') # text-mode streams translate to \r\n if needed class TextTestResult(result.TestResult): """A test result class that can print formatted text results to a stream. Used by TextTestRunner. """ separator1 = '=' * 70 separator2 = '-' * 70 def __init__(self, stream, descriptions, verbosity): super(TextTestResult, self).__init__(stream, descriptions, verbosity) self.stream = stream self.showAll = verbosity > 1 self.dots = verbosity == 1 self.descriptions = descriptions def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: return '\n'.join((str(test), doc_first_line)) else: return str(test) def startTest(self, test): super(TextTestResult, self).startTest(test) if self.showAll: self.stream.write(self.getDescription(test)) self.stream.write(" ... ") self.stream.flush() def addSuccess(self, test): super(TextTestResult, self).addSuccess(test) if self.showAll: self.stream.writeln("ok") elif self.dots: self.stream.write('.') self.stream.flush() def addError(self, test, err): super(TextTestResult, self).addError(test, err) if self.showAll: self.stream.writeln("ERROR") elif self.dots: self.stream.write('E') self.stream.flush() def addFailure(self, test, err): super(TextTestResult, self).addFailure(test, err) if self.showAll: self.stream.writeln("FAIL") elif self.dots: self.stream.write('F') self.stream.flush() def addSkip(self, test, reason): super(TextTestResult, self).addSkip(test, reason) if self.showAll: self.stream.writeln("skipped {0!r}".format(reason)) elif self.dots: self.stream.write("s") self.stream.flush() def addExpectedFailure(self, test, err): super(TextTestResult, self).addExpectedFailure(test, err) if self.showAll: self.stream.writeln("expected failure") elif self.dots: self.stream.write("x") self.stream.flush() def addUnexpectedSuccess(self, test): super(TextTestResult, self).addUnexpectedSuccess(test) if self.showAll: self.stream.writeln("unexpected success") elif self.dots: self.stream.write("u") self.stream.flush() def printErrors(self): if self.dots or self.showAll: self.stream.writeln() self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) def printErrorList(self, flavour, errors): for test, err in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln("%s" % err) class TextTestRunner(object): """A test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. """ resultclass = TextTestResult def __init__(self, stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False): """Construct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. """ if stream is None: stream = sys.stderr self.stream = _WritelnDecorator(stream) self.descriptions = descriptions self.verbosity = verbosity self.failfast = failfast self.buffer = buffer self.tb_locals = tb_locals self.warnings = warnings if resultclass is not None: self.resultclass = resultclass def _makeResult(self): return self.resultclass(self.stream, self.descriptions, self.verbosity) 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 result.tb_locals = self.tb_locals with warnings.catch_warnings(): if self.warnings: # if self.warnings is set, use it to filter all the warnings warnings.simplefilter(self.warnings) # if the filter is 'default' or 'always', special-case the # warnings from the deprecated unittest methods to show them # no more than once per module, because they can be fairly # noisy. The -Wd and -Wa flags can be used to bypass this # only when self.warnings is None. if self.warnings in ['default', 'always']: warnings.filterwarnings('module', category=DeprecationWarning, message=r'Please use assert\w+ instead.') 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 = len(result.failures), len(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
7,751
222
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/_main.py
"""Unittest main program""" import sys import argparse import os from . import loader, runner from .signals import installHandler __unittest = True MAIN_EXAMPLES = """\ Examples: %(prog)s test_module - run tests from test_module %(prog)s module.TestClass - run tests from module.TestClass %(prog)s module.Class.test_method - run specified test method %(prog)s path/to/test_file.py - run tests from test_file.py """ MODULE_EXAMPLES = """\ Examples: %(prog)s - run default set of tests %(prog)s MyTestSuite - run suite 'MyTestSuite' %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething %(prog)s MyTestCase - run all 'test*' test methods in MyTestCase """ def _convert_name(name): # on Linux / Mac OS X 'foo.PY' is not importable, but on # Windows it is. Simpler to do a case insensitive match # a better check would be to check that the name is a # valid Python module name. if os.path.isfile(name) and name.lower().endswith('.py'): if os.path.isabs(name): rel_path = os.path.relpath(name, os.getcwd()) if os.path.isabs(rel_path) or rel_path.startswith(os.pardir): return name name = rel_path # on Windows both '\' and '/' are used as path # separators. Better to replace both than rely on os.path.sep return name[:-3].replace('\\', '.').replace('/', '.') return name def _convert_names(names): return [_convert_name(name) for name in names] class TestProgram(object): """A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. """ # defaults for testing module=None verbosity = 1 failfast = catchbreak = buffer = progName = warnings = None _discovery_parser = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None, *, tb_locals=False): if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: self.module = getattr(self.module, part) else: self.module = module if argv is None: argv = sys.argv self.exit = exit self.failfast = failfast self.catchbreak = catchbreak self.verbosity = verbosity self.buffer = buffer self.tb_locals = tb_locals if warnings is None and not sys.warnoptions: # even if DeprecationWarnings are ignored by default # print them anyway unless other warnings settings are # specified by the warnings arg or the -W python flag self.warnings = 'default' else: # here self.warnings is set either to the value passed # to the warnings args or to None. # If the user didn't pass a value self.warnings will # be None. This means that the behavior is unchanged # and depends on the values passed to -W. self.warnings = warnings self.defaultTest = defaultTest self.testRunner = testRunner self.testLoader = testLoader self.progName = os.path.basename(argv[0]) self.parseArgs(argv) self.runTests() def usageExit(self, msg=None): if msg: print(msg) if self._discovery_parser is None: self._initArgParsers() self._print_help() sys.exit(2) def _print_help(self, *args, **kwargs): if self.module is None: print(self._main_parser.format_help()) print(MAIN_EXAMPLES % {'prog': self.progName}) self._discovery_parser.print_help() else: print(self._main_parser.format_help()) print(MODULE_EXAMPLES % {'prog': self.progName}) def parseArgs(self, argv): self._initArgParsers() if self.module is None: if len(argv) > 1 and argv[1].lower() == 'discover': self._do_discovery(argv[2:]) return self._main_parser.parse_args(argv[1:], self) if not self.tests: # this allows "python -m unittest -v" to still work for # test discovery. self._do_discovery([]) return else: self._main_parser.parse_args(argv[1:], self) if self.tests: self.testNames = _convert_names(self.tests) if __name__ == '__main__': # to support python -m unittest ... self.module = None elif self.defaultTest is None: # createTests will load tests from self.module self.testNames = None elif isinstance(self.defaultTest, str): self.testNames = (self.defaultTest,) else: self.testNames = list(self.defaultTest) self.createTests() def createTests(self): if self.testNames is None: self.test = self.testLoader.loadTestsFromModule(self.module) else: self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module) def _initArgParsers(self): parent_parser = self._getParentArgParser() self._main_parser = self._getMainArgParser(parent_parser) self._discovery_parser = self._getDiscoveryArgParser(parent_parser) def _getParentArgParser(self): parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-v', '--verbose', dest='verbosity', action='store_const', const=2, help='Verbose output') parser.add_argument('-q', '--quiet', dest='verbosity', action='store_const', const=0, help='Quiet output') parser.add_argument('--locals', dest='tb_locals', action='store_true', help='Show local variables in tracebacks') if self.failfast is None: parser.add_argument('-f', '--failfast', dest='failfast', action='store_true', help='Stop on first fail or error') self.failfast = False if self.catchbreak is None: parser.add_argument('-c', '--catch', dest='catchbreak', action='store_true', help='Catch Ctrl-C and display results so far') self.catchbreak = False if self.buffer is None: parser.add_argument('-b', '--buffer', dest='buffer', action='store_true', help='Buffer stdout and stderr during tests') self.buffer = False return parser def _getMainArgParser(self, parent): parser = argparse.ArgumentParser(parents=[parent]) parser.prog = self.progName parser.print_help = self._print_help parser.add_argument('tests', nargs='*', help='a list of any number of test modules, ' 'classes and test methods.') return parser def _getDiscoveryArgParser(self, parent): parser = argparse.ArgumentParser(parents=[parent]) parser.prog = '%s discover' % self.progName parser.epilog = ('For test discovery all test modules must be ' 'importable from the top level directory of the ' 'project.') parser.add_argument('-s', '--start-directory', dest='start', help="Directory to start discovery ('.' default)") parser.add_argument('-p', '--pattern', dest='pattern', help="Pattern to match tests ('test*.py' default)") parser.add_argument('-t', '--top-level-directory', dest='top', help='Top level directory of project (defaults to ' 'start directory)') for arg in ('start', 'pattern', 'top'): parser.add_argument(arg, nargs='?', default=argparse.SUPPRESS, help=argparse.SUPPRESS) return parser def _do_discovery(self, argv, Loader=None): self.start = '.' self.pattern = 'test*.py' self.top = None if argv is not None: # handle command line args for test discovery if self._discovery_parser is None: # for testing self._initArgParsers() self._discovery_parser.parse_args(argv, self) loader = self.testLoader if Loader is None else Loader() self.test = loader.discover(self.start, self.pattern, self.top) def runTests(self): if self.catchbreak: installHandler() if self.testRunner is None: self.testRunner = runner.TextTestRunner if isinstance(self.testRunner, type): try: try: testRunner = self.testRunner(verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer, warnings=self.warnings, tb_locals=self.tb_locals) except TypeError: # didn't accept the tb_locals argument testRunner = self.testRunner(verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer, warnings=self.warnings) except TypeError: # didn't accept the verbosity, buffer or failfast arguments testRunner = self.testRunner() else: # it is assumed to be a TestRunner instance testRunner = self.testRunner self.result = testRunner.run(self.test) if self.exit: sys.exit(not self.result.wasSuccessful()) main = TestProgram
10,552
261
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/__main__.py
"""Main entry point""" import sys if sys.argv[0].endswith("__main__.py"): import os.path # We change sys.argv[0] to make help message more useful # use executable without path, unquoted # (it's just a hint anyway) # (if you have spaces in your executable you get what you deserve!) executable = os.path.basename(sys.executable) sys.argv[0] = executable + " -m unittest" del os __unittest = True from ._main import main, TestProgram main(module=None)
486
19
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/mock.py
# mock.py # Test tools for mocking and patching. # Maintained by Michael Foord # Backport for other versions of Python available from # https://pypi.org/project/mock __all__ = ( 'Mock', 'MagicMock', 'patch', 'sentinel', 'DEFAULT', 'ANY', 'call', 'create_autospec', 'FILTER_DIR', 'NonCallableMock', 'NonCallableMagicMock', 'mock_open', 'PropertyMock', ) __version__ = '1.0' import inspect import pprint import sys import builtins from types import ModuleType from functools import wraps, partial _builtins = {name for name in dir(builtins) if not name.startswith('_')} BaseExceptions = (BaseException,) FILTER_DIR = True # Workaround for issue #12370 # Without this, the __class__ properties wouldn't be set correctly _safe_super = super def _is_instance_mock(obj): # can't use isinstance on Mock objects because they override __class__ # The base class for all mocks is NonCallableMock return issubclass(type(obj), NonCallableMock) def _is_exception(obj): return ( isinstance(obj, BaseExceptions) or isinstance(obj, type) and issubclass(obj, BaseExceptions) ) def _get_signature_object(func, as_instance, eat_self): """ Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. """ if isinstance(func, type) and not as_instance: # If it's a type and should be modelled as a type, use __init__. try: func = func.__init__ except AttributeError: return None # Skip the `self` argument in __init__ eat_self = True elif not isinstance(func, FunctionTypes): # If we really want to model an instance of the passed type, # __call__ should be looked up, not __init__. try: func = func.__call__ except AttributeError: return None if eat_self: sig_func = partial(func, None) else: sig_func = func try: return func, inspect.signature(sig_func) except ValueError: # Certain callable types are not supported by inspect.signature() return None def _check_signature(func, mock, skipfirst, instance=False): sig = _get_signature_object(func, instance, skipfirst) if sig is None: return func, sig = sig def checksig(_mock_self, *args, **kwargs): sig.bind(*args, **kwargs) _copy_func_details(func, checksig) type(mock)._mock_check_sig = checksig def _copy_func_details(func, funcopy): funcopy.__name__ = func.__name__ funcopy.__doc__ = func.__doc__ try: funcopy.__text_signature__ = func.__text_signature__ except AttributeError: pass # we explicitly don't copy func.__dict__ into this copy as it would # expose original attributes that should be mocked try: funcopy.__module__ = func.__module__ except AttributeError: pass try: funcopy.__defaults__ = func.__defaults__ except AttributeError: pass try: funcopy.__kwdefaults__ = func.__kwdefaults__ except AttributeError: pass def _callable(obj): if isinstance(obj, type): return True if getattr(obj, '__call__', None) is not None: return True return False def _is_list(obj): # checks for list or tuples # XXXX badly named! return type(obj) in (list, tuple) def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, type): # already an instance return getattr(obj, '__call__', None) is not None # *could* be broken by a class overriding __mro__ or __dict__ via # a metaclass for base in (obj,) + obj.__mro__: if base.__dict__.get('__call__') is not None: return True return False def _set_signature(mock, original, instance=False): # creates a function with signature (*args, **kwargs) that delegates to a # mock. It still does signature checking by calling a lambda with the same # signature as the original. if not _callable(original): return skipfirst = isinstance(original, type) result = _get_signature_object(original, instance, skipfirst) if result is None: return mock func, sig = result def checksig(*args, **kwargs): sig.bind(*args, **kwargs) _copy_func_details(func, checksig) name = original.__name__ if not name.isidentifier(): name = 'funcopy' context = {'_checksig_': checksig, 'mock': mock} src = """def %s(*args, **kwargs): _checksig_(*args, **kwargs) return mock(*args, **kwargs)""" % name exec (src, context) funcopy = context[name] _setup_func(funcopy, mock) return funcopy def _setup_func(funcopy, mock): funcopy.mock = mock # can't use isinstance with mocks if not _is_instance_mock(mock): return def assert_called_with(*args, **kwargs): return mock.assert_called_with(*args, **kwargs) def assert_called(*args, **kwargs): return mock.assert_called(*args, **kwargs) def assert_not_called(*args, **kwargs): return mock.assert_not_called(*args, **kwargs) def assert_called_once(*args, **kwargs): return mock.assert_called_once(*args, **kwargs) def assert_called_once_with(*args, **kwargs): return mock.assert_called_once_with(*args, **kwargs) def assert_has_calls(*args, **kwargs): return mock.assert_has_calls(*args, **kwargs) def assert_any_call(*args, **kwargs): return mock.assert_any_call(*args, **kwargs) def reset_mock(): funcopy.method_calls = _CallList() funcopy.mock_calls = _CallList() mock.reset_mock() ret = funcopy.return_value if _is_instance_mock(ret) and not ret is mock: ret.reset_mock() funcopy.called = False funcopy.call_count = 0 funcopy.call_args = None funcopy.call_args_list = _CallList() funcopy.method_calls = _CallList() funcopy.mock_calls = _CallList() funcopy.return_value = mock.return_value funcopy.side_effect = mock.side_effect funcopy._mock_children = mock._mock_children funcopy.assert_called_with = assert_called_with funcopy.assert_called_once_with = assert_called_once_with funcopy.assert_has_calls = assert_has_calls funcopy.assert_any_call = assert_any_call funcopy.reset_mock = reset_mock funcopy.assert_called = assert_called funcopy.assert_not_called = assert_not_called funcopy.assert_called_once = assert_called_once mock._mock_delegate = funcopy def _is_magic(name): return '__%s__' % name[2:-2] == name class _SentinelObject(object): "A unique, named, sentinel object." def __init__(self, name): self.name = name def __repr__(self): return 'sentinel.%s' % self.name class _Sentinel(object): """Access attributes to return a named object, usable as a sentinel.""" def __init__(self): self._sentinels = {} def __getattr__(self, name): if name == '__bases__': # Without this help(unittest.mock) raises an exception raise AttributeError return self._sentinels.setdefault(name, _SentinelObject(name)) sentinel = _Sentinel() DEFAULT = sentinel.DEFAULT _missing = sentinel.MISSING _deleted = sentinel.DELETED def _copy(value): if type(value) in (dict, list, tuple, set): return type(value)(value) return value _allowed_names = { 'return_value', '_mock_return_value', 'side_effect', '_mock_side_effect', '_mock_parent', '_mock_new_parent', '_mock_name', '_mock_new_name' } def _delegating_property(name): _allowed_names.add(name) _the_name = '_mock_' + name def _get(self, name=name, _the_name=_the_name): sig = self._mock_delegate if sig is None: return getattr(self, _the_name) return getattr(sig, name) def _set(self, value, name=name, _the_name=_the_name): sig = self._mock_delegate if sig is None: self.__dict__[_the_name] = value else: setattr(sig, name, value) return property(_get, _set) class _CallList(list): def __contains__(self, value): if not isinstance(value, list): return list.__contains__(self, value) len_value = len(value) len_self = len(self) if len_value > len_self: return False for i in range(0, len_self - len_value + 1): sub_list = self[i:i+len_value] if sub_list == value: return True return False def __repr__(self): return pprint.pformat(list(self)) def _check_and_set_parent(parent, value, name, new_name): if not _is_instance_mock(value): return False if ((value._mock_name or value._mock_new_name) or (value._mock_parent is not None) or (value._mock_new_parent is not None)): return False _parent = parent while _parent is not None: # setting a mock (value) as a child or return value of itself # should not modify the mock if _parent is value: return False _parent = _parent._mock_new_parent if new_name: value._mock_new_parent = parent value._mock_new_name = new_name if name: value._mock_parent = parent value._mock_name = name return True # Internal class to identify if we wrapped an iterator object or not. class _MockIter(object): def __init__(self, obj): self.obj = iter(obj) def __iter__(self): return self def __next__(self): return next(self.obj) class Base(object): _mock_return_value = DEFAULT _mock_side_effect = None def __init__(self, *args, **kwargs): pass class NonCallableMock(Base): """A non-callable version of `Mock`""" def __new__(cls, *args, **kw): # every instance has its own class # so we can create magic methods on the # class without stomping on other mocks new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) instance = object.__new__(new) return instance def __init__( self, spec=None, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs ): if _new_parent is None: _new_parent = parent __dict__ = self.__dict__ __dict__['_mock_parent'] = parent __dict__['_mock_name'] = name __dict__['_mock_new_name'] = _new_name __dict__['_mock_new_parent'] = _new_parent if spec_set is not None: spec = spec_set spec_set = True if _eat_self is None: _eat_self = parent is not None self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self) __dict__['_mock_children'] = {} __dict__['_mock_wraps'] = wraps __dict__['_mock_delegate'] = None __dict__['_mock_called'] = False __dict__['_mock_call_args'] = None __dict__['_mock_call_count'] = 0 __dict__['_mock_call_args_list'] = _CallList() __dict__['_mock_mock_calls'] = _CallList() __dict__['method_calls'] = _CallList() __dict__['_mock_unsafe'] = unsafe if kwargs: self.configure_mock(**kwargs) _safe_super(NonCallableMock, self).__init__( spec, wraps, name, spec_set, parent, _spec_state ) def attach_mock(self, mock, attribute): """ Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.""" mock._mock_parent = None mock._mock_new_parent = None mock._mock_name = '' mock._mock_new_name = None setattr(self, attribute, mock) def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False, _eat_self=False): _spec_class = None _spec_signature = None if spec is not None and not _is_list(spec): if isinstance(spec, type): _spec_class = spec else: _spec_class = _get_class(spec) res = _get_signature_object(spec, _spec_as_instance, _eat_self) _spec_signature = res and res[1] spec = dir(spec) __dict__ = self.__dict__ __dict__['_spec_class'] = _spec_class __dict__['_spec_set'] = spec_set __dict__['_spec_signature'] = _spec_signature __dict__['_mock_methods'] = spec def __get_return_value(self): ret = self._mock_return_value if self._mock_delegate is not None: ret = self._mock_delegate.return_value if ret is DEFAULT: ret = self._get_child_mock( _new_parent=self, _new_name='()' ) self.return_value = ret return ret def __set_return_value(self, value): if self._mock_delegate is not None: self._mock_delegate.return_value = value else: self._mock_return_value = value _check_and_set_parent(self, value, None, '()') __return_value_doc = "The value to be returned when the mock is called." return_value = property(__get_return_value, __set_return_value, __return_value_doc) @property def __class__(self): if self._spec_class is None: return type(self) return self._spec_class called = _delegating_property('called') call_count = _delegating_property('call_count') call_args = _delegating_property('call_args') call_args_list = _delegating_property('call_args_list') mock_calls = _delegating_property('mock_calls') def __get_side_effect(self): delegated = self._mock_delegate if delegated is None: return self._mock_side_effect sf = delegated.side_effect if (sf is not None and not callable(sf) and not isinstance(sf, _MockIter) and not _is_exception(sf)): sf = _MockIter(sf) delegated.side_effect = sf return sf def __set_side_effect(self, value): value = _try_iter(value) delegated = self._mock_delegate if delegated is None: self._mock_side_effect = value else: delegated.side_effect = value side_effect = property(__get_side_effect, __set_side_effect) def reset_mock(self, visited=None,*, return_value=False, side_effect=False): "Restore the mock object to its initial state." if visited is None: visited = [] if id(self) in visited: return visited.append(id(self)) self.called = False self.call_args = None self.call_count = 0 self.mock_calls = _CallList() self.call_args_list = _CallList() self.method_calls = _CallList() if return_value: self._mock_return_value = DEFAULT if side_effect: self._mock_side_effect = None for child in self._mock_children.values(): if isinstance(child, _SpecState) or child is _deleted: continue child.reset_mock(visited) ret = self._mock_return_value if _is_instance_mock(ret) and ret is not self: ret.reset_mock(visited) def configure_mock(self, **kwargs): """Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)""" for arg, val in sorted(kwargs.items(), # we sort on the number of dots so that # attributes are set before we set attributes on # attributes key=lambda entry: entry[0].count('.')): args = arg.split('.') final = args.pop() obj = self for entry in args: obj = getattr(obj, entry) setattr(obj, final, val) def __getattr__(self, name): if name in {'_mock_methods', '_mock_unsafe'}: raise AttributeError(name) elif self._mock_methods is not None: if name not in self._mock_methods or name in _all_magics: raise AttributeError("Mock object has no attribute %r" % name) elif _is_magic(name): raise AttributeError(name) if not self._mock_unsafe: if name.startswith(('assert', 'assret')): raise AttributeError(name) result = self._mock_children.get(name) if result is _deleted: raise AttributeError(name) elif result is None: wraps = None if self._mock_wraps is not None: # XXXX should we get the attribute without triggering code # execution? wraps = getattr(self._mock_wraps, name) result = self._get_child_mock( parent=self, name=name, wraps=wraps, _new_name=name, _new_parent=self ) self._mock_children[name] = result elif isinstance(result, _SpecState): result = create_autospec( result.spec, result.spec_set, result.instance, result.parent, result.name ) self._mock_children[name] = result return result def __repr__(self): _name_list = [self._mock_new_name] _parent = self._mock_new_parent last = self dot = '.' if _name_list == ['()']: dot = '' seen = set() while _parent is not None: last = _parent _name_list.append(_parent._mock_new_name + dot) dot = '.' if _parent._mock_new_name == '()': dot = '' _parent = _parent._mock_new_parent # use ids here so as not to call __hash__ on the mocks if id(_parent) in seen: break seen.add(id(_parent)) _name_list = list(reversed(_name_list)) _first = last._mock_name or 'mock' if len(_name_list) > 1: if _name_list[1] not in ('()', '().'): _first += '.' _name_list[0] = _first name = ''.join(_name_list) name_string = '' if name not in ('mock', 'mock.'): name_string = ' name=%r' % name spec_string = '' if self._spec_class is not None: spec_string = ' spec=%r' if self._spec_set: spec_string = ' spec_set=%r' spec_string = spec_string % self._spec_class.__name__ return "<%s%s%s id='%s'>" % ( type(self).__name__, name_string, spec_string, id(self) ) def __dir__(self): """Filter the output of `dir(mock)` to only useful members.""" if not FILTER_DIR: return object.__dir__(self) extras = self._mock_methods or [] from_type = dir(type(self)) from_dict = list(self.__dict__) from_type = [e for e in from_type if not e.startswith('_')] from_dict = [e for e in from_dict if not e.startswith('_') or _is_magic(e)] return sorted(set(extras + from_type + from_dict + list(self._mock_children))) def __setattr__(self, name, value): if name in _allowed_names: # property setters go through here return object.__setattr__(self, name, value) elif (self._spec_set and self._mock_methods is not None and name not in self._mock_methods and name not in self.__dict__): raise AttributeError("Mock object has no attribute '%s'" % name) elif name in _unsupported_magics: msg = 'Attempting to set unsupported magic method %r.' % name raise AttributeError(msg) elif name in _all_magics: if self._mock_methods is not None and name not in self._mock_methods: raise AttributeError("Mock object has no attribute '%s'" % name) if not _is_instance_mock(value): setattr(type(self), name, _get_method(name, value)) original = value value = lambda *args, **kw: original(self, *args, **kw) else: # only set _new_name and not name so that mock_calls is tracked # but not method calls _check_and_set_parent(self, value, None, name) setattr(type(self), name, value) self._mock_children[name] = value elif name == '__class__': self._spec_class = value return else: if _check_and_set_parent(self, value, name, name): self._mock_children[name] = value return object.__setattr__(self, name, value) def __delattr__(self, name): if name in _all_magics and name in type(self).__dict__: delattr(type(self), name) if name not in self.__dict__: # for magic methods that are still MagicProxy objects and # not set on the instance itself return if name in self.__dict__: object.__delattr__(self, name) obj = self._mock_children.get(name, _missing) if obj is _deleted: raise AttributeError(name) if obj is not _missing: del self._mock_children[name] self._mock_children[name] = _deleted def _format_mock_call_signature(self, args, kwargs): name = self._mock_name or 'mock' return _format_call_signature(name, args, kwargs) def _format_mock_failure_message(self, args, kwargs): message = 'Expected call: %s\nActual call: %s' expected_string = self._format_mock_call_signature(args, kwargs) call_args = self.call_args if len(call_args) == 3: call_args = call_args[1:] actual_string = self._format_mock_call_signature(*call_args) return message % (expected_string, actual_string) def _call_matcher(self, _call): """ Given a call (or simply an (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec's signature, if available, or falls back on the arguments themselves. """ sig = self._spec_signature if sig is not None: if len(_call) == 2: name = '' args, kwargs = _call else: name, args, kwargs = _call try: return name, sig.bind(*args, **kwargs) except TypeError as e: return e.with_traceback(None) else: return _call def assert_not_called(_mock_self): """assert that the mock was never called. """ self = _mock_self if self.call_count != 0: msg = ("Expected '%s' to not have been called. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) def assert_called(_mock_self): """assert that the mock was called at least once """ self = _mock_self if self.call_count == 0: msg = ("Expected '%s' to have been called." % self._mock_name or 'mock') raise AssertionError(msg) def assert_called_once(_mock_self): """assert that the mock was called only once. """ self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to have been called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: expected = self._format_mock_call_signature(args, kwargs) raise AssertionError('Expected call: %s\nNot called' % (expected,)) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if expected != actual: cause = expected if isinstance(expected, Exception) else None raise AssertionError(_error_message()) from cause def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and that that call was with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self._mock_name or 'mock', self.call_count)) raise AssertionError(msg) return self.assert_called_with(*args, **kwargs) def assert_has_calls(self, calls, any_order=False): """assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls can be in any order, but they must all appear in `mock_calls`.""" expected = [self._call_matcher(c) for c in calls] cause = expected if isinstance(expected, Exception) else None all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls) if not any_order: if expected not in all_calls: raise AssertionError( 'Calls not found.\nExpected: %r\n' 'Actual: %r' % (_CallList(calls), self.mock_calls) ) from cause return all_calls = list(all_calls) not_found = [] for kall in expected: try: all_calls.remove(kall) except ValueError: not_found.append(kall) if not_found: raise AssertionError( '%r not all found in call list' % (tuple(not_found),) ) from cause def assert_any_call(self, *args, **kwargs): """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.""" expected = self._call_matcher((args, kwargs)) actual = [self._call_matcher(c) for c in self.call_args_list] if expected not in actual: cause = expected if isinstance(expected, Exception) else None expected_string = self._format_mock_call_signature(args, kwargs) raise AssertionError( '%s call not found' % expected_string ) from cause def _get_child_mock(self, **kw): """Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).""" _type = type(self) if not issubclass(_type, CallableMixin): if issubclass(_type, NonCallableMagicMock): klass = MagicMock elif issubclass(_type, NonCallableMock) : klass = Mock else: klass = _type.__mro__[1] return klass(**kw) def _try_iter(obj): if obj is None: return obj if _is_exception(obj): return obj if _callable(obj): return obj try: return iter(obj) except TypeError: # XXXX backwards compatibility # but this will blow up on first call - so maybe we should fail early? return obj class CallableMixin(Base): def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, **kwargs): self.__dict__['_mock_return_value'] = return_value _safe_super(CallableMixin, self).__init__( spec, wraps, name, spec_set, parent, _spec_state, _new_name, _new_parent, **kwargs ) self.side_effect = side_effect def _mock_check_sig(self, *args, **kwargs): # stub method that can be replaced with one with a specific signature pass def __call__(_mock_self, *args, **kwargs): # can't use self in-case a function / method we are mocking uses self # in the signature _mock_self._mock_check_sig(*args, **kwargs) return _mock_self._mock_call(*args, **kwargs) def _mock_call(_mock_self, *args, **kwargs): self = _mock_self self.called = True self.call_count += 1 # handle call_args _call = _Call((args, kwargs), two=True) self.call_args = _call self.call_args_list.append(_call) seen = set() # initial stuff for method_calls: do_method_calls = self._mock_parent is not None method_call_name = self._mock_name # initial stuff for mock_calls: mock_call_name = self._mock_new_name is_a_call = mock_call_name == '()' self.mock_calls.append(_Call(('', args, kwargs))) # follow up the chain of mocks: _new_parent = self._mock_new_parent while _new_parent is not None: # handle method_calls: if do_method_calls: _new_parent.method_calls.append(_Call((method_call_name, args, kwargs))) do_method_calls = _new_parent._mock_parent is not None if do_method_calls: method_call_name = _new_parent._mock_name + '.' + method_call_name # handle mock_calls: this_mock_call = _Call((mock_call_name, args, kwargs)) _new_parent.mock_calls.append(this_mock_call) if _new_parent._mock_new_name: if is_a_call: dot = '' else: dot = '.' is_a_call = _new_parent._mock_new_name == '()' mock_call_name = _new_parent._mock_new_name + dot + mock_call_name # follow the parental chain: _new_parent = _new_parent._mock_new_parent # check we're not in an infinite loop: # ( use ids here so as not to call __hash__ on the mocks) _new_parent_id = id(_new_parent) if _new_parent_id in seen: break seen.add(_new_parent_id) effect = self.side_effect if effect is not None: if _is_exception(effect): raise effect elif not _callable(effect): result = next(effect) if _is_exception(result): raise result else: result = effect(*args, **kwargs) if result is not DEFAULT: return result if self._mock_return_value is not DEFAULT: return self.return_value if self._mock_wraps is not None: return self._mock_wraps(*args, **kwargs) return self.return_value class Mock(CallableMixin, NonCallableMock): """ Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an `AttributeError`. If `spec` is an object (rather than a list of strings) then `mock.__class__` returns the class of the spec object. This allows mocks to pass `isinstance` tests. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* or get an attribute on the mock that isn't on the object passed as `spec_set` will raise an `AttributeError`. * `side_effect`: A function to be called whenever the Mock is called. See the `side_effect` attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns `DEFAULT`, the return value of this function is used as the return value. If `side_effect` is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned. * `return_value`: The value returned when the mock is called. By default this is a new Mock (created on first access). See the `return_value` attribute. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn't exist will raise an `AttributeError`). If the mock has an explicit `return_value` set then calls are not passed to the wrapped object and the `return_value` is returned instead. * `name`: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks. Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. """ def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: __import__(import_path) return getattr(thing, comp) def _importer(target): components = target.split('.') import_path = components.pop(0) thing = __import__(import_path) for comp in components: import_path += ".%s" % comp thing = _dot_lookup(thing, comp, import_path) return thing def _is_started(patcher): # XXXX horrible return hasattr(patcher, 'is_local') class _patch(object): attribute_name = None _active_patches = [] def __init__( self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ): if new_callable is not None: if new is not DEFAULT: raise ValueError( "Cannot use 'new' and 'new_callable' together" ) if autospec is not None: raise ValueError( "Cannot use 'autospec' and 'new_callable' together" ) self.getter = getter self.attribute = attribute self.new = new self.new_callable = new_callable self.spec = spec self.create = create self.has_local = False self.spec_set = spec_set self.autospec = autospec self.kwargs = kwargs self.additional_patchers = [] def copy(self): patcher = _patch( self.getter, self.attribute, self.new, self.spec, self.create, self.spec_set, self.autospec, self.new_callable, self.kwargs ) patcher.attribute_name = self.attribute_name patcher.additional_patchers = [ p.copy() for p in self.additional_patchers ] return patcher def __call__(self, func): if isinstance(func, type): return self.decorate_class(func) return self.decorate_callable(func) def decorate_class(self, klass): for attr in dir(klass): if not attr.startswith(patch.TEST_PREFIX): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue patcher = self.copy() setattr(klass, attr, patcher(attr_value)) return klass def decorate_callable(self, func): if hasattr(func, 'patchings'): func.patchings.append(self) return func @wraps(func) def patched(*args, **keywargs): extra_args = [] entered_patchers = [] exc_info = tuple() try: for patching in patched.patchings: arg = patching.__enter__() entered_patchers.append(patching) if patching.attribute_name is not None: keywargs.update(arg) elif patching.new is DEFAULT: extra_args.append(arg) args += tuple(extra_args) return func(*args, **keywargs) except: if (patching not in entered_patchers and _is_started(patching)): # the patcher may have been started, but an exception # raised whilst entering one of its additional_patchers entered_patchers.append(patching) # Pass the exception to __exit__ exc_info = sys.exc_info() # re-raise the exception raise finally: for patching in reversed(entered_patchers): patching.__exit__(*exc_info) patched.patchings = [self] return patched def get_original(self): target = self.getter() name = self.attribute original = DEFAULT local = False try: original = target.__dict__[name] except (AttributeError, KeyError): original = getattr(target, name, DEFAULT) else: local = True if name in _builtins and isinstance(target, ModuleType): self.create = True if not self.create and original is DEFAULT: raise AttributeError( "%s does not have the attribute %r" % (target, name) ) return original, local def __enter__(self): """Perform the patch.""" new, spec, spec_set = self.new, self.spec, self.spec_set autospec, kwargs = self.autospec, self.kwargs new_callable = self.new_callable self.target = self.getter() # normalise False to None if spec is False: spec = None if spec_set is False: spec_set = None if autospec is False: autospec = None if spec is not None and autospec is not None: raise TypeError("Can't specify spec and autospec") if ((spec is not None or autospec is not None) and spec_set not in (True, None)): raise TypeError("Can't provide explicit spec_set *and* spec or autospec") original, local = self.get_original() if new is DEFAULT and autospec is None: inherit = False if spec is True: # set spec to the object we are replacing spec = original if spec_set is True: spec_set = original spec = None elif spec is not None: if spec_set is True: spec_set = spec spec = None elif spec_set is True: spec_set = original if spec is not None or spec_set is not None: if original is DEFAULT: raise TypeError("Can't use 'spec' with create=True") if isinstance(original, type): # If we're patching out a class and there is a spec inherit = True Klass = MagicMock _kwargs = {} if new_callable is not None: Klass = new_callable elif spec is not None or spec_set is not None: this_spec = spec if spec_set is not None: this_spec = spec_set if _is_list(this_spec): not_callable = '__call__' not in this_spec else: not_callable = not callable(this_spec) if not_callable: Klass = NonCallableMagicMock if spec is not None: _kwargs['spec'] = spec if spec_set is not None: _kwargs['spec_set'] = spec_set # add a name to mocks if (isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute): _kwargs['name'] = self.attribute _kwargs.update(kwargs) new = Klass(**_kwargs) if inherit and _is_instance_mock(new): # we can only tell if the instance should be callable if the # spec is not a list this_spec = spec if spec_set is not None: this_spec = spec_set if (not _is_list(this_spec) and not _instance_callable(this_spec)): Klass = NonCallableMagicMock _kwargs.pop('name') new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs) elif autospec is not None: # spec is ignored, new *must* be default, spec_set is treated # as a boolean. Should we check spec is not None and that spec_set # is a bool? if new is not DEFAULT: raise TypeError( "autospec creates the mock for you. Can't specify " "autospec and new." ) if original is DEFAULT: raise TypeError("Can't use 'autospec' with create=True") spec_set = bool(spec_set) if autospec is True: autospec = original new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs) elif kwargs: # can't set keyword args when we aren't creating the mock # XXXX If new is a Mock we could call new.configure_mock(**kwargs) raise TypeError("Can't pass kwargs to a mock we aren't creating") new_attr = new self.temp_original = original self.is_local = local setattr(self.target, self.attribute, new_attr) if self.attribute_name is not None: extra_args = {} if self.new is DEFAULT: extra_args[self.attribute_name] = new for patching in self.additional_patchers: arg = patching.__enter__() if patching.new is DEFAULT: extra_args.update(arg) return extra_args return new def __exit__(self, *exc_info): """Undo the patch.""" if not _is_started(self): raise RuntimeError('stop called on unstarted patcher') if self.is_local and self.temp_original is not DEFAULT: setattr(self.target, self.attribute, self.temp_original) else: delattr(self.target, self.attribute) if not self.create and (not hasattr(self.target, self.attribute) or self.attribute in ('__doc__', '__module__', '__defaults__', '__annotations__', '__kwdefaults__')): # needed for proxy objects like django settings setattr(self.target, self.attribute, self.temp_original) del self.temp_original del self.is_local del self.target for patcher in reversed(self.additional_patchers): if _is_started(patcher): patcher.__exit__(*exc_info) def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.append(self) return result def stop(self): """Stop an active patch.""" try: self._active_patches.remove(self) except ValueError: # If the patch hasn't been started this will fail pass return self.__exit__() def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError): raise TypeError("Need a valid target to patch. You supplied: %r" % (target,)) getter = lambda: _importer(target) return getter, attribute def _patch_object( target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs ): """ patch the named member (`attribute`) on an object (`target`) with a mock object. `patch.object` can be used as a decorator, class decorator or a context manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and `new_callable` have the same meaning as for `patch`. Like `patch`, `patch.object` takes arbitrary keyword arguments for configuring the mock object it creates. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ getter = lambda: target return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ) def _patch_multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs): """Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ if type(target) is str: getter = lambda: _importer(target) else: getter = lambda: target if not kwargs: raise ValueError( 'Must supply at least one keyword argument with patch.multiple' ) # need to wrap in a list for python 3, where items is a view items = list(kwargs.items()) attribute, new = items[0] patcher = _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, {} ) patcher.attribute_name = attribute for attribute, new in items[1:]: this_patcher = _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, {} ) this_patcher.attribute_name = attribute patcher.additional_patchers.append(this_patcher) return patcher def patch( target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs ): """ `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with a `MagicMock`. If `patch` is used as a decorator and `new` is omitted, the created mock is passed in as an extra argument to the decorated function. If `patch` is used as a context manager the created mock is returned by the context manager. `target` should be a string in the form `'package.module.ClassName'`. The `target` is imported and the specified object replaced with the `new` object, so the `target` must be importable from the environment you are calling `patch` from. The target is imported when the decorated function is executed, not at decoration time. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` if patch is creating one for you. In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec_set object. `new_callable` allows you to specify a different class, or callable object, that will be called to create the `new` object. By default `MagicMock` is used. A more powerful form of `spec` is `autospec`. If you set `autospec=True` then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a `TypeError` if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced. By default `patch` will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist! Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. `patch` finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if `patch` is creating a mock object for you. `patch` takes arbitrary keyword arguments. These will be passed to the `Mock` (or `new_callable`) on construction. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. """ getter, attribute = _get_target(target) return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ) class _patch_dict(object): """ Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test. `in_dict` can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys. `in_dict` can also be a string specifying the name of the dictionary, which will then be fetched by importing it. `values` can be a dictionary of values to set in the dictionary. `values` can also be an iterable of `(key, value)` pairs. If `clear` is True then the dictionary will be cleared before the new values are set. `patch.dict` can also be called with arbitrary keyword arguments to set values in the dictionary:: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): ... `patch.dict` can be used as a context manager, decorator or class decorator. When used as a class decorator `patch.dict` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ def __init__(self, in_dict, values=(), clear=False, **kwargs): if isinstance(in_dict, str): in_dict = _importer(in_dict) self.in_dict = in_dict # support any argument supported by dict(...) constructor self.values = dict(values) self.values.update(kwargs) self.clear = clear self._original = None def __call__(self, f): if isinstance(f, type): return self.decorate_class(f) @wraps(f) def _inner(*args, **kw): self._patch_dict() try: return f(*args, **kw) finally: self._unpatch_dict() return _inner def decorate_class(self, klass): for attr in dir(klass): attr_value = getattr(klass, attr) if (attr.startswith(patch.TEST_PREFIX) and hasattr(attr_value, "__call__")): decorator = _patch_dict(self.in_dict, self.values, self.clear) decorated = decorator(attr_value) setattr(klass, attr, decorated) return klass def __enter__(self): """Patch the dict.""" self._patch_dict() def _patch_dict(self): values = self.values in_dict = self.in_dict clear = self.clear try: original = in_dict.copy() except AttributeError: # dict like object with no copy method # must support iteration over keys original = {} for key in in_dict: original[key] = in_dict[key] self._original = original if clear: _clear_dict(in_dict) try: in_dict.update(values) except AttributeError: # dict like object with no update method for key in values: in_dict[key] = values[key] def _unpatch_dict(self): in_dict = self.in_dict original = self._original _clear_dict(in_dict) try: in_dict.update(original) except AttributeError: for key in original: in_dict[key] = original[key] def __exit__(self, *args): """Unpatch the dict.""" self._unpatch_dict() return False start = __enter__ stop = __exit__ def _clear_dict(in_dict): try: in_dict.clear() except AttributeError: keys = list(in_dict) for key in keys: del in_dict[key] def _patch_stopall(): """Stop all active patches. LIFO to unroll nested patches.""" for patch in reversed(_patch._active_patches): patch.stop() patch.object = _patch_object patch.dict = _patch_dict patch.multiple = _patch_multiple patch.stopall = _patch_stopall patch.TEST_PREFIX = 'test' magic_methods = ( "lt le gt ge eq ne " "getitem setitem delitem " "len contains iter " "hash str sizeof " "enter exit " # we added divmod and rdivmod here instead of numerics # because there is no idivmod "divmod rdivmod neg pos abs invert " "complex int float index " "trunc floor ceil " "bool next " ) numerics = ( "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv" ) inplace = ' '.join('i%s' % n for n in numerics.split()) right = ' '.join('r%s' % n for n in numerics.split()) # not including __prepare__, __instancecheck__, __subclasscheck__ # (as they are metaclass methods) # __del__ is not supported at all as it causes problems if it exists _non_defaults = { '__get__', '__set__', '__delete__', '__reversed__', '__missing__', '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__', '__getstate__', '__setstate__', '__getformat__', '__setformat__', '__repr__', '__dir__', '__subclasses__', '__format__', '__getnewargs_ex__', } def _get_method(name, func): "Turns a callable object (like a mock) into a real function" def method(self, *args, **kw): return func(self, *args, **kw) method.__name__ = name return method _magics = { '__%s__' % method for method in ' '.join([magic_methods, numerics, inplace, right]).split() } _all_magics = _magics | _non_defaults _unsupported_magics = { '__getattr__', '__setattr__', '__init__', '__new__', '__prepare__', '__instancecheck__', '__subclasscheck__', '__del__' } _calculate_return_value = { '__hash__': lambda self: object.__hash__(self), '__str__': lambda self: object.__str__(self), '__sizeof__': lambda self: object.__sizeof__(self), } _return_values = { '__lt__': NotImplemented, '__gt__': NotImplemented, '__le__': NotImplemented, '__ge__': NotImplemented, '__int__': 1, '__contains__': False, '__len__': 0, '__exit__': False, '__complex__': 1j, '__float__': 1.0, '__bool__': True, '__index__': 1, } def _get_eq(self): def __eq__(other): ret_val = self.__eq__._mock_return_value if ret_val is not DEFAULT: return ret_val if self is other: return True return NotImplemented return __eq__ def _get_ne(self): def __ne__(other): if self.__ne__._mock_return_value is not DEFAULT: return DEFAULT if self is other: return False return NotImplemented return __ne__ def _get_iter(self): def __iter__(): ret_val = self.__iter__._mock_return_value if ret_val is DEFAULT: return iter([]) # if ret_val was already an iterator, then calling iter on it should # return the iterator unchanged return iter(ret_val) return __iter__ _side_effect_methods = { '__eq__': _get_eq, '__ne__': _get_ne, '__iter__': _get_iter, } def _set_return_value(mock, method, name): fixed = _return_values.get(name, DEFAULT) if fixed is not DEFAULT: method.return_value = fixed return return_calulator = _calculate_return_value.get(name) if return_calulator is not None: try: return_value = return_calulator(mock) except AttributeError: # XXXX why do we return AttributeError here? # set it as a side_effect instead? return_value = AttributeError(name) method.return_value = return_value return side_effector = _side_effect_methods.get(name) if side_effector is not None: method.side_effect = side_effector(mock) class MagicMixin(object): def __init__(self, *args, **kw): self._mock_set_magics() # make magic work for kwargs in init _safe_super(MagicMixin, self).__init__(*args, **kw) self._mock_set_magics() # fix magic broken by upper level init def _mock_set_magics(self): these_magics = _magics if getattr(self, "_mock_methods", None) is not None: these_magics = _magics.intersection(self._mock_methods) remove_magics = set() remove_magics = _magics - these_magics for entry in remove_magics: if entry in type(self).__dict__: # remove unneeded magic methods delattr(self, entry) # don't overwrite existing attributes if called a second time these_magics = these_magics - set(type(self).__dict__) _type = type(self) for entry in these_magics: setattr(_type, entry, MagicProxy(entry, self)) class NonCallableMagicMock(MagicMixin, NonCallableMock): """A version of `MagicMock` that isn't callable.""" def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics() class MagicMock(MagicMixin, Mock): """ MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the spec will be created. Attributes and the return value of a `MagicMock` will also be `MagicMocks`. """ def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics() class MagicProxy(object): def __init__(self, name, parent): self.name = name self.parent = parent def __call__(self, *args, **kwargs): m = self.create_mock() return m(*args, **kwargs) def create_mock(self): entry = self.name parent = self.parent m = parent._get_child_mock(name=entry, _new_name=entry, _new_parent=parent) setattr(parent, entry, m) _set_return_value(parent, m, entry) return m def __get__(self, obj, _type=None): return self.create_mock() class _ANY(object): "A helper object that compares equal to everything." def __eq__(self, other): return True def __ne__(self, other): return False def __repr__(self): return '<ANY>' ANY = _ANY() def _format_call_signature(name, args, kwargs): message = '%s(%%s)' % name formatted_args = '' args_string = ', '.join([repr(arg) for arg in args]) kwargs_string = ', '.join([ '%s=%r' % (key, value) for key, value in sorted(kwargs.items()) ]) if args_string: formatted_args = args_string if kwargs_string: if formatted_args: formatted_args += ', ' formatted_args += kwargs_string return message % formatted_args class _Call(tuple): """ A tuple for holding the results of a call to a mock, either in the form `(args, kwargs)` or `(name, args, kwargs)`. If args or kwargs are empty then a call tuple will compare equal to a tuple without those values. This makes comparisons less verbose:: _Call(('name', (), {})) == ('name',) _Call(('name', (1,), {})) == ('name', (1,)) _Call(((), {'a': 'b'})) == ({'a': 'b'},) The `_Call` object provides a useful shortcut for comparing with call:: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) If the _Call has no name then it will match any name. """ def __new__(cls, value=(), name='', parent=None, two=False, from_kall=True): args = () kwargs = {} _len = len(value) if _len == 3: name, args, kwargs = value elif _len == 2: first, second = value if isinstance(first, str): name = first if isinstance(second, tuple): args = second else: kwargs = second else: args, kwargs = first, second elif _len == 1: value, = value if isinstance(value, str): name = value elif isinstance(value, tuple): args = value else: kwargs = value if two: return tuple.__new__(cls, (args, kwargs)) return tuple.__new__(cls, (name, args, kwargs)) def __init__(self, value=(), name=None, parent=None, two=False, from_kall=True): self._mock_name = name self._mock_parent = parent self._mock_from_kall = from_kall def __eq__(self, other): if other is ANY: return True try: len_other = len(other) except TypeError: return False self_name = '' if len(self) == 2: self_args, self_kwargs = self else: self_name, self_args, self_kwargs = self if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None) and self._mock_parent != other._mock_parent): return False other_name = '' if len_other == 0: other_args, other_kwargs = (), {} elif len_other == 3: other_name, other_args, other_kwargs = other elif len_other == 1: value, = other if isinstance(value, tuple): other_args = value other_kwargs = {} elif isinstance(value, str): other_name = value other_args, other_kwargs = (), {} else: other_args = () other_kwargs = value elif len_other == 2: # could be (name, args) or (name, kwargs) or (args, kwargs) first, second = other if isinstance(first, str): other_name = first if isinstance(second, tuple): other_args, other_kwargs = second, {} else: other_args, other_kwargs = (), second else: other_args, other_kwargs = first, second else: return False if self_name and other_name != self_name: return False # this order is important for ANY to work! return (other_args, other_kwargs) == (self_args, self_kwargs) __ne__ = object.__ne__ def __call__(self, *args, **kwargs): if self._mock_name is None: return _Call(('', args, kwargs), name='()') name = self._mock_name + '()' return _Call((self._mock_name, args, kwargs), name=name, parent=self) def __getattr__(self, attr): if self._mock_name is None: return _Call(name=attr, from_kall=False) name = '%s.%s' % (self._mock_name, attr) return _Call(name=name, parent=self, from_kall=False) def count(self, *args, **kwargs): return self.__getattr__('count')(*args, **kwargs) def index(self, *args, **kwargs): return self.__getattr__('index')(*args, **kwargs) def __repr__(self): if not self._mock_from_kall: name = self._mock_name or 'call' if name.startswith('()'): name = 'call%s' % name return name if len(self) == 2: name = 'call' args, kwargs = self else: name, args, kwargs = self if not name: name = 'call' elif not name.startswith('()'): name = 'call.%s' % name else: name = 'call%s' % name return _format_call_signature(name, args, kwargs) def call_list(self): """For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.""" vals = [] thing = self while thing is not None: if thing._mock_from_kall: vals.append(thing) thing = thing._mock_parent return _CallList(reversed(vals)) call = _Call(from_kall=False) def create_autospec(spec, spec_set=False, instance=False, _parent=None, _name=None, **kwargs): """Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. Functions or methods being mocked will have their arguments checked to check that they are called with the correct signature. If `spec_set` is True then attempting to set attributes that don't exist on the spec object will raise an `AttributeError`. If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing `instance=True`. The returned mock will only be callable if instances of the mock are callable. `create_autospec` also takes arbitrary keyword arguments that are passed to the constructor of the created mock.""" if _is_list(spec): # can't pass a list instance to the mock constructor as it will be # interpreted as a list of strings spec = type(spec) is_type = isinstance(spec, type) _kwargs = {'spec': spec} if spec_set: _kwargs = {'spec_set': spec} elif spec is None: # None we mock with a normal mock without a spec _kwargs = {} if _kwargs and instance: _kwargs['_spec_as_instance'] = True _kwargs.update(kwargs) Klass = MagicMock if inspect.isdatadescriptor(spec): # descriptors don't have a spec # because we don't know what type they return _kwargs = {} elif not _callable(spec): Klass = NonCallableMagicMock elif is_type and instance and not _instance_callable(spec): Klass = NonCallableMagicMock _name = _kwargs.pop('name', _name) _new_name = _name if _parent is None: # for a top level object no _new_name should be set _new_name = '' mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, name=_name, **_kwargs) if isinstance(spec, FunctionTypes): # should only happen at the top level because we don't # recurse for functions mock = _set_signature(mock, spec) else: _check_signature(spec, mock, is_type, instance) if _parent is not None and not instance: _parent._mock_children[_name] = mock if is_type and not instance and 'return_value' not in kwargs: mock.return_value = create_autospec(spec, spec_set, instance=True, _name='()', _parent=mock) for entry in dir(spec): if _is_magic(entry): # MagicMock already does the useful magic methods for us continue # XXXX do we need a better way of getting attributes without # triggering code execution (?) Probably not - we need the actual # object to mock it so we would rather trigger a property than mock # the property descriptor. Likewise we want to mock out dynamically # provided attributes. # XXXX what about attributes that raise exceptions other than # AttributeError on being fetched? # we could be resilient against it, or catch and propagate the # exception when the attribute is fetched from the mock try: original = getattr(spec, entry) except AttributeError: continue kwargs = {'spec': original} if spec_set: kwargs = {'spec_set': original} if not isinstance(original, FunctionTypes): new = _SpecState(original, spec_set, mock, entry, instance) mock._mock_children[entry] = new else: parent = mock if isinstance(spec, FunctionTypes): parent = mock.mock skipfirst = _must_skip(spec, entry, is_type) kwargs['_eat_self'] = skipfirst new = MagicMock(parent=parent, name=entry, _new_name=entry, _new_parent=parent, **kwargs) mock._mock_children[entry] = new _check_signature(original, new, skipfirst=skipfirst) # so functions created with _set_signature become instance attributes, # *plus* their underlying mock exists in _mock_children of the parent # mock. Adding to _mock_children may be unnecessary where we are also # setting as an instance attribute? if isinstance(new, FunctionTypes): setattr(mock, entry, new) return mock def _must_skip(spec, entry, is_type): """ Return whether we should skip the first argument on spec's `entry` attribute. """ if not isinstance(spec, type): if entry in getattr(spec, '__dict__', {}): # instance attribute - shouldn't skip return False spec = spec.__class__ for klass in spec.__mro__: result = klass.__dict__.get(entry, DEFAULT) if result is DEFAULT: continue if isinstance(result, (staticmethod, classmethod)): return False elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes): # Normal method => skip if looked up on type # (if looked up on instance, self is already skipped) return is_type else: return False # shouldn't get here unless function is a dynamically provided attribute # XXXX untested behaviour return is_type def _get_class(obj): try: return obj.__class__ except AttributeError: # it is possible for objects to have no __class__ return type(obj) class _SpecState(object): def __init__(self, spec, spec_set=False, parent=None, name=None, ids=None, instance=False): self.spec = spec self.ids = ids self.spec_set = spec_set self.parent = parent self.instance = instance self.name = name FunctionTypes = ( # python function type(create_autospec), # instance method type(ANY.__eq__), ) MethodWrapperTypes = ( type(ANY.__eq__.__get__), ) file_spec = None def _iterate_read_data(read_data): # Helper for mock_open: # Retrieve lines from read_data via a generator so that separate calls to # readline, read, and readlines are properly interleaved sep = b'\n' if isinstance(read_data, bytes) else '\n' data_as_list = [l + sep for l in read_data.split(sep)] if data_as_list[-1] == sep: # If the last line ended in a newline, the list comprehension will have an # extra entry that's just a newline. Remove this. data_as_list = data_as_list[:-1] else: # If there wasn't an extra newline by itself, then the file being # emulated doesn't have a newline to end the last line remove the # newline that our naive format() added data_as_list[-1] = data_as_list[-1][:-1] for line in data_as_list: yield line def mock_open(mock=None, read_data=''): """ A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the default) then a `MagicMock` will be created for you, with the API limited to methods or attributes available on standard file handles. `read_data` is a string for the `read` methoddline`, and `readlines` of the file handle to return. This is an empty string by default. """ def _readlines_side_effect(*args, **kwargs): if handle.readlines.return_value is not None: return handle.readlines.return_value return list(_state[0]) def _read_side_effect(*args, **kwargs): if handle.read.return_value is not None: return handle.read.return_value return type(read_data)().join(_state[0]) def _readline_side_effect(): if handle.readline.return_value is not None: while True: yield handle.readline.return_value for line in _state[0]: yield line while True: yield type(read_data)() global file_spec if file_spec is None: import _io file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) if mock is None: mock = MagicMock(name='open', spec=open) handle = MagicMock(spec=file_spec) handle.__enter__.return_value = handle _state = [_iterate_read_data(read_data), None] handle.write.return_value = None handle.read.return_value = None handle.readline.return_value = None handle.readlines.return_value = None handle.read.side_effect = _read_side_effect _state[1] = _readline_side_effect() handle.readline.side_effect = _state[1] handle.readlines.side_effect = _readlines_side_effect def reset_data(*args, **kwargs): _state[0] = _iterate_read_data(read_data) if handle.readline.side_effect == _state[1]: # Only reset the side effect if the user hasn't overridden it. _state[1] = _readline_side_effect() handle.readline.side_effect = _state[1] return DEFAULT mock.side_effect = reset_data mock.return_value = handle return mock class PropertyMock(Mock): """ A mock intended to be used as a property, or other descriptor, on a class. `PropertyMock` provides `__get__` and `__set__` methods so you can specify a return value when it is fetched. Fetching a `PropertyMock` instance from an object calls the mock, with no args. Setting it calls the mock with the value being set. """ def _get_child_mock(self, **kwargs): return MagicMock(**kwargs) def __get__(self, obj, obj_type): return self() def __set__(self, obj, val): self(val)
79,741
2,411
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/util.py
"""Various utility functions.""" from collections import namedtuple, OrderedDict from os.path import commonprefix __unittest = True _MAX_LENGTH = 80 _PLACEHOLDER_LEN = 12 _MIN_BEGIN_LEN = 5 _MIN_END_LEN = 5 _MIN_COMMON_LEN = 5 _MIN_DIFF_LEN = _MAX_LENGTH - \ (_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + _PLACEHOLDER_LEN + _MIN_END_LEN) assert _MIN_DIFF_LEN >= 0 def _shorten(s, prefixlen, suffixlen): skip = len(s) - prefixlen - suffixlen if skip > _PLACEHOLDER_LEN: s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:]) return s def _common_shorten_repr(*args): args = tuple(map(safe_repr, args)) maxlen = max(map(len, args)) if maxlen <= _MAX_LENGTH: return args prefix = commonprefix(args) prefixlen = len(prefix) common_len = _MAX_LENGTH - \ (maxlen - prefixlen + _MIN_BEGIN_LEN + _PLACEHOLDER_LEN) if common_len > _MIN_COMMON_LEN: assert _MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + \ (maxlen - prefixlen) < _MAX_LENGTH prefix = _shorten(prefix, _MIN_BEGIN_LEN, common_len) return tuple(prefix + s[prefixlen:] for s in args) prefix = _shorten(prefix, _MIN_BEGIN_LEN, _MIN_COMMON_LEN) return tuple(prefix + _shorten(s[prefixlen:], _MIN_DIFF_LEN, _MIN_END_LEN) for s in args) def safe_repr(obj, short=False): try: result = repr(obj) except Exception: result = object.__repr__(obj) if not short or len(result) < _MAX_LENGTH: return result return result[:_MAX_LENGTH] + ' [truncated]...' def strclass(cls): return "%s.%s" % (cls.__module__, cls.__qualname__) 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 def unorderable_list_difference(expected, 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.""" missing = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) # anything left in actual is unexpected return missing, actual def three_way_cmp(x, y): """Return -1 if x < y, 0 if x == y and 1 if x > y""" return (x > y) - (x < y) _Mismatch = namedtuple('Mismatch', 'actual expected value') 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 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 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
5,433
178
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/result.py
"""Test result object""" import io import sys import traceback from . import util from functools import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'failfast', False): self.stop() return method(self, *args, **kw) return inner STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' class TestResult(object): """Holder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. """ _previousTestClass = None _testRunEntered = False _moduleSetUpFailed = False def __init__(self, stream=None, descriptions=None, verbosity=None): self.failfast = False self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False self.buffer = False self.tb_locals = False self._stdout_buffer = None self._stderr_buffer = None self._original_stdout = sys.stdout self._original_stderr = sys.stderr self._mirrorOutput = False def printErrors(self): "Called by TestRunner after test run" def startTest(self, test): "Called when the given test is about to be run" self.testsRun += 1 self._mirrorOutput = False self._setupStdout() def _setupStdout(self): if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = io.StringIO() self._stdout_buffer = io.StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def startTestRun(self): """Called once before any tests are executed. See startTest for a method called before each test. """ def stopTest(self, test): """Called when the given test has been run""" self._restoreStdout() self._mirrorOutput = False def _restoreStdout(self): if self.buffer: if self._mirrorOutput: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def stopTestRun(self): """Called once after all tests are executed. See stopTest for a method called after each test. """ @failfast 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 @failfast 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 def addSubTest(self, test, subtest, err): """Called at the end of a subtest. 'err' is None if the subtest ended successfully, otherwise it's a tuple of values as returned by sys.exc_info(). """ # By default, we don't do anything with successful subtests, but # more sophisticated test results might want to record them. if err is not None: if getattr(self, 'failfast', False): self.stop() if issubclass(err[0], test.failureException): errors = self.failures else: errors = self.errors errors.append((subtest, self._exc_info_to_string(err, test))) self._mirrorOutput = True def addSuccess(self, test): "Called when a test has completed successfully" pass def addSkip(self, test, reason): """Called when a test is skipped.""" self.skipped.append((test, reason)) def addExpectedFailure(self, test, err): """Called when an expected failure/error occurred.""" self.expectedFailures.append( (test, self._exc_info_to_string(err, test))) @failfast def addUnexpectedSuccess(self, test): """Called when a test was expected to fail, but succeed.""" self.unexpectedSuccesses.append(test) def wasSuccessful(self): """Tells whether or not this result was a success.""" # The hasattr check is for test_result's OldResult test. That # way this method works on objects that lack the attribute. # (where would such result intances come from? old stored pickles?) return ((len(self.failures) == len(self.errors) == 0) and (not hasattr(self, 'unexpectedSuccesses') or len(self.unexpectedSuccesses) == 0)) def stop(self): """Indicates that the tests should be aborted.""" self.shouldStop = True 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) else: length = None tb_e = traceback.TracebackException( exctype, value, tb, limit=length, capture_locals=self.tb_locals) msgLines = list(tb_e.format()) 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) def _is_relevant_tb_level(self, tb): return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def __repr__(self): return ("<%s run=%i errors=%i failures=%i>" % (util.strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures)))
7,442
217
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/suite.py
"""TestSuite""" import sys from . import case from . import util __unittest = True def _call_if_exists(parent, attr): func = getattr(parent, attr, lambda: None) func() class BaseTestSuite(object): """A simple test suite that doesn't provide class or module shared fixtures. """ _cleanup = True def __init__(self, tests=()): self._tests = [] self._removed_tests = 0 self.addTests(tests) def __repr__(self): return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return list(self) == list(other) def __iter__(self): return iter(self._tests) def countTestCases(self): cases = self._removed_tests for test in self: if test: cases += test.countTestCases() return cases def addTest(self, test): # sanity checks if not callable(test): raise TypeError("{} is not callable".format(repr(test))) if isinstance(test, type) and issubclass(test, (case.TestCase, TestSuite)): raise TypeError("TestCases and TestSuites must be instantiated " "before passing them to addTest()") self._tests.append(test) def addTests(self, tests): if isinstance(tests, str): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for index, test in enumerate(self): if result.shouldStop: break test(result) if self._cleanup: self._removeTestAtIndex(index) return result def _removeTestAtIndex(self, index): """Stop holding a reference to the TestCase at index.""" try: test = self._tests[index] except TypeError: # support for suite implementations that have overridden self._tests pass else: # Some unittest tests add non TestCase/TestSuite objects to # the suite. if hasattr(test, 'countTestCases'): self._removed_tests += test.countTestCases() self._tests[index] = None def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the tests without collecting errors in a TestResult""" for test in self: test.debug() class TestSuite(BaseTestSuite): """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. """ def run(self, result, debug=False): topLevel = False if getattr(result, '_testRunEntered', False) is False: result._testRunEntered = topLevel = True for index, test in enumerate(self): if result.shouldStop: break if _isnotsuite(test): self._tearDownPreviousClass(test, result) self._handleModuleFixture(test, result) self._handleClassSetUp(test, result) result._previousTestClass = test.__class__ if (getattr(test.__class__, '_classSetupFailed', False) or getattr(result, '_moduleSetUpFailed', False)): continue if not debug: test(result) else: test.debug() if self._cleanup: self._removeTestAtIndex(index) if topLevel: self._tearDownPreviousClass(None, result) self._handleModuleTearDown(result) result._testRunEntered = False return result def debug(self): """Run the tests without collecting errors in a TestResult""" debug = _DebugResult() self.run(debug, True) ################################ def _handleClassSetUp(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if result._moduleSetUpFailed: return if getattr(currentClass, "__unittest_skip__", False): return try: currentClass._classSetupFailed = False except TypeError: # test may actually be a function # so its class will be a builtin-type pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: _call_if_exists(result, '_setupStdout') try: setUpClass() except Exception as e: if isinstance(result, _DebugResult): raise currentClass._classSetupFailed = True className = util.strclass(currentClass) errorName = 'setUpClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _get_previous_module(self, result): previousModule = None previousClass = getattr(result, '_previousTestClass', None) if previousClass is not None: previousModule = previousClass.__module__ return previousModule def _handleModuleFixture(self, test, result): previousModule = self._get_previous_module(result) currentModule = test.__class__.__module__ if currentModule == previousModule: return self._handleModuleTearDown(result) result._moduleSetUpFailed = False try: module = sys.modules[currentModule] except KeyError: return setUpModule = getattr(module, 'setUpModule', None) if setUpModule is not None: _call_if_exists(result, '_setupStdout') try: setUpModule() except Exception as e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True errorName = 'setUpModule (%s)' % currentModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _addClassOrModuleLevelException(self, result, exception, errorName): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) if addSkip is not None and isinstance(exception, case.SkipTest): addSkip(error, str(exception)) else: result.addError(error, sys.exc_info()) def _handleModuleTearDown(self, result): previousModule = self._get_previous_module(result) if previousModule is None: return if result._moduleSetUpFailed: return try: module = sys.modules[previousModule] except KeyError: return tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: _call_if_exists(result, '_setupStdout') try: tearDownModule() except Exception as e: if isinstance(result, _DebugResult): raise errorName = 'tearDownModule (%s)' % previousModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _tearDownPreviousClass(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if getattr(previousClass, '_classSetupFailed', False): return if getattr(result, '_moduleSetUpFailed', False): return if getattr(previousClass, "__unittest_skip__", False): return tearDownClass = getattr(previousClass, 'tearDownClass', None) if tearDownClass is not None: _call_if_exists(result, '_setupStdout') try: tearDownClass() except Exception as e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) errorName = 'tearDownClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') class _ErrorHolder(object): """ Placeholder for a TestCase inside a result. As far as a TestResult is concerned, this looks exactly like a unit test. Used to insert arbitrary errors into a test suite run. """ # Inspired by the ErrorHolder from Twisted: # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py # attribute used by TestResult._exc_info_to_string failureException = None def __init__(self, description): self.description = description def id(self): return self.description def shortDescription(self): return None def __repr__(self): return "<ErrorHolder description=%r>" % (self.description,) def __str__(self): return self.id() def run(self, result): # could call result.addError(...) - but this test-like object # shouldn't be run anyway pass def __call__(self, result): return self.run(result) def countTestCases(self): return 0 def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False class _DebugResult(object): "Used by the TestSuite to hold previous class when running in debug." _previousTestClass = None _moduleSetUpFailed = False shouldStop = False
10,479
322
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/__init__.py
""" Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework (used with permission). This module contains the core framework classes that form the basis of specific test cases and suites (TestCase, TestSuite etc.), and also a text-based utility class for running the tests and reporting the results (TextTestRunner). Simple usage: import unittest class IntegerArithmeticTestCase(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main() Further information is available in the bundled documentation, and from http://docs.python.org/library/unittest.html Copyright (c) 1999-2003 Steve Purcell Copyright (c) 2003-2010 Python Software Foundation This module is free software, and you may redistribute it and/or modify it under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. """ __all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', 'expectedFailure', 'TextTestResult', 'installHandler', 'registerResult', 'removeResult', 'removeHandler', 'getTestCaseNames', 'makeSuite', 'findTestCases'] __unittest = True from .result import TestResult from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf, skipUnless, expectedFailure) from .suite import BaseTestSuite, TestSuite from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames, findTestCases) from ._main import TestProgram, main from .runner import TextTestRunner, TextTestResult from .signals import installHandler, registerResult, removeResult, removeHandler # deprecated _TextTestResult = TextTestResult # There are no tests here, so don't try to run anything discovered from # introspecting the symbols (e.g. FunctionTestCase). Instead, all our # tests come from within unittest.test. def load_tests(loader, tests, pattern): import os.path # top level directory cached on loader instance this_dir = os.path.dirname(__file__) return loader.discover(start_dir=this_dir, pattern=pattern)
3,081
77
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_case.py
import contextlib import difflib import pprint import pickle import re import sys import logging import warnings import weakref import inspect from copy import deepcopy from test import support import unittest from unittest.test.support import ( TestEquality, TestHashing, LoggingResult, LegacyLoggingResult, ResultWithNoStartTestRunStopTestRun ) from test.support import captured_stderr log_foo = logging.getLogger('foo') log_foobar = logging.getLogger('foo.bar') log_quux = logging.getLogger('quux') class Test(object): "Keep these TestCase classes out of the main namespace" class Foo(unittest.TestCase): def runTest(self): pass def test1(self): pass class Bar(Foo): def test2(self): pass class LoggingTestCase(unittest.TestCase): """A test case which logs its calls.""" def __init__(self, events): super(Test.LoggingTestCase, self).__init__('test') self.events = events def setUp(self): self.events.append('setUp') def test(self): self.events.append('test') def tearDown(self): self.events.append('tearDown') class Test_TestCase(unittest.TestCase, TestEquality, TestHashing): ### Set up attributes used by inherited tests ################################################################ # Used by TestHashing.test_hash and TestEquality.test_eq eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))] # Used by TestEquality.test_ne ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')), (Test.Foo('test1'), Test.Bar('test1')), (Test.Foo('test1'), Test.Bar('test2'))] ################################################################ ### /Set up attributes used by inherited tests # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." # ... # "methodName defaults to "runTest"." # # Make sure it really is optional, and that it defaults to the proper # thing. def test_init__no_test_name(self): class Test(unittest.TestCase): def runTest(self): raise MyException() def test(self): pass self.assertEqual(Test().id()[-13:], '.Test.runTest') # test that TestCase can be instantiated with no args # primarily for use at the interactive interpreter test = unittest.TestCase() test.assertEqual(3, 3) with test.assertRaises(test.failureException): test.assertEqual(3, 2) with self.assertRaises(AttributeError): test.run() # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." def test_init__test_name__valid(self): class Test(unittest.TestCase): def runTest(self): raise MyException() def test(self): pass self.assertEqual(Test('test').id()[-10:], '.Test.test') # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." def test_init__test_name__invalid(self): class Test(unittest.TestCase): def runTest(self): raise MyException() def test(self): pass try: Test('testfoo') except ValueError: pass else: self.fail("Failed to raise ValueError") # "Return the number of tests represented by the this test object. For # TestCase instances, this will always be 1" def test_countTestCases(self): class Foo(unittest.TestCase): def test(self): pass self.assertEqual(Foo('test').countTestCases(), 1) # "Return the default type of test result object to be used to run this # test. For TestCase instances, this will always be # unittest.TestResult; subclasses of TestCase should # override this as necessary." def test_defaultTestResult(self): class Foo(unittest.TestCase): def runTest(self): pass result = Foo().defaultTestResult() self.assertEqual(type(result), unittest.TestResult) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if setUp() raises # an exception. def test_run_call_order__error_in_setUp(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def setUp(self): super(Foo, self).setUp() raise RuntimeError('raised by Foo.setUp') Foo(events).run(result) expected = ['startTest', 'setUp', 'addError', 'stopTest'] self.assertEqual(events, expected) # "With a temporary result stopTestRun is called when setUp errors. def test_run_call_order__error_in_setUp_default_result(self): events = [] class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def setUp(self): super(Foo, self).setUp() raise RuntimeError('raised by Foo.setUp') Foo(events).run() expected = ['startTestRun', 'startTest', 'setUp', 'addError', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test raises # an error (as opposed to a failure). def test_run_call_order__error_in_test(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() raise RuntimeError('raised by Foo.test') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) # "With a default result, an error in the test still results in stopTestRun # being called." def test_run_call_order__error_in_test_default_result(self): events = [] class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def test(self): super(Foo, self).test() raise RuntimeError('raised by Foo.test') expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest', 'stopTestRun'] Foo(events).run() self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test signals # a failure (as opposed to an error). def test_run_call_order__failure_in_test(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() self.fail('raised by Foo.test') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addFailure', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) # "When a test fails with a default result stopTestRun is still called." def test_run_call_order__failure_in_test_default_result(self): class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def test(self): super(Foo, self).test() self.fail('raised by Foo.test') expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addFailure', 'stopTest', 'stopTestRun'] events = [] Foo(events).run() self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if tearDown() raises # an exception. def test_run_call_order__error_in_tearDown(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def tearDown(self): super(Foo, self).tearDown() raise RuntimeError('raised by Foo.tearDown') Foo(events).run(result) expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] self.assertEqual(events, expected) # "When tearDown errors with a default result stopTestRun is still called." def test_run_call_order__error_in_tearDown_default_result(self): class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def tearDown(self): super(Foo, self).tearDown() raise RuntimeError('raised by Foo.tearDown') events = [] Foo(events).run() expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "TestCase.run() still works when the defaultTestResult is a TestResult # that does not support startTestRun and stopTestRun. def test_run_call_order_default_result(self): class Foo(unittest.TestCase): def defaultTestResult(self): return ResultWithNoStartTestRunStopTestRun() def test(self): pass Foo('test').run() def _check_call_order__subtests(self, result, events, expected_events): class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() for i in [1, 2, 3]: with self.subTest(i=i): if i == 1: self.fail('failure') for j in [2, 3]: with self.subTest(j=j): if i * j == 6: raise RuntimeError('raised by Foo.test') 1 / 0 # Order is the following: # i=1 => subtest failure # i=2, j=2 => subtest success # i=2, j=3 => subtest error # i=3, j=2 => subtest error # i=3, j=3 => subtest success # toplevel => error Foo(events).run(result) self.assertEqual(events, expected_events) def test_run_call_order__subtests(self): events = [] result = LoggingResult(events) expected = ['startTest', 'setUp', 'test', 'tearDown', 'addSubTestFailure', 'addSubTestSuccess', 'addSubTestFailure', 'addSubTestFailure', 'addSubTestSuccess', 'addError', 'stopTest'] self._check_call_order__subtests(result, events, expected) def test_run_call_order__subtests_legacy(self): # With a legacy result object (without an addSubTest method), # text execution stops after the first subtest failure. events = [] result = LegacyLoggingResult(events) expected = ['startTest', 'setUp', 'test', 'tearDown', 'addFailure', 'stopTest'] self._check_call_order__subtests(result, events, expected) def _check_call_order__subtests_success(self, result, events, expected_events): class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() for i in [1, 2]: with self.subTest(i=i): for j in [2, 3]: with self.subTest(j=j): pass Foo(events).run(result) self.assertEqual(events, expected_events) def test_run_call_order__subtests_success(self): events = [] result = LoggingResult(events) # The 6 subtest successes are individually recorded, in addition # to the whole test success. expected = (['startTest', 'setUp', 'test', 'tearDown'] + 6 * ['addSubTestSuccess'] + ['addSuccess', 'stopTest']) self._check_call_order__subtests_success(result, events, expected) def test_run_call_order__subtests_success_legacy(self): # With a legacy result, only the whole test success is recorded. events = [] result = LegacyLoggingResult(events) expected = ['startTest', 'setUp', 'test', 'tearDown', 'addSuccess', 'stopTest'] self._check_call_order__subtests_success(result, events, expected) def test_run_call_order__subtests_failfast(self): events = [] result = LoggingResult(events) result.failfast = True class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() with self.subTest(i=1): self.fail('failure') with self.subTest(i=2): self.fail('failure') self.fail('failure') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addSubTestFailure', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) def test_subtests_failfast(self): # Ensure proper test flow with subtests and failfast (issue #22894) events = [] class Foo(unittest.TestCase): def test_a(self): with self.subTest(): events.append('a1') events.append('a2') def test_b(self): with self.subTest(): events.append('b1') with self.subTest(): self.fail('failure') events.append('b2') def test_c(self): events.append('c') result = unittest.TestResult() result.failfast = True suite = unittest.makeSuite(Foo) suite.run(result) expected = ['a1', 'a2', 'b1'] self.assertEqual(events, expected) def test_subtests_debug(self): # Test debug() with a test that uses subTest() (bpo-34900) events = [] class Foo(unittest.TestCase): def test_a(self): events.append('test case') with self.subTest(): events.append('subtest 1') Foo('test_a').debug() self.assertEqual(events, ['test case', 'subtest 1']) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework. The initial value of this # attribute is AssertionError" def test_failureException__default(self): class Foo(unittest.TestCase): def test(self): pass self.assertIs(Foo('test').failureException, AssertionError) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException def test_failureException__subclassing__explicit_raise(self): events = [] result = LoggingResult(events) class Foo(unittest.TestCase): def test(self): raise RuntimeError() failureException = RuntimeError self.assertIs(Foo('test').failureException, RuntimeError) Foo('test').run(result) expected = ['startTest', 'addFailure', 'stopTest'] self.assertEqual(events, expected) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException def test_failureException__subclassing__implicit_raise(self): events = [] result = LoggingResult(events) class Foo(unittest.TestCase): def test(self): self.fail("foo") failureException = RuntimeError self.assertIs(Foo('test').failureException, RuntimeError) Foo('test').run(result) expected = ['startTest', 'addFailure', 'stopTest'] self.assertEqual(events, expected) # "The default implementation does nothing." def test_setUp(self): class Foo(unittest.TestCase): def runTest(self): pass # ... and nothing should happen Foo().setUp() # "The default implementation does nothing." def test_tearDown(self): class Foo(unittest.TestCase): def runTest(self): pass # ... and nothing should happen Foo().tearDown() # "Return a string identifying the specific test case." # # Because of the vague nature of the docs, I'm not going to lock this # test down too much. Really all that can be asserted is that the id() # will be a string (either 8-byte or unicode -- again, because the docs # just say "string") def test_id(self): class Foo(unittest.TestCase): def runTest(self): pass self.assertIsInstance(Foo().id(), str) # "If result is omitted or None, a temporary result object is created, # used, and is made available to the caller. As TestCase owns the # temporary result startTestRun and stopTestRun are called. def test_run__uses_defaultTestResult(self): events = [] defaultResult = LoggingResult(events) class Foo(unittest.TestCase): def test(self): events.append('test') def defaultTestResult(self): return defaultResult # Make run() find a result object on its own result = Foo('test').run() self.assertIs(result, defaultResult) expected = ['startTestRun', 'startTest', 'test', 'addSuccess', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "The result object is returned to run's caller" def test_run__returns_given_result(self): class Foo(unittest.TestCase): def test(self): pass result = unittest.TestResult() retval = Foo('test').run(result) self.assertIs(retval, result) # "The same effect [as method run] may be had by simply calling the # TestCase instance." def test_call__invoking_an_instance_delegates_to_run(self): resultIn = unittest.TestResult() resultOut = unittest.TestResult() class Foo(unittest.TestCase): def test(self): pass def run(self, result): self.assertIs(result, resultIn) return resultOut retval = Foo('test')(resultIn) self.assertIs(retval, resultOut) def testShortDescriptionWithoutDocstring(self): self.assertIsNone(self.shortDescription()) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testShortDescriptionWithOneLineDocstring(self): """Tests shortDescription() for a method with a docstring.""" self.assertEqual( self.shortDescription(), 'Tests shortDescription() for a method with a docstring.') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testShortDescriptionWithMultiLineDocstring(self): """Tests shortDescription() for a method with a longer docstring. This method ensures that only the first line of a docstring is returned used in the short description, no matter how long the whole thing is. """ self.assertEqual( self.shortDescription(), 'Tests shortDescription() for a method with a longer ' 'docstring.') def testAddTypeEqualityFunc(self): class SadSnake(object): """Dummy class for test_addTypeEqualityFunc.""" s1, s2 = SadSnake(), SadSnake() self.assertFalse(s1 == s2) def AllSnakesCreatedEqual(a, b, msg=None): return type(a) == type(b) == SadSnake self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) self.assertEqual(s1, s2) # No this doesn't clean up and remove the SadSnake equality func # from this TestCase instance but since its a local nothing else # will ever notice that. def testAssertIs(self): thing = object() self.assertIs(thing, thing) self.assertRaises(self.failureException, self.assertIs, thing, object()) def testAssertIsNot(self): thing = object() self.assertIsNot(thing, object()) self.assertRaises(self.failureException, self.assertIsNot, thing, thing) def testAssertIsInstance(self): thing = [] self.assertIsInstance(thing, list) self.assertRaises(self.failureException, self.assertIsInstance, thing, dict) def testAssertNotIsInstance(self): thing = [] self.assertNotIsInstance(thing, dict) self.assertRaises(self.failureException, self.assertNotIsInstance, thing, list) def testAssertIn(self): animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} self.assertIn('a', 'abc') self.assertIn(2, [1, 2, 3]) self.assertIn('monkey', animals) self.assertNotIn('d', 'abc') self.assertNotIn(0, [1, 2, 3]) self.assertNotIn('otter', animals) self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) self.assertRaises(self.failureException, self.assertIn, 'elephant', animals) self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) self.assertRaises(self.failureException, self.assertNotIn, 'cow', animals) def testAssertDictContainsSubset(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertDictContainsSubset({}, {}) self.assertDictContainsSubset({}, {'a': 1}) self.assertDictContainsSubset({'a': 1}, {'a': 1}) self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({1: "one"}, {}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 2}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'c': 1}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) one = ''.join(chr(i) for i in range(255)) # this used to cause a UnicodeDecodeError constructing the failure msg with self.assertRaises(self.failureException): self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'}) def testAssertEqual(self): equal_pairs = [ ((), ()), ({}, {}), ([], []), (set(), set()), (frozenset(), frozenset())] for a, b in equal_pairs: # This mess of try excepts is to test the assertEqual behavior # itself. try: self.assertEqual(a, b) except self.failureException: self.fail('assertEqual(%r, %r) failed' % (a, b)) try: self.assertEqual(a, b, msg='foo') except self.failureException: self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) try: self.assertEqual(a, b, 'foo') except self.failureException: self.fail('assertEqual(%r, %r) with third parameter failed' % (a, b)) unequal_pairs = [ ((), []), ({}, set()), (set([4,1]), frozenset([4,2])), (frozenset([4,5]), set([2,3])), (set([3,4]), set([5,4]))] for a, b in unequal_pairs: self.assertRaises(self.failureException, self.assertEqual, a, b) self.assertRaises(self.failureException, self.assertEqual, a, b, 'foo') self.assertRaises(self.failureException, self.assertEqual, a, b, msg='foo') def testEquality(self): self.assertListEqual([], []) self.assertTupleEqual((), ()) self.assertSequenceEqual([], ()) a = [0, 'a', []] b = [] self.assertRaises(unittest.TestCase.failureException, self.assertListEqual, a, b) self.assertRaises(unittest.TestCase.failureException, self.assertListEqual, tuple(a), tuple(b)) self.assertRaises(unittest.TestCase.failureException, self.assertSequenceEqual, a, tuple(b)) b.extend(a) self.assertListEqual(a, b) self.assertTupleEqual(tuple(a), tuple(b)) self.assertSequenceEqual(a, tuple(b)) self.assertSequenceEqual(tuple(a), b) self.assertRaises(self.failureException, self.assertListEqual, a, tuple(b)) self.assertRaises(self.failureException, self.assertTupleEqual, tuple(a), b) self.assertRaises(self.failureException, self.assertListEqual, None, b) self.assertRaises(self.failureException, self.assertTupleEqual, None, tuple(b)) self.assertRaises(self.failureException, self.assertSequenceEqual, None, tuple(b)) self.assertRaises(self.failureException, self.assertListEqual, 1, 1) self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) self.assertRaises(self.failureException, self.assertSequenceEqual, 1, 1) self.assertDictEqual({}, {}) c = { 'x': 1 } d = {} self.assertRaises(unittest.TestCase.failureException, self.assertDictEqual, c, d) d.update(c) self.assertDictEqual(c, d) d['x'] = 0 self.assertRaises(unittest.TestCase.failureException, self.assertDictEqual, c, d, 'These are unequal') self.assertRaises(self.failureException, self.assertDictEqual, None, d) self.assertRaises(self.failureException, self.assertDictEqual, [], d) self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) def testAssertSequenceEqualMaxDiff(self): self.assertEqual(self.maxDiff, 80*8) seq1 = 'a' + 'x' * 80**2 seq2 = 'b' + 'x' * 80**2 diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) # the +1 is the leading \n added by assertSequenceEqual omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,) self.maxDiff = len(diff)//2 try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertLess(len(msg), len(diff)) self.assertIn(omitted, msg) self.maxDiff = len(diff) * 2 try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertGreater(len(msg), len(diff)) self.assertNotIn(omitted, msg) self.maxDiff = None try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertGreater(len(msg), len(diff)) self.assertNotIn(omitted, msg) def testTruncateMessage(self): self.maxDiff = 1 message = self._truncateMessage('foo', 'bar') omitted = unittest.case.DIFF_OMITTED % len('bar') self.assertEqual(message, 'foo' + omitted) self.maxDiff = None message = self._truncateMessage('foo', 'bar') self.assertEqual(message, 'foobar') self.maxDiff = 4 message = self._truncateMessage('foo', 'bar') self.assertEqual(message, 'foobar') def testAssertDictEqualTruncates(self): test = unittest.TestCase('assertEqual') def truncate(msg, diff): return 'foo' test._truncateMessage = truncate try: test.assertDictEqual({}, {1: 0}) except self.failureException as e: self.assertEqual(str(e), 'foo') else: self.fail('assertDictEqual did not fail') def testAssertMultiLineEqualTruncates(self): test = unittest.TestCase('assertEqual') def truncate(msg, diff): return 'foo' test._truncateMessage = truncate try: test.assertMultiLineEqual('foo', 'bar') except self.failureException as e: self.assertEqual(str(e), 'foo') else: self.fail('assertMultiLineEqual did not fail') def testAssertEqual_diffThreshold(self): # check threshold value self.assertEqual(self._diffThreshold, 2**16) # disable madDiff to get diff markers self.maxDiff = None # set a lower threshold value and add a cleanup to restore it old_threshold = self._diffThreshold self._diffThreshold = 2**5 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) # under the threshold: diff marker (^) in error message s = 'x' * (2**4) with self.assertRaises(self.failureException) as cm: self.assertEqual(s + 'a', s + 'b') self.assertIn('^', str(cm.exception)) self.assertEqual(s + 'a', s + 'a') # over the threshold: diff not used and marker (^) not in error message s = 'x' * (2**6) # if the path that uses difflib is taken, _truncateMessage will be # called -- replace it with explodingTruncation to verify that this # doesn't happen def explodingTruncation(message, diff): raise SystemError('this should not be raised') old_truncate = self._truncateMessage self._truncateMessage = explodingTruncation self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate)) s1, s2 = s + 'a', s + 'b' with self.assertRaises(self.failureException) as cm: self.assertEqual(s1, s2) self.assertNotIn('^', str(cm.exception)) self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2)) self.assertEqual(s + 'a', s + 'a') def testAssertEqual_shorten(self): # set a lower threshold value and add a cleanup to restore it old_threshold = self._diffThreshold self._diffThreshold = 0 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) s = 'x' * 100 s1, s2 = s + 'a', s + 'b' with self.assertRaises(self.failureException) as cm: self.assertEqual(s1, s2) c = 'xxxx[35 chars]' + 'x' * 61 self.assertEqual(str(cm.exception), "'%sa' != '%sb'" % (c, c)) self.assertEqual(s + 'a', s + 'a') p = 'y' * 50 s1, s2 = s + 'a' + p, s + 'b' + p with self.assertRaises(self.failureException) as cm: self.assertEqual(s1, s2) c = 'xxxx[85 chars]xxxxxxxxxxx' self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, p, c, p)) p = 'y' * 100 s1, s2 = s + 'a' + p, s + 'b' + p with self.assertRaises(self.failureException) as cm: self.assertEqual(s1, s2) c = 'xxxx[91 chars]xxxxx' d = 'y' * 40 + '[56 chars]yyyy' self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, d, c, d)) def testAssertCountEqual(self): a = object() self.assertCountEqual([1, 2, 3], [3, 2, 1]) self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2)) self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"]) self.assertRaises(self.failureException, self.assertCountEqual, [1, 2] + [3] * 100, [1] * 100 + [2, 3]) self.assertRaises(self.failureException, self.assertCountEqual, [1, "2", "a", "a"], ["a", "2", True, 1]) self.assertRaises(self.failureException, self.assertCountEqual, [10], [10, 11]) self.assertRaises(self.failureException, self.assertCountEqual, [10, 11], [10]) self.assertRaises(self.failureException, self.assertCountEqual, [10, 11, 10], [10, 11]) # Test that sequences of unhashable objects can be tested for sameness: self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]]) # Test that iterator of unhashable objects can be tested for sameness: self.assertCountEqual(iter([1, 2, [], 3, 4]), iter([1, 2, [], 3, 4])) # hashable types, but not orderable self.assertRaises(self.failureException, self.assertCountEqual, [], [divmod, 'x', 1, 5j, 2j, frozenset()]) # comparing dicts self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) # comparing heterogenous non-hashable sequences self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1]) self.assertRaises(self.failureException, self.assertCountEqual, [], [divmod, [], 'x', 1, 5j, 2j, set()]) self.assertRaises(self.failureException, self.assertCountEqual, [[1]], [[2]]) # Same elements, but not same sequence length self.assertRaises(self.failureException, self.assertCountEqual, [1, 1, 2], [2, 1]) self.assertRaises(self.failureException, self.assertCountEqual, [1, 1, "2", "a", "a"], ["2", "2", True, "a"]) self.assertRaises(self.failureException, self.assertCountEqual, [1, {'b': 2}, None, True], [{'b': 2}, True, None]) # Same elements which don't reliably compare, in # different order, see issue 10242 a = [{2,4}, {1,2}] b = a[::-1] self.assertCountEqual(a, b) # test utility functions supporting assertCountEqual() diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce')) expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} self.assertEqual(diffs, expected) diffs = unittest.util._count_diff_all_purpose([[]], []) self.assertEqual(diffs, [(1, 0, [])]) diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce')) expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} self.assertEqual(diffs, expected) def testAssertSetEqual(self): set1 = set() set2 = set() self.assertSetEqual(set1, set2) self.assertRaises(self.failureException, self.assertSetEqual, None, set2) self.assertRaises(self.failureException, self.assertSetEqual, [], set2) self.assertRaises(self.failureException, self.assertSetEqual, set1, None) self.assertRaises(self.failureException, self.assertSetEqual, set1, []) set1 = set(['a']) set2 = set() self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a']) set2 = set(['a']) self.assertSetEqual(set1, set2) set1 = set(['a']) set2 = set(['a', 'b']) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a']) set2 = frozenset(['a', 'b']) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a', 'b']) set2 = frozenset(['a', 'b']) self.assertSetEqual(set1, set2) set1 = set() set2 = "foo" self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) # make sure any string formatting is tuple-safe set1 = set([(0, 1), (2, 3)]) set2 = set([(4, 5)]) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) def testInequality(self): # Try ints self.assertGreater(2, 1) self.assertGreaterEqual(2, 1) self.assertGreaterEqual(1, 1) self.assertLess(1, 2) self.assertLessEqual(1, 2) self.assertLessEqual(1, 1) self.assertRaises(self.failureException, self.assertGreater, 1, 2) self.assertRaises(self.failureException, self.assertGreater, 1, 1) self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) self.assertRaises(self.failureException, self.assertLess, 2, 1) self.assertRaises(self.failureException, self.assertLess, 1, 1) self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) # Try Floats self.assertGreater(1.1, 1.0) self.assertGreaterEqual(1.1, 1.0) self.assertGreaterEqual(1.0, 1.0) self.assertLess(1.0, 1.1) self.assertLessEqual(1.0, 1.1) self.assertLessEqual(1.0, 1.0) self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) # Try Strings self.assertGreater('bug', 'ant') self.assertGreaterEqual('bug', 'ant') self.assertGreaterEqual('ant', 'ant') self.assertLess('ant', 'bug') self.assertLessEqual('ant', 'bug') self.assertLessEqual('ant', 'ant') self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') # Try bytes self.assertGreater(b'bug', b'ant') self.assertGreaterEqual(b'bug', b'ant') self.assertGreaterEqual(b'ant', b'ant') self.assertLess(b'ant', b'bug') self.assertLessEqual(b'ant', b'bug') self.assertLessEqual(b'ant', b'ant') self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug') self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant', b'bug') self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant') self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant') self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant') def testAssertMultiLineEqual(self): sample_text = """\ http://www.python.org/doc/2.3/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] """ revised_sample_text = """\ http://www.python.org/doc/2.4.1/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] You may provide your own implementation that does not subclass from TestCase, of course. """ sample_text_error = """\ - http://www.python.org/doc/2.3/lib/module-unittest.html ? ^ + http://www.python.org/doc/2.4.1/lib/module-unittest.html ? ^^^ test case - A test case is the smallest unit of testing. [...] + A test case is the smallest unit of testing. [...] You may provide your ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. """ self.maxDiff = None try: self.assertMultiLineEqual(sample_text, revised_sample_text) except self.failureException as e: # need to remove the first line of the error message error = str(e).split('\n', 1)[1] self.assertEqual(sample_text_error, error) def testAssertEqualSingleLine(self): sample_text = "laden swallows fly slowly" revised_sample_text = "unladen swallows fly quickly" sample_text_error = """\ - laden swallows fly slowly ? ^^^^ + unladen swallows fly quickly ? ++ ^^^^^ """ try: self.assertEqual(sample_text, revised_sample_text) except self.failureException as e: # need to remove the first line of the error message error = str(e).split('\n', 1)[1] self.assertEqual(sample_text_error, error) def testEqualityBytesWarning(self): if sys.flags.bytes_warning: def bytes_warning(): return self.assertWarnsRegex(BytesWarning, 'Comparison between bytes and string') else: def bytes_warning(): return contextlib.ExitStack() with bytes_warning(), self.assertRaises(self.failureException): self.assertEqual('a', b'a') with bytes_warning(): self.assertNotEqual('a', b'a') a = [0, 'a'] b = [0, b'a'] with bytes_warning(), self.assertRaises(self.failureException): self.assertListEqual(a, b) with bytes_warning(), self.assertRaises(self.failureException): self.assertTupleEqual(tuple(a), tuple(b)) with bytes_warning(), self.assertRaises(self.failureException): self.assertSequenceEqual(a, tuple(b)) with bytes_warning(), self.assertRaises(self.failureException): self.assertSequenceEqual(tuple(a), b) with bytes_warning(), self.assertRaises(self.failureException): self.assertSequenceEqual('a', b'a') with bytes_warning(), self.assertRaises(self.failureException): self.assertSetEqual(set(a), set(b)) with self.assertRaises(self.failureException): self.assertListEqual(a, tuple(b)) with self.assertRaises(self.failureException): self.assertTupleEqual(tuple(a), b) a = [0, b'a'] b = [0] with self.assertRaises(self.failureException): self.assertListEqual(a, b) with self.assertRaises(self.failureException): self.assertTupleEqual(tuple(a), tuple(b)) with self.assertRaises(self.failureException): self.assertSequenceEqual(a, tuple(b)) with self.assertRaises(self.failureException): self.assertSequenceEqual(tuple(a), b) with self.assertRaises(self.failureException): self.assertSetEqual(set(a), set(b)) a = [0] b = [0, b'a'] with self.assertRaises(self.failureException): self.assertListEqual(a, b) with self.assertRaises(self.failureException): self.assertTupleEqual(tuple(a), tuple(b)) with self.assertRaises(self.failureException): self.assertSequenceEqual(a, tuple(b)) with self.assertRaises(self.failureException): self.assertSequenceEqual(tuple(a), b) with self.assertRaises(self.failureException): self.assertSetEqual(set(a), set(b)) with bytes_warning(), self.assertRaises(self.failureException): self.assertDictEqual({'a': 0}, {b'a': 0}) with self.assertRaises(self.failureException): self.assertDictEqual({}, {b'a': 0}) with self.assertRaises(self.failureException): self.assertDictEqual({b'a': 0}, {}) with self.assertRaises(self.failureException): self.assertCountEqual([b'a', b'a'], [b'a', b'a', b'a']) with bytes_warning(): self.assertCountEqual(['a', b'a'], ['a', b'a']) with bytes_warning(), self.assertRaises(self.failureException): self.assertCountEqual(['a', 'a'], [b'a', b'a']) with bytes_warning(), self.assertRaises(self.failureException): self.assertCountEqual(['a', 'a', []], [b'a', b'a', []]) def testAssertIsNone(self): self.assertIsNone(None) self.assertRaises(self.failureException, self.assertIsNone, False) self.assertIsNotNone('DjZoPloGears on Rails') self.assertRaises(self.failureException, self.assertIsNotNone, None) def testAssertRegex(self): self.assertRegex('asdfabasdf', r'ab+') self.assertRaises(self.failureException, self.assertRegex, 'saaas', r'aaaa') def testAssertRaisesCallable(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') self.assertRaises(ExceptionMock, Stub) # A tuple of exception classes is accepted self.assertRaises((ValueError, ExceptionMock), Stub) # *args and **kwargs also work self.assertRaises(ValueError, int, '19', base=8) # Failure when no exception is raised with self.assertRaises(self.failureException): self.assertRaises(ExceptionMock, lambda: 0) # Failure when the function is None with self.assertWarns(DeprecationWarning): self.assertRaises(ExceptionMock, None) # Failure when another exception is raised with self.assertRaises(ExceptionMock): self.assertRaises(ValueError, Stub) def testAssertRaisesContext(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') with self.assertRaises(ExceptionMock): Stub() # A tuple of exception classes is accepted with self.assertRaises((ValueError, ExceptionMock)) as cm: Stub() # The context manager exposes caught exception self.assertIsInstance(cm.exception, ExceptionMock) self.assertEqual(cm.exception.args[0], 'We expect') # *args and **kwargs also work with self.assertRaises(ValueError): int('19', base=8) # Failure when no exception is raised with self.assertRaises(self.failureException): with self.assertRaises(ExceptionMock): pass # Custom message with self.assertRaisesRegex(self.failureException, 'foobar'): with self.assertRaises(ExceptionMock, msg='foobar'): pass # Invalid keyword argument with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ self.assertRaises(AssertionError): with self.assertRaises(ExceptionMock, foobar=42): pass # Failure when another exception is raised with self.assertRaises(ExceptionMock): self.assertRaises(ValueError, Stub) def testAssertRaisesNoExceptionType(self): with self.assertRaises(TypeError): self.assertRaises() with self.assertRaises(TypeError): self.assertRaises(1) with self.assertRaises(TypeError): self.assertRaises(object) with self.assertRaises(TypeError): self.assertRaises((ValueError, 1)) with self.assertRaises(TypeError): self.assertRaises((ValueError, object)) def testAssertRaisesRefcount(self): # bpo-23890: assertRaises() must not keep objects alive longer # than expected def func() : try: raise ValueError except ValueError: raise ValueError refcount = sys.getrefcount(func) self.assertRaises(ValueError, func) self.assertEqual(refcount, sys.getrefcount(func)) def testAssertRaisesRegex(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub) self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) with self.assertWarns(DeprecationWarning): self.assertRaisesRegex(ExceptionMock, 'expect$', None) def testAssertNotRaisesRegex(self): self.assertRaisesRegex( self.failureException, '^Exception not raised by <lambda>$', self.assertRaisesRegex, Exception, re.compile('x'), lambda: None) self.assertRaisesRegex( self.failureException, '^Exception not raised by <lambda>$', self.assertRaisesRegex, Exception, 'x', lambda: None) # Custom message with self.assertRaisesRegex(self.failureException, 'foobar'): with self.assertRaisesRegex(Exception, 'expect', msg='foobar'): pass # Invalid keyword argument with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ self.assertRaises(AssertionError): with self.assertRaisesRegex(Exception, 'expect', foobar=42): pass def testAssertRaisesRegexInvalidRegex(self): # Issue 20145. class MyExc(Exception): pass self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True) def testAssertWarnsRegexInvalidRegex(self): # Issue 20145. class MyWarn(Warning): pass self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True) def testAssertRaisesRegexMismatch(self): def Stub(): raise Exception('Unexpected') self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegex, Exception, '^Expected$', Stub) self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegex, Exception, re.compile('^Expected$'), Stub) def testAssertRaisesExcValue(self): class ExceptionMock(Exception): pass def Stub(foo): raise ExceptionMock(foo) v = "particular value" ctx = self.assertRaises(ExceptionMock) with ctx: Stub(v) e = ctx.exception self.assertIsInstance(e, ExceptionMock) self.assertEqual(e.args[0], v) def testAssertRaisesRegexNoExceptionType(self): with self.assertRaises(TypeError): self.assertRaisesRegex() with self.assertRaises(TypeError): self.assertRaisesRegex(ValueError) with self.assertRaises(TypeError): self.assertRaisesRegex(1, 'expect') with self.assertRaises(TypeError): self.assertRaisesRegex(object, 'expect') with self.assertRaises(TypeError): self.assertRaisesRegex((ValueError, 1), 'expect') with self.assertRaises(TypeError): self.assertRaisesRegex((ValueError, object), 'expect') def testAssertWarnsCallable(self): def _runtime_warn(): warnings.warn("foo", RuntimeWarning) # Success when the right warning is triggered, even several times self.assertWarns(RuntimeWarning, _runtime_warn) self.assertWarns(RuntimeWarning, _runtime_warn) # A tuple of warning classes is accepted self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) # *args and **kwargs also work self.assertWarns(RuntimeWarning, warnings.warn, "foo", category=RuntimeWarning) # Failure when no warning is triggered with self.assertRaises(self.failureException): self.assertWarns(RuntimeWarning, lambda: 0) # Failure when the function is None with self.assertWarns(DeprecationWarning): self.assertWarns(RuntimeWarning, None) # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): self.assertWarns(DeprecationWarning, _runtime_warn) # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): self.assertWarns(DeprecationWarning, _runtime_warn) def testAssertWarnsContext(self): # Believe it or not, it is preferable to duplicate all tests above, # to make sure the __warningregistry__ $@ is circumvented correctly. def _runtime_warn(): warnings.warn("foo", RuntimeWarning) _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] with self.assertWarns(RuntimeWarning) as cm: _runtime_warn() # A tuple of warning classes is accepted with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm: _runtime_warn() # The context manager exposes various useful attributes self.assertIsInstance(cm.warning, RuntimeWarning) self.assertEqual(cm.warning.args[0], "foo") self.assertIn("test_case.py", cm.filename) self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) # Same with several warnings with self.assertWarns(RuntimeWarning): _runtime_warn() _runtime_warn() with self.assertWarns(RuntimeWarning): warnings.warn("foo", category=RuntimeWarning) # Failure when no warning is triggered with self.assertRaises(self.failureException): with self.assertWarns(RuntimeWarning): pass # Custom message with self.assertRaisesRegex(self.failureException, 'foobar'): with self.assertWarns(RuntimeWarning, msg='foobar'): pass # Invalid keyword argument with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ self.assertRaises(AssertionError): with self.assertWarns(RuntimeWarning, foobar=42): pass # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): with self.assertWarns(DeprecationWarning): _runtime_warn() # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): with self.assertWarns(DeprecationWarning): _runtime_warn() def testAssertWarnsNoExceptionType(self): with self.assertRaises(TypeError): self.assertWarns() with self.assertRaises(TypeError): self.assertWarns(1) with self.assertRaises(TypeError): self.assertWarns(object) with self.assertRaises(TypeError): self.assertWarns((UserWarning, 1)) with self.assertRaises(TypeError): self.assertWarns((UserWarning, object)) with self.assertRaises(TypeError): self.assertWarns((UserWarning, Exception)) def testAssertWarnsRegexCallable(self): def _runtime_warn(msg): warnings.warn(msg, RuntimeWarning) self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "foox") # Failure when no warning is triggered with self.assertRaises(self.failureException): self.assertWarnsRegex(RuntimeWarning, "o+", lambda: 0) # Failure when the function is None with self.assertWarns(DeprecationWarning): self.assertWarnsRegex(RuntimeWarning, "o+", None) # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): self.assertWarnsRegex(DeprecationWarning, "o+", _runtime_warn, "foox") # Failure when message doesn't match with self.assertRaises(self.failureException): self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "barz") # A little trickier: we ask RuntimeWarnings to be raised, and then # check for some of them. It is implementation-defined whether # non-matching RuntimeWarnings are simply re-raised, or produce a # failureException. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises((RuntimeWarning, self.failureException)): self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "barz") def testAssertWarnsRegexContext(self): # Same as above, but with assertWarnsRegex as a context manager def _runtime_warn(msg): warnings.warn(msg, RuntimeWarning) _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] with self.assertWarnsRegex(RuntimeWarning, "o+") as cm: _runtime_warn("foox") self.assertIsInstance(cm.warning, RuntimeWarning) self.assertEqual(cm.warning.args[0], "foox") self.assertIn("test_case.py", cm.filename) self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) # Failure when no warning is triggered with self.assertRaises(self.failureException): with self.assertWarnsRegex(RuntimeWarning, "o+"): pass # Custom message with self.assertRaisesRegex(self.failureException, 'foobar'): with self.assertWarnsRegex(RuntimeWarning, 'o+', msg='foobar'): pass # Invalid keyword argument with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \ self.assertRaises(AssertionError): with self.assertWarnsRegex(RuntimeWarning, 'o+', foobar=42): pass # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): with self.assertWarnsRegex(DeprecationWarning, "o+"): _runtime_warn("foox") # Failure when message doesn't match with self.assertRaises(self.failureException): with self.assertWarnsRegex(RuntimeWarning, "o+"): _runtime_warn("barz") # A little trickier: we ask RuntimeWarnings to be raised, and then # check for some of them. It is implementation-defined whether # non-matching RuntimeWarnings are simply re-raised, or produce a # failureException. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises((RuntimeWarning, self.failureException)): with self.assertWarnsRegex(RuntimeWarning, "o+"): _runtime_warn("barz") def testAssertWarnsRegexNoExceptionType(self): with self.assertRaises(TypeError): self.assertWarnsRegex() with self.assertRaises(TypeError): self.assertWarnsRegex(UserWarning) with self.assertRaises(TypeError): self.assertWarnsRegex(1, 'expect') with self.assertRaises(TypeError): self.assertWarnsRegex(object, 'expect') with self.assertRaises(TypeError): self.assertWarnsRegex((UserWarning, 1), 'expect') with self.assertRaises(TypeError): self.assertWarnsRegex((UserWarning, object), 'expect') with self.assertRaises(TypeError): self.assertWarnsRegex((UserWarning, Exception), 'expect') @contextlib.contextmanager def assertNoStderr(self): with captured_stderr() as buf: yield self.assertEqual(buf.getvalue(), "") def assertLogRecords(self, records, matches): self.assertEqual(len(records), len(matches)) for rec, match in zip(records, matches): self.assertIsInstance(rec, logging.LogRecord) for k, v in match.items(): self.assertEqual(getattr(rec, k), v) def testAssertLogsDefaults(self): # defaults: root logger, level INFO with self.assertNoStderr(): with self.assertLogs() as cm: log_foo.info("1") log_foobar.debug("2") self.assertEqual(cm.output, ["INFO:foo:1"]) self.assertLogRecords(cm.records, [{'name': 'foo'}]) def testAssertLogsTwoMatchingMessages(self): # Same, but with two matching log messages with self.assertNoStderr(): with self.assertLogs() as cm: log_foo.info("1") log_foobar.debug("2") log_quux.warning("3") self.assertEqual(cm.output, ["INFO:foo:1", "WARNING:quux:3"]) self.assertLogRecords(cm.records, [{'name': 'foo'}, {'name': 'quux'}]) def checkAssertLogsPerLevel(self, level): # Check level filtering with self.assertNoStderr(): with self.assertLogs(level=level) as cm: log_foo.warning("1") log_foobar.error("2") log_quux.critical("3") self.assertEqual(cm.output, ["ERROR:foo.bar:2", "CRITICAL:quux:3"]) self.assertLogRecords(cm.records, [{'name': 'foo.bar'}, {'name': 'quux'}]) def testAssertLogsPerLevel(self): self.checkAssertLogsPerLevel(logging.ERROR) self.checkAssertLogsPerLevel('ERROR') def checkAssertLogsPerLogger(self, logger): # Check per-logger filtering with self.assertNoStderr(): with self.assertLogs(level='DEBUG') as outer_cm: with self.assertLogs(logger, level='DEBUG') as cm: log_foo.info("1") log_foobar.debug("2") log_quux.warning("3") self.assertEqual(cm.output, ["INFO:foo:1", "DEBUG:foo.bar:2"]) self.assertLogRecords(cm.records, [{'name': 'foo'}, {'name': 'foo.bar'}]) # The outer catchall caught the quux log self.assertEqual(outer_cm.output, ["WARNING:quux:3"]) def testAssertLogsPerLogger(self): self.checkAssertLogsPerLogger(logging.getLogger('foo')) self.checkAssertLogsPerLogger('foo') def testAssertLogsFailureNoLogs(self): # Failure due to no logs with self.assertNoStderr(): with self.assertRaises(self.failureException): with self.assertLogs(): pass def testAssertLogsFailureLevelTooHigh(self): # Failure due to level too high with self.assertNoStderr(): with self.assertRaises(self.failureException): with self.assertLogs(level='WARNING'): log_foo.info("1") def testAssertLogsFailureMismatchingLogger(self): # Failure due to mismatching logger (and the logged message is # passed through) with self.assertLogs('quux', level='ERROR'): with self.assertRaises(self.failureException): with self.assertLogs('foo'): log_quux.error("1") def testDeprecatedMethodNames(self): """ Test that the deprecated methods raise a DeprecationWarning. See #9424. """ old = ( (self.failIfEqual, (3, 5)), (self.assertNotEquals, (3, 5)), (self.failUnlessEqual, (3, 3)), (self.assertEquals, (3, 3)), (self.failUnlessAlmostEqual, (2.0, 2.0)), (self.assertAlmostEquals, (2.0, 2.0)), (self.failIfAlmostEqual, (3.0, 5.0)), (self.assertNotAlmostEquals, (3.0, 5.0)), (self.failUnless, (True,)), (self.assert_, (True,)), (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')), (self.failIf, (False,)), (self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))), (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])), (self.assertRegexpMatches, ('bar', 'bar')), ) for meth, args in old: with self.assertWarns(DeprecationWarning): meth(*args) # disable this test for now. When the version where the fail* methods will # be removed is decided, re-enable it and update the version def _testDeprecatedFailMethods(self): """Test that the deprecated fail* methods get removed in 3.x""" if sys.version_info[:2] < (3, 3): return deprecated_names = [ 'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual', 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf', 'assertDictContainsSubset', ] for deprecated_name in deprecated_names: with self.assertRaises(AttributeError): getattr(self, deprecated_name) # remove these in 3.x def testDeepcopy(self): # Issue: 5660 class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') # This shouldn't blow up deepcopy(test) def testPickle(self): # Issue 10326 # Can't use TestCase classes defined in Test class as # pickle does not work with inner classes test = unittest.TestCase('run') for protocol in range(pickle.HIGHEST_PROTOCOL + 1): # blew up prior to fix pickled_test = pickle.dumps(test, protocol=protocol) unpickled_test = pickle.loads(pickled_test) self.assertEqual(test, unpickled_test) # exercise the TestCase instance in a way that will invoke # the type equality lookup mechanism unpickled_test.assertEqual(set(), set()) def testKeyboardInterrupt(self): def _raise(self=None): raise KeyboardInterrupt def nothing(self): pass class Test1(unittest.TestCase): test_something = _raise class Test2(unittest.TestCase): setUp = _raise test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _raise class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_raise) for klass in (Test1, Test2, Test3, Test4): with self.assertRaises(KeyboardInterrupt): klass('test_something').run() def testSkippingEverywhere(self): def _skip(self=None): raise unittest.SkipTest('some reason') def nothing(self): pass class Test1(unittest.TestCase): test_something = _skip class Test2(unittest.TestCase): setUp = _skip test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _skip class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_skip) for klass in (Test1, Test2, Test3, Test4): result = unittest.TestResult() klass('test_something').run(result) self.assertEqual(len(result.skipped), 1) self.assertEqual(result.testsRun, 1) def testSystemExit(self): def _raise(self=None): raise SystemExit def nothing(self): pass class Test1(unittest.TestCase): test_something = _raise class Test2(unittest.TestCase): setUp = _raise test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _raise class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_raise) for klass in (Test1, Test2, Test3, Test4): result = unittest.TestResult() klass('test_something').run(result) self.assertEqual(len(result.errors), 1) self.assertEqual(result.testsRun, 1) @support.cpython_only def testNoCycles(self): case = unittest.TestCase() wr = weakref.ref(case) with support.disable_gc(): del case self.assertFalse(wr()) def test_no_exception_leak(self): # Issue #19880: TestCase.run() should not keep a reference # to the exception class MyException(Exception): ninstance = 0 def __init__(self): MyException.ninstance += 1 Exception.__init__(self) def __del__(self): MyException.ninstance -= 1 class TestCase(unittest.TestCase): def test1(self): raise MyException() @unittest.expectedFailure def test2(self): raise MyException() for method_name in ('test1', 'test2'): testcase = TestCase(method_name) testcase.run() self.assertEqual(MyException.ninstance, 0) if __name__ == "__main__": unittest.main()
72,998
1,848
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_break.py
import gc import io import os import sys import signal import weakref import unittest @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreak(unittest.TestCase): int_handler = None def setUp(self): self._default_handler = signal.getsignal(signal.SIGINT) if self.int_handler is not None: signal.signal(signal.SIGINT, self.int_handler) def tearDown(self): signal.signal(signal.SIGINT, self._default_handler) unittest.signals._results = weakref.WeakKeyDictionary() unittest.signals._interrupt_handler = None def testInstallHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(unittest.signals._interrupt_handler.called) def testRegisterResult(self): result = unittest.TestResult() self.assertNotIn(result, unittest.signals._results) unittest.registerResult(result) try: self.assertIn(result, unittest.signals._results) finally: unittest.removeResult(result) def testInterruptCaught(self): default_handler = signal.getsignal(signal.SIGINT) result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.breakCaught) def testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught) def testTwoResults(self): unittest.installHandler() result = unittest.TestResult() unittest.registerResult(result) new_handler = signal.getsignal(signal.SIGINT) result2 = unittest.TestResult() unittest.registerResult(result2) self.assertEqual(signal.getsignal(signal.SIGINT), new_handler) result3 = unittest.TestResult() def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.shouldStop) self.assertTrue(result2.shouldStop) self.assertFalse(result3.shouldStop) def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt") def testRunner(self): # Creating a TextTestRunner with the appropriate argument should # register the TextTestResult it creates runner = unittest.TextTestRunner(stream=io.StringIO()) result = runner.run(unittest.TestSuite()) self.assertIn(result, unittest.signals._results) def testWeakReferences(self): # Calling registerResult on a result should not keep it alive result = unittest.TestResult() unittest.registerResult(result) ref = weakref.ref(result) del result # For non-reference counting implementations gc.collect();gc.collect() self.assertIsNone(ref()) def testRemoveResult(self): result = unittest.TestResult() unittest.registerResult(result) unittest.installHandler() self.assertTrue(unittest.removeResult(result)) # Should this raise an error instead? self.assertFalse(unittest.removeResult(unittest.TestResult())) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass self.assertFalse(result.shouldStop) def testMainInstallsHandler(self): failfast = object() test = object() verbosity = object() result = object() default_handler = signal.getsignal(signal.SIGINT) class FakeRunner(object): initArgs = [] runArgs = [] def __init__(self, *args, **kwargs): self.initArgs.append((args, kwargs)) def run(self, test): self.runArgs.append(test) return result class Program(unittest.TestProgram): def __init__(self, catchbreak): self.exit = False self.verbosity = verbosity self.failfast = failfast self.catchbreak = catchbreak self.tb_locals = False self.testRunner = FakeRunner self.test = test self.result = None p = Program(False) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast, 'tb_locals': False, 'warnings': None})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) FakeRunner.initArgs = [] FakeRunner.runArgs = [] p = Program(True) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast, 'tb_locals': False, 'warnings': None})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) # check that calling removeHandler multiple times has no ill-effect unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandlerAsDecorator(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() @unittest.removeHandler def test(): self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) test() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakDefaultIntHandler(TestBreak): int_handler = signal.default_int_handler @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakSignalIgnored(TestBreak): int_handler = signal.SIG_IGN @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakSignalDefault(TestBreak): int_handler = signal.SIG_DFL if __name__ == "__main__": unittest.main()
9,945
289
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/dummy.py
# Empty module for testing the loading of modules
50
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_setups.py
import io import sys import unittest def resultFactory(*_): return unittest.TestResult() class TestSetups(unittest.TestCase): def getRunner(self): return unittest.TextTestRunner(resultclass=resultFactory, stream=io.StringIO()) def runTests(self, *cases): suite = unittest.TestSuite() for case in cases: tests = unittest.defaultTestLoader.loadTestsFromTestCase(case) suite.addTests(tests) runner = self.getRunner() # creating a nested suite exposes some potential bugs realSuite = unittest.TestSuite() realSuite.addTest(suite) # adding empty suites to the end exposes potential bugs suite.addTest(unittest.TestSuite()) realSuite.addTest(unittest.TestSuite()) return runner.run(realSuite) def test_setup_class(self): class Test(unittest.TestCase): setUpCalled = 0 @classmethod def setUpClass(cls): Test.setUpCalled += 1 unittest.TestCase.setUpClass() def test_one(self): pass def test_two(self): pass result = self.runTests(Test) self.assertEqual(Test.setUpCalled, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_teardown_class(self): class Test(unittest.TestCase): tearDownCalled = 0 @classmethod def tearDownClass(cls): Test.tearDownCalled += 1 unittest.TestCase.tearDownClass() def test_one(self): pass def test_two(self): pass result = self.runTests(Test) self.assertEqual(Test.tearDownCalled, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_teardown_class_two_classes(self): class Test(unittest.TestCase): tearDownCalled = 0 @classmethod def tearDownClass(cls): Test.tearDownCalled += 1 unittest.TestCase.tearDownClass() def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): tearDownCalled = 0 @classmethod def tearDownClass(cls): Test2.tearDownCalled += 1 unittest.TestCase.tearDownClass() def test_one(self): pass def test_two(self): pass result = self.runTests(Test, Test2) self.assertEqual(Test.tearDownCalled, 1) self.assertEqual(Test2.tearDownCalled, 1) self.assertEqual(result.testsRun, 4) self.assertEqual(len(result.errors), 0) def test_error_in_setupclass(self): class BrokenTest(unittest.TestCase): @classmethod def setUpClass(cls): raise TypeError('foo') def test_one(self): pass def test_two(self): pass result = self.runTests(BrokenTest) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.errors), 1) error, _ = result.errors[0] self.assertEqual(str(error), 'setUpClass (%s.%s)' % (__name__, BrokenTest.__qualname__)) def test_error_in_teardown_class(self): class Test(unittest.TestCase): tornDown = 0 @classmethod def tearDownClass(cls): Test.tornDown += 1 raise TypeError('foo') def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): tornDown = 0 @classmethod def tearDownClass(cls): Test2.tornDown += 1 raise TypeError('foo') def test_one(self): pass def test_two(self): pass result = self.runTests(Test, Test2) self.assertEqual(result.testsRun, 4) self.assertEqual(len(result.errors), 2) self.assertEqual(Test.tornDown, 1) self.assertEqual(Test2.tornDown, 1) error, _ = result.errors[0] self.assertEqual(str(error), 'tearDownClass (%s.%s)' % (__name__, Test.__qualname__)) def test_class_not_torndown_when_setup_fails(self): class Test(unittest.TestCase): tornDown = False @classmethod def setUpClass(cls): raise TypeError @classmethod def tearDownClass(cls): Test.tornDown = True raise TypeError('foo') def test_one(self): pass self.runTests(Test) self.assertFalse(Test.tornDown) def test_class_not_setup_or_torndown_when_skipped(self): class Test(unittest.TestCase): classSetUp = False tornDown = False @classmethod def setUpClass(cls): Test.classSetUp = True @classmethod def tearDownClass(cls): Test.tornDown = True def test_one(self): pass Test = unittest.skip("hop")(Test) self.runTests(Test) self.assertFalse(Test.classSetUp) self.assertFalse(Test.tornDown) def test_setup_teardown_order_with_pathological_suite(self): results = [] class Module1(object): @staticmethod def setUpModule(): results.append('Module1.setUpModule') @staticmethod def tearDownModule(): results.append('Module1.tearDownModule') class Module2(object): @staticmethod def setUpModule(): results.append('Module2.setUpModule') @staticmethod def tearDownModule(): results.append('Module2.tearDownModule') class Test1(unittest.TestCase): @classmethod def setUpClass(cls): results.append('setup 1') @classmethod def tearDownClass(cls): results.append('teardown 1') def testOne(self): results.append('Test1.testOne') def testTwo(self): results.append('Test1.testTwo') class Test2(unittest.TestCase): @classmethod def setUpClass(cls): results.append('setup 2') @classmethod def tearDownClass(cls): results.append('teardown 2') def testOne(self): results.append('Test2.testOne') def testTwo(self): results.append('Test2.testTwo') class Test3(unittest.TestCase): @classmethod def setUpClass(cls): results.append('setup 3') @classmethod def tearDownClass(cls): results.append('teardown 3') def testOne(self): results.append('Test3.testOne') def testTwo(self): results.append('Test3.testTwo') Test1.__module__ = Test2.__module__ = 'Module' Test3.__module__ = 'Module2' sys.modules['Module'] = Module1 sys.modules['Module2'] = Module2 first = unittest.TestSuite((Test1('testOne'),)) second = unittest.TestSuite((Test1('testTwo'),)) third = unittest.TestSuite((Test2('testOne'),)) fourth = unittest.TestSuite((Test2('testTwo'),)) fifth = unittest.TestSuite((Test3('testOne'),)) sixth = unittest.TestSuite((Test3('testTwo'),)) suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth)) runner = self.getRunner() result = runner.run(suite) self.assertEqual(result.testsRun, 6) self.assertEqual(len(result.errors), 0) self.assertEqual(results, ['Module1.setUpModule', 'setup 1', 'Test1.testOne', 'Test1.testTwo', 'teardown 1', 'setup 2', 'Test2.testOne', 'Test2.testTwo', 'teardown 2', 'Module1.tearDownModule', 'Module2.setUpModule', 'setup 3', 'Test3.testOne', 'Test3.testTwo', 'teardown 3', 'Module2.tearDownModule']) def test_setup_module(self): class Module(object): moduleSetup = 0 @staticmethod def setUpModule(): Module.moduleSetup += 1 class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test) self.assertEqual(Module.moduleSetup, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_error_in_setup_module(self): class Module(object): moduleSetup = 0 moduleTornDown = 0 @staticmethod def setUpModule(): Module.moduleSetup += 1 raise TypeError('foo') @staticmethod def tearDownModule(): Module.moduleTornDown += 1 class Test(unittest.TestCase): classSetUp = False classTornDown = False @classmethod def setUpClass(cls): Test.classSetUp = True @classmethod def tearDownClass(cls): Test.classTornDown = True def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' Test2.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test, Test2) self.assertEqual(Module.moduleSetup, 1) self.assertEqual(Module.moduleTornDown, 0) self.assertEqual(result.testsRun, 0) self.assertFalse(Test.classSetUp) self.assertFalse(Test.classTornDown) self.assertEqual(len(result.errors), 1) error, _ = result.errors[0] self.assertEqual(str(error), 'setUpModule (Module)') def test_testcase_with_missing_module(self): class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' sys.modules.pop('Module', None) result = self.runTests(Test) self.assertEqual(result.testsRun, 2) def test_teardown_module(self): class Module(object): moduleTornDown = 0 @staticmethod def tearDownModule(): Module.moduleTornDown += 1 class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test) self.assertEqual(Module.moduleTornDown, 1) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.errors), 0) def test_error_in_teardown_module(self): class Module(object): moduleTornDown = 0 @staticmethod def tearDownModule(): Module.moduleTornDown += 1 raise TypeError('foo') class Test(unittest.TestCase): classSetUp = False classTornDown = False @classmethod def setUpClass(cls): Test.classSetUp = True @classmethod def tearDownClass(cls): Test.classTornDown = True def test_one(self): pass def test_two(self): pass class Test2(unittest.TestCase): def test_one(self): pass def test_two(self): pass Test.__module__ = 'Module' Test2.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test, Test2) self.assertEqual(Module.moduleTornDown, 1) self.assertEqual(result.testsRun, 4) self.assertTrue(Test.classSetUp) self.assertTrue(Test.classTornDown) self.assertEqual(len(result.errors), 1) error, _ = result.errors[0] self.assertEqual(str(error), 'tearDownModule (Module)') def test_skiptest_in_setupclass(self): class Test(unittest.TestCase): @classmethod def setUpClass(cls): raise unittest.SkipTest('foo') def test_one(self): pass def test_two(self): pass result = self.runTests(Test) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.skipped), 1) skipped = result.skipped[0][0] self.assertEqual(str(skipped), 'setUpClass (%s.%s)' % (__name__, Test.__qualname__)) def test_skiptest_in_setupmodule(self): class Test(unittest.TestCase): def test_one(self): pass def test_two(self): pass class Module(object): @staticmethod def setUpModule(): raise unittest.SkipTest('foo') Test.__module__ = 'Module' sys.modules['Module'] = Module result = self.runTests(Test) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.skipped), 1) skipped = result.skipped[0][0] self.assertEqual(str(skipped), 'setUpModule (Module)') def test_suite_debug_executes_setups_and_teardowns(self): ordering = [] class Module(object): @staticmethod def setUpModule(): ordering.append('setUpModule') @staticmethod def tearDownModule(): ordering.append('tearDownModule') class Test(unittest.TestCase): @classmethod def setUpClass(cls): ordering.append('setUpClass') @classmethod def tearDownClass(cls): ordering.append('tearDownClass') def test_something(self): ordering.append('test_something') Test.__module__ = 'Module' sys.modules['Module'] = Module suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test) suite.debug() expectedOrder = ['setUpModule', 'setUpClass', 'test_something', 'tearDownClass', 'tearDownModule'] self.assertEqual(ordering, expectedOrder) def test_suite_debug_propagates_exceptions(self): class Module(object): @staticmethod def setUpModule(): if phase == 0: raise Exception('setUpModule') @staticmethod def tearDownModule(): if phase == 1: raise Exception('tearDownModule') class Test(unittest.TestCase): @classmethod def setUpClass(cls): if phase == 2: raise Exception('setUpClass') @classmethod def tearDownClass(cls): if phase == 3: raise Exception('tearDownClass') def test_something(self): if phase == 4: raise Exception('test_something') Test.__module__ = 'Module' sys.modules['Module'] = Module messages = ('setUpModule', 'tearDownModule', 'setUpClass', 'tearDownClass', 'test_something') for phase, msg in enumerate(messages): _suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test) suite = unittest.TestSuite([_suite]) with self.assertRaisesRegex(Exception, msg): suite.debug() if __name__ == '__main__': unittest.main()
16,503
508
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_loader.py
import sys import types import warnings import unittest # Decorator used in the deprecation tests to reset the warning registry for # test isolation and reproducibility. def warningregistry(func): def wrapper(*args, **kws): missing = [] saved = getattr(warnings, '__warningregistry__', missing).copy() try: return func(*args, **kws) finally: if saved is missing: try: del warnings.__warningregistry__ except AttributeError: pass else: warnings.__warningregistry__ = saved return wrapper class Test_TestLoader(unittest.TestCase): ### Basic object tests ################################################################ def test___init__(self): loader = unittest.TestLoader() self.assertEqual([], loader.errors) ### Tests for TestLoader.loadTestsFromTestCase ################################################################ # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" def test_loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" # # Make sure it does the right thing even if no tests were found def test_loadTestsFromTestCase__no_matches(self): class Foo(unittest.TestCase): def foo_bar(self): pass empty_suite = unittest.TestSuite() loader = unittest.TestLoader() self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite) # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" # # What happens if loadTestsFromTestCase() is given an object # that isn't a subclass of TestCase? Specifically, what happens # if testCaseClass is a subclass of TestSuite? # # This is checked for specifically in the code, so we better add a # test for it. def test_loadTestsFromTestCase__TestSuite_subclass(self): class NotATestCase(unittest.TestSuite): pass loader = unittest.TestLoader() try: loader.loadTestsFromTestCase(NotATestCase) except TypeError: pass else: self.fail('Should raise TypeError') # "Return a suite of all test cases contained in the TestCase-derived # class testCaseClass" # # Make sure loadTestsFromTestCase() picks up the default test method # name (as specified by TestCase), even though the method name does # not match the default TestLoader.testMethodPrefix string def test_loadTestsFromTestCase__default_method_name(self): class Foo(unittest.TestCase): def runTest(self): pass loader = unittest.TestLoader() # This has to be false for the test to succeed self.assertFalse('runTest'.startswith(loader.testMethodPrefix)) suite = loader.loadTestsFromTestCase(Foo) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [Foo('runTest')]) ################################################################ ### /Tests for TestLoader.loadTestsFromTestCase ### Tests for TestLoader.loadTestsFromModule ################################################################ # "This method searches `module` for classes derived from TestCase" def test_loadTestsFromModule__TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) expected = [loader.suiteClass([MyTestCase('test')])] self.assertEqual(list(suite), expected) # "This method searches `module` for classes derived from TestCase" # # What happens if no tests are found (no TestCase instances)? def test_loadTestsFromModule__no_TestCase_instances(self): m = types.ModuleType('m') loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "This method searches `module` for classes derived from TestCase" # # What happens if no tests are found (TestCases instances, but no tests)? def test_loadTestsFromModule__no_TestCase_tests(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [loader.suiteClass()]) # "This method searches `module` for classes derived from TestCase"s # # What happens if loadTestsFromModule() is given something other # than a module? # # XXX Currently, it succeeds anyway. This flexibility # should either be documented or loadTestsFromModule() should # raise a TypeError # # XXX Certain people are using this behaviour. We'll add a test for it def test_loadTestsFromModule__not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(NotAModule) reference = [unittest.TestSuite([MyTestCase('test')])] self.assertEqual(list(suite), reference) # Check that loadTestsFromModule honors (or not) a module # with a load_tests function. @warningregistry def test_loadTestsFromModule__load_tests(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(load_tests_args, [loader, suite, None]) # With Python 3.5, the undocumented and unofficial use_load_tests is # ignored (and deprecated). load_tests_args = [] with warnings.catch_warnings(record=False): warnings.simplefilter('ignore') suite = loader.loadTestsFromModule(m, use_load_tests=False) self.assertEqual(load_tests_args, [loader, suite, None]) @warningregistry def test_loadTestsFromModule__use_load_tests_deprecated_positional(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests # The method still works. loader = unittest.TestLoader() # use_load_tests=True as a positional argument. with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') suite = loader.loadTestsFromModule(m, False) self.assertIsInstance(suite, unittest.TestSuite) # load_tests was still called because use_load_tests is deprecated # and ignored. self.assertEqual(load_tests_args, [loader, suite, None]) # We got a warning. self.assertIs(w[-1].category, DeprecationWarning) self.assertEqual(str(w[-1].message), 'use_load_tests is deprecated and ignored') @warningregistry def test_loadTestsFromModule__use_load_tests_deprecated_keyword(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests # The method still works. loader = unittest.TestLoader() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') suite = loader.loadTestsFromModule(m, use_load_tests=False) self.assertIsInstance(suite, unittest.TestSuite) # load_tests was still called because use_load_tests is deprecated # and ignored. self.assertEqual(load_tests_args, [loader, suite, None]) # We got a warning. self.assertIs(w[-1].category, DeprecationWarning) self.assertEqual(str(w[-1].message), 'use_load_tests is deprecated and ignored') @warningregistry def test_loadTestsFromModule__too_many_positional_args(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests loader = unittest.TestLoader() with self.assertRaises(TypeError) as cm, \ warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') loader.loadTestsFromModule(m, False, 'testme.*') # We still got the deprecation warning. self.assertIs(w[-1].category, DeprecationWarning) self.assertEqual(str(w[-1].message), 'use_load_tests is deprecated and ignored') # We also got a TypeError for too many positional arguments. self.assertEqual(type(cm.exception), TypeError) self.assertEqual( str(cm.exception), 'loadTestsFromModule() takes 1 positional argument but 3 were given') @warningregistry def test_loadTestsFromModule__use_load_tests_other_bad_keyword(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests loader = unittest.TestLoader() with warnings.catch_warnings(): warnings.simplefilter('ignore') with self.assertRaises(TypeError) as cm: loader.loadTestsFromModule( m, use_load_tests=False, very_bad=True, worse=False) self.assertEqual(type(cm.exception), TypeError) # The error message names the first bad argument alphabetically, # however use_load_tests (which sorts first) is ignored. self.assertEqual( str(cm.exception), "loadTestsFromModule() got an unexpected keyword argument 'very_bad'") def test_loadTestsFromModule__pattern(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m, pattern='testme.*') self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(load_tests_args, [loader, suite, 'testme.*']) def test_loadTestsFromModule__faulty_load_tests(self): m = types.ModuleType('m') def load_tests(loader, tests, pattern): raise TypeError('some failure') m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(suite.countTestCases(), 1) # Errors loading the suite are also captured for introspection. self.assertNotEqual([], loader.errors) self.assertEqual(1, len(loader.errors)) error = loader.errors[0] self.assertTrue( 'Failed to call load_tests:' in error, 'missing error string in %r' % error) test = list(suite)[0] self.assertRaisesRegex(TypeError, "some failure", test.m) ################################################################ ### /Tests for TestLoader.loadTestsFromModule() ### Tests for TestLoader.loadTestsFromName() ################################################################ # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Is ValueError raised in response to an empty name? def test_loadTestsFromName__empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('') except ValueError as e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the name contains invalid characters? def test_loadTestsFromName__malformed_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromName('abc () //') error, test = self.check_deferred_error(loader, suite) expected = "Failed to import test module: abc () //" expected_regex = r"Failed to import test module: abc \(\) //" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex( ImportError, expected_regex, getattr(test, 'abc () //')) # "The specifier name is a ``dotted name'' that may resolve ... to a # module" # # What happens when a module by that name can't be found? def test_loadTestsFromName__unknown_module_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromName('sdasfasfasdf') expected = "No module named 'sdasfasfasdf'" error, test = self.check_deferred_error(loader, suite) self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(ImportError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module is found, but the attribute isn't? def test_loadTestsFromName__unknown_attr_name_on_module(self): loader = unittest.TestLoader() suite = loader.loadTestsFromName('unittest.loader.sdasfasfasdf') expected = "module 'unittest.loader' has no attribute 'sdasfasfasdf'" error, test = self.check_deferred_error(loader, suite) self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module is found, but the attribute isn't? def test_loadTestsFromName__unknown_attr_name_on_package(self): loader = unittest.TestLoader() suite = loader.loadTestsFromName('unittest.sdasfasfasdf') expected = "No module named 'unittest.sdasfasfasdf'" error, test = self.check_deferred_error(loader, suite) self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(ImportError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when we provide the module, but the attribute can't be # found? def test_loadTestsFromName__relative_unknown_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromName('sdasfasfasdf', unittest) expected = "module 'unittest' has no attribute 'sdasfasfasdf'" error, test = self.check_deferred_error(loader, suite) self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # Does loadTestsFromName raise ValueError when passed an empty # name relative to a provided module? # # XXX Should probably raise a ValueError instead of an AttributeError def test_loadTestsFromName__relative_empty_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromName('', unittest) error, test = self.check_deferred_error(loader, suite) expected = "has no attribute ''" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, getattr(test, '')) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when an impossible name is given, relative to the provided # `module`? def test_loadTestsFromName__relative_malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise AttributeError or ValueError? suite = loader.loadTestsFromName('abc () //', unittest) error, test = self.check_deferred_error(loader, suite) expected = "module 'unittest' has no attribute 'abc () //'" expected_regex = r"module 'unittest' has no attribute 'abc \(\) //'" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex( AttributeError, expected_regex, getattr(test, 'abc () //')) # "The method optionally resolves name relative to the given module" # # Does loadTestsFromName raise TypeError when the `module` argument # isn't a module object? # # XXX Accepts the not-a-module object, ignoring the object's type # This should raise an exception or the method name should be changed # # XXX Some people are relying on this, so keep it for now def test_loadTestsFromName__relative_not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('test_2', NotAModule) reference = [MyTestCase('test')] self.assertEqual(list(suite), reference) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does it raise an exception if the name resolves to an invalid # object? def test_loadTestsFromName__relative_bad_object(self): m = types.ModuleType('m') m.testcase_1 = object() loader = unittest.TestLoader() try: loader.loadTestsFromName('testcase_1', m) except TypeError: pass else: self.fail("Should have raised TypeError") # "The specifier name is a ``dotted name'' that may # resolve either to ... a test case class" def test_loadTestsFromName__relative_TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." def test_loadTestsFromName__relative_TestSuite(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testsuite = unittest.TestSuite([MyTestCase('test')]) loader = unittest.TestLoader() suite = loader.loadTestsFromName('testsuite', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test method within a test case class" def test_loadTestsFromName__relative_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1.test', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does loadTestsFromName() raise the proper exception when trying to # resolve "a test method within a test case class" that doesn't exist # for the given name (relative to a provided module)? def test_loadTestsFromName__relative_invalid_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1.testfoo', m) expected = "type object 'MyTestCase' has no attribute 'testfoo'" error, test = self.check_deferred_error(loader, suite) self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.testfoo) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a ... TestSuite instance" def test_loadTestsFromName__callable__TestSuite(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) testcase_2 = unittest.FunctionTestCase(lambda: None) def return_TestSuite(): return unittest.TestSuite([testcase_1, testcase_2]) m.return_TestSuite = return_TestSuite loader = unittest.TestLoader() suite = loader.loadTestsFromName('return_TestSuite', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1, testcase_2]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" def test_loadTestsFromName__callable__TestCase_instance(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('return_TestCase', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" #***************************************************************** #Override the suiteClass attribute to ensure that the suiteClass #attribute is used def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self): class SubTestSuite(unittest.TestSuite): pass m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() loader.suiteClass = SubTestSuite suite = loader.loadTestsFromName('return_TestCase', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test method within a test case class" #***************************************************************** #Override the suiteClass attribute to ensure that the suiteClass #attribute is used def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self): class SubTestSuite(unittest.TestSuite): pass m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() loader.suiteClass=SubTestSuite suite = loader.loadTestsFromName('testcase_1.test', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # What happens if the callable returns something else? def test_loadTestsFromName__callable__wrong_type(self): m = types.ModuleType('m') def return_wrong(): return 6 m.return_wrong = return_wrong loader = unittest.TestLoader() try: suite = loader.loadTestsFromName('return_wrong', m) except TypeError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise TypeError") # "The specifier can refer to modules and packages which have not been # imported; they will be imported as a side-effect" def test_loadTestsFromName__module_not_loaded(self): # We're going to try to load this module as a side-effect, so it # better not be loaded before we try. # module_name = 'unittest.test.dummy' sys.modules.pop(module_name, None) loader = unittest.TestLoader() try: suite = loader.loadTestsFromName(module_name) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # module should now be loaded, thanks to loadTestsFromName() self.assertIn(module_name, sys.modules) finally: if module_name in sys.modules: del sys.modules[module_name] ################################################################ ### Tests for TestLoader.loadTestsFromName() ### Tests for TestLoader.loadTestsFromNames() ################################################################ def check_deferred_error(self, loader, suite): """Helper function for checking that errors in loading are reported. :param loader: A loader with some errors. :param suite: A suite that should have a late bound error. :return: The first error message from the loader and the test object from the suite. """ self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(suite.countTestCases(), 1) # Errors loading the suite are also captured for introspection. self.assertNotEqual([], loader.errors) self.assertEqual(1, len(loader.errors)) error = loader.errors[0] test = list(suite)[0] return error, test # "Similar to loadTestsFromName(), but takes a sequence of names rather # than a single name." # # What happens if that sequence of names is empty? def test_loadTestsFromNames__empty_name_list(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([]) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "Similar to loadTestsFromName(), but takes a sequence of names rather # than a single name." # ... # "The method optionally resolves name relative to the given module" # # What happens if that sequence of names is empty? # # XXX Should this raise a ValueError or just return an empty TestSuite? def test_loadTestsFromNames__relative_empty_name_list(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([], unittest) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Is ValueError raised in response to an empty name? def test_loadTestsFromNames__empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['']) except ValueError as e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when presented with an impossible module name? def test_loadTestsFromNames__malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise ValueError or ImportError? suite = loader.loadTestsFromNames(['abc () //']) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "Failed to import test module: abc () //" expected_regex = r"Failed to import test module: abc \(\) //" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex( ImportError, expected_regex, getattr(test, 'abc () //')) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when no module can be found for the given name? def test_loadTestsFromNames__unknown_module_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['sdasfasfasdf']) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "Failed to import test module: sdasfasfasdf" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(ImportError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module can be found, but not the attribute? def test_loadTestsFromNames__unknown_attr_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames( ['unittest.loader.sdasfasfasdf', 'unittest.test.dummy']) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "module 'unittest.loader' has no attribute 'sdasfasfasdf'" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when given an unknown attribute on a specified `module` # argument? def test_loadTestsFromNames__unknown_name_relative_1(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['sdasfasfasdf'], unittest) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "module 'unittest' has no attribute 'sdasfasfasdf'" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # Do unknown attributes (relative to a provided module) still raise an # exception even in the presence of valid attribute names? def test_loadTestsFromNames__unknown_name_relative_2(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) error, test = self.check_deferred_error(loader, list(suite)[1]) expected = "module 'unittest' has no attribute 'sdasfasfasdf'" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.sdasfasfasdf) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when faced with the empty string? # # XXX This currently raises AttributeError, though ValueError is probably # more appropriate def test_loadTestsFromNames__relative_empty_name(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([''], unittest) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "has no attribute ''" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, getattr(test, '')) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when presented with an impossible attribute name? def test_loadTestsFromNames__relative_malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise AttributeError or ValueError? suite = loader.loadTestsFromNames(['abc () //'], unittest) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "module 'unittest' has no attribute 'abc () //'" expected_regex = r"module 'unittest' has no attribute 'abc \(\) //'" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex( AttributeError, expected_regex, getattr(test, 'abc () //')) # "The method optionally resolves name relative to the given module" # # Does loadTestsFromNames() make sure the provided `module` is in fact # a module? # # XXX This validation is currently not done. This flexibility should # either be documented or a TypeError should be raised. def test_loadTestsFromNames__relative_not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['test_2'], NotAModule) reference = [unittest.TestSuite([MyTestCase('test')])] self.assertEqual(list(suite), reference) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does it raise an exception if the name resolves to an invalid # object? def test_loadTestsFromNames__relative_bad_object(self): m = types.ModuleType('m') m.testcase_1 = object() loader = unittest.TestLoader() try: loader.loadTestsFromNames(['testcase_1'], m) except TypeError: pass else: self.fail("Should have raised TypeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test case class" def test_loadTestsFromNames__relative_TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1'], m) self.assertIsInstance(suite, loader.suiteClass) expected = loader.suiteClass([MyTestCase('test')]) self.assertEqual(list(suite), [expected]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a TestSuite instance" def test_loadTestsFromNames__relative_TestSuite(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testsuite = unittest.TestSuite([MyTestCase('test')]) loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testsuite'], m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [m.testsuite]) # "The specifier name is a ``dotted name'' that may resolve ... to ... a # test method within a test case class" def test_loadTestsFromNames__relative_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1.test'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([MyTestCase('test')]) self.assertEqual(list(suite), [ref_suite]) # #14971: Make sure the dotted name resolution works even if the actual # function doesn't have the same name as is used to find it. def test_loadTestsFromName__function_with_different_name_than_method(self): # lambdas have the name '<lambda>'. m = types.ModuleType('m') class MyTestCase(unittest.TestCase): test = lambda: 1 m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1.test'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([MyTestCase('test')]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to ... a # test method within a test case class" # # Does the method gracefully handle names that initially look like they # resolve to "a test method within a test case class" but don't? def test_loadTestsFromNames__relative_invalid_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1.testfoo'], m) error, test = self.check_deferred_error(loader, list(suite)[0]) expected = "type object 'MyTestCase' has no attribute 'testfoo'" self.assertIn( expected, error, 'missing error string in %r' % error) self.assertRaisesRegex(AttributeError, expected, test.testfoo) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a ... TestSuite instance" def test_loadTestsFromNames__callable__TestSuite(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) testcase_2 = unittest.FunctionTestCase(lambda: None) def return_TestSuite(): return unittest.TestSuite([testcase_1, testcase_2]) m.return_TestSuite = return_TestSuite loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['return_TestSuite'], m) self.assertIsInstance(suite, loader.suiteClass) expected = unittest.TestSuite([testcase_1, testcase_2]) self.assertEqual(list(suite), [expected]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" def test_loadTestsFromNames__callable__TestCase_instance(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['return_TestCase'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([testcase_1]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # Are staticmethods handled correctly? def test_loadTestsFromNames__callable__call_staticmethod(self): m = types.ModuleType('m') class Test1(unittest.TestCase): def test(self): pass testcase_1 = Test1('test') class Foo(unittest.TestCase): @staticmethod def foo(): return testcase_1 m.Foo = Foo loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['Foo.foo'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([testcase_1]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # What happens when the callable returns something else? def test_loadTestsFromNames__callable__wrong_type(self): m = types.ModuleType('m') def return_wrong(): return 6 m.return_wrong = return_wrong loader = unittest.TestLoader() try: suite = loader.loadTestsFromNames(['return_wrong'], m) except TypeError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") # "The specifier can refer to modules and packages which have not been # imported; they will be imported as a side-effect" def test_loadTestsFromNames__module_not_loaded(self): # We're going to try to load this module as a side-effect, so it # better not be loaded before we try. # module_name = 'unittest.test.dummy' sys.modules.pop(module_name, None) loader = unittest.TestLoader() try: suite = loader.loadTestsFromNames([module_name]) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [unittest.TestSuite()]) # module should now be loaded, thanks to loadTestsFromName() self.assertIn(module_name, sys.modules) finally: if module_name in sys.modules: del sys.modules[module_name] ################################################################ ### /Tests for TestLoader.loadTestsFromNames() ### Tests for TestLoader.getTestCaseNames() ################################################################ # "Return a sorted sequence of method names found within testCaseClass" # # Test.foobar is defined to make sure getTestCaseNames() respects # loader.testMethodPrefix def test_getTestCaseNames(self): class Test(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foobar(self): pass loader = unittest.TestLoader() self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2']) # "Return a sorted sequence of method names found within testCaseClass" # # Does getTestCaseNames() behave appropriately if no tests are found? def test_getTestCaseNames__no_tests(self): class Test(unittest.TestCase): def foobar(self): pass loader = unittest.TestLoader() self.assertEqual(loader.getTestCaseNames(Test), []) # "Return a sorted sequence of method names found within testCaseClass" # # Are not-TestCases handled gracefully? # # XXX This should raise a TypeError, not return a list # # XXX It's too late in the 2.5 release cycle to fix this, but it should # probably be revisited for 2.6 def test_getTestCaseNames__not_a_TestCase(self): class BadCase(int): def test_foo(self): pass loader = unittest.TestLoader() names = loader.getTestCaseNames(BadCase) self.assertEqual(names, ['test_foo']) # "Return a sorted sequence of method names found within testCaseClass" # # Make sure inherited names are handled. # # TestP.foobar is defined to make sure getTestCaseNames() respects # loader.testMethodPrefix def test_getTestCaseNames__inheritance(self): class TestP(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foobar(self): pass class TestC(TestP): def test_1(self): pass def test_3(self): pass loader = unittest.TestLoader() names = ['test_1', 'test_2', 'test_3'] self.assertEqual(loader.getTestCaseNames(TestC), names) ################################################################ ### /Tests for TestLoader.getTestCaseNames() ### Tests for TestLoader.testMethodPrefix ################################################################ # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests_1 = unittest.TestSuite([Foo('foo_bar')]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromModule(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = [unittest.TestSuite([Foo('foo_bar')])] tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])] loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromName(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = unittest.TestSuite([Foo('foo_bar')]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromNames(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) tests_2 = unittest.TestSuite([tests_2]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2) # "The default value is 'test'" def test_testMethodPrefix__default_value(self): loader = unittest.TestLoader() self.assertEqual(loader.testMethodPrefix, 'test') ################################################################ ### /Tests for TestLoader.testMethodPrefix ### Tests for TestLoader.sortTestMethodsUsing ################################################################ # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromTestCase(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromModule(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] self.assertEqual(list(loader.loadTestsFromModule(m)), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromName(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) self.assertEqual(loader.loadTestsFromName('Foo', m), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromNames(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames()" # # Does it actually affect getTestCaseNames()? def test_sortTestMethodsUsing__getTestCaseNames(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp test_names = ['test_2', 'test_1'] self.assertEqual(loader.getTestCaseNames(Foo), test_names) # "The default value is the built-in cmp() function" # Since cmp is now defunct, we simply verify that the results # occur in the same order as they would with the default sort. def test_sortTestMethodsUsing__default_value(self): loader = unittest.TestLoader() class Foo(unittest.TestCase): def test_2(self): pass def test_3(self): pass def test_1(self): pass test_names = ['test_2', 'test_3', 'test_1'] self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names)) # "it can be set to None to disable the sort." # # XXX How is this different from reassigning cmp? Are the tests returned # in a random order or something? This behaviour should die def test_sortTestMethodsUsing__None(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = None test_names = ['test_2', 'test_1'] self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names)) ################################################################ ### /Tests for TestLoader.sortTestMethodsUsing ### Tests for TestLoader.suiteClass ################################################################ # "Callable object that constructs a test suite from a list of tests." def test_suiteClass__loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests = [Foo('test_1'), Foo('test_2')] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromModule(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [[Foo('test_1'), Foo('test_2')]] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromModule(m), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromName(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [Foo('test_1'), Foo('test_2')] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromName('Foo', m), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromNames(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [[Foo('test_1'), Foo('test_2')]] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests) # "The default value is the TestSuite class" def test_suiteClass__default_value(self): loader = unittest.TestLoader() self.assertIs(loader.suiteClass, unittest.TestSuite) if __name__ == "__main__": unittest.main()
60,769
1,530
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_assertions.py
import datetime import warnings import weakref import unittest from itertools import product class Test_Assertions(unittest.TestCase): def test_AlmostEqual(self): self.assertAlmostEqual(1.00000001, 1.0) self.assertNotAlmostEqual(1.0000001, 1.0) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.0000001, 1.0) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.00000001, 1.0) self.assertAlmostEqual(1.1, 1.0, places=0) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.1, 1.0, places=1) self.assertAlmostEqual(0, .1+.1j, places=0) self.assertNotAlmostEqual(0, .1+.1j, places=1) self.assertRaises(self.failureException, self.assertAlmostEqual, 0, .1+.1j, places=1) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 0, .1+.1j, places=0) self.assertAlmostEqual(float('inf'), float('inf')) self.assertRaises(self.failureException, self.assertNotAlmostEqual, float('inf'), float('inf')) def test_AmostEqualWithDelta(self): self.assertAlmostEqual(1.1, 1.0, delta=0.5) self.assertAlmostEqual(1.0, 1.1, delta=0.5) self.assertNotAlmostEqual(1.1, 1.0, delta=0.05) self.assertNotAlmostEqual(1.0, 1.1, delta=0.05) self.assertAlmostEqual(1.0, 1.0, delta=0.5) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.0, 1.0, delta=0.5) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.1, 1.0, delta=0.05) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.1, 1.0, delta=0.5) self.assertRaises(TypeError, self.assertAlmostEqual, 1.1, 1.0, places=2, delta=2) self.assertRaises(TypeError, self.assertNotAlmostEqual, 1.1, 1.0, places=2, delta=2) first = datetime.datetime.now() second = first + datetime.timedelta(seconds=10) self.assertAlmostEqual(first, second, delta=datetime.timedelta(seconds=20)) self.assertNotAlmostEqual(first, second, delta=datetime.timedelta(seconds=5)) def test_assertRaises(self): def _raise(e): raise e self.assertRaises(KeyError, _raise, KeyError) self.assertRaises(KeyError, _raise, KeyError("key")) try: self.assertRaises(KeyError, lambda: None) except self.failureException as e: self.assertIn("KeyError not raised", str(e)) else: self.fail("assertRaises() didn't fail") try: self.assertRaises(KeyError, _raise, ValueError) except ValueError: pass else: self.fail("assertRaises() didn't let exception pass through") with self.assertRaises(KeyError) as cm: try: raise KeyError except Exception as e: exc = e raise self.assertIs(cm.exception, exc) with self.assertRaises(KeyError): raise KeyError("key") try: with self.assertRaises(KeyError): pass except self.failureException as e: self.assertIn("KeyError not raised", str(e)) else: self.fail("assertRaises() didn't fail") try: with self.assertRaises(KeyError): raise ValueError except ValueError: pass else: self.fail("assertRaises() didn't let exception pass through") def test_assertRaises_frames_survival(self): # Issue #9815: assertRaises should avoid keeping local variables # in a traceback alive. class A: pass wr = None class Foo(unittest.TestCase): def foo(self): nonlocal wr a = A() wr = weakref.ref(a) try: raise IOError except IOError: raise ValueError def test_functional(self): self.assertRaises(ValueError, self.foo) def test_with(self): with self.assertRaises(ValueError): self.foo() Foo("test_functional").run() self.assertIsNone(wr()) Foo("test_with").run() self.assertIsNone(wr()) def testAssertNotRegex(self): self.assertNotRegex('Ala ma kota', r'r+') try: self.assertNotRegex('Ala ma kota', r'k.t', 'Message') except self.failureException as e: self.assertIn('Message', e.args[0]) else: self.fail('assertNotRegex should have failed.') class TestLongMessage(unittest.TestCase): """Test that the individual asserts honour longMessage. This actually tests all the message behaviour for asserts that use longMessage.""" def setUp(self): class TestableTestFalse(unittest.TestCase): longMessage = False failureException = self.failureException def testTest(self): pass class TestableTestTrue(unittest.TestCase): longMessage = True failureException = self.failureException def testTest(self): pass self.testableTrue = TestableTestTrue('testTest') self.testableFalse = TestableTestFalse('testTest') def testDefault(self): self.assertTrue(unittest.TestCase.longMessage) def test_formatMsg(self): self.assertEqual(self.testableFalse._formatMessage(None, "foo"), "foo") self.assertEqual(self.testableFalse._formatMessage("foo", "bar"), "foo") self.assertEqual(self.testableTrue._formatMessage(None, "foo"), "foo") self.assertEqual(self.testableTrue._formatMessage("foo", "bar"), "bar : foo") # This blows up if _formatMessage uses string concatenation self.testableTrue._formatMessage(object(), 'foo') def test_formatMessage_unicode_error(self): one = ''.join(chr(i) for i in range(255)) # this used to cause a UnicodeDecodeError constructing msg self.testableTrue._formatMessage(one, '\uFFFD') def assertMessages(self, methodName, args, errors): """ Check that methodName(*args) raises the correct error messages. errors should be a list of 4 regex that match the error when: 1) longMessage = False and no msg passed; 2) longMessage = False and msg passed; 3) longMessage = True and no msg passed; 4) longMessage = True and msg passed; """ def getMethod(i): useTestableFalse = i < 2 if useTestableFalse: test = self.testableFalse else: test = self.testableTrue return getattr(test, methodName) for i, expected_regex in enumerate(errors): testMethod = getMethod(i) kwargs = {} withMsg = i % 2 if withMsg: kwargs = {"msg": "oops"} with self.assertRaisesRegex(self.failureException, expected_regex=expected_regex): testMethod(*args, **kwargs) def testAssertTrue(self): self.assertMessages('assertTrue', (False,), ["^False is not true$", "^oops$", "^False is not true$", "^False is not true : oops$"]) def testAssertFalse(self): self.assertMessages('assertFalse', (True,), ["^True is not false$", "^oops$", "^True is not false$", "^True is not false : oops$"]) def testNotEqual(self): self.assertMessages('assertNotEqual', (1, 1), ["^1 == 1$", "^oops$", "^1 == 1$", "^1 == 1 : oops$"]) def testAlmostEqual(self): self.assertMessages('assertAlmostEqual', (1, 2), ["^1 != 2 within 7 places$", "^oops$", "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"]) def testNotAlmostEqual(self): self.assertMessages('assertNotAlmostEqual', (1, 1), ["^1 == 1 within 7 places$", "^oops$", "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"]) def test_baseAssertEqual(self): self.assertMessages('_baseAssertEqual', (1, 2), ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"]) def testAssertSequenceEqual(self): # Error messages are multiline so not testing on full message # assertTupleEqual and assertListEqual delegate to this method self.assertMessages('assertSequenceEqual', ([], [None]), [r"\+ \[None\]$", "^oops$", r"\+ \[None\]$", r"\+ \[None\] : oops$"]) def testAssertSetEqual(self): self.assertMessages('assertSetEqual', (set(), set([None])), ["None$", "^oops$", "None$", "None : oops$"]) def testAssertIn(self): self.assertMessages('assertIn', (None, []), [r'^None not found in \[\]$', "^oops$", r'^None not found in \[\]$', r'^None not found in \[\] : oops$']) def testAssertNotIn(self): self.assertMessages('assertNotIn', (None, [None]), [r'^None unexpectedly found in \[None\]$', "^oops$", r'^None unexpectedly found in \[None\]$', r'^None unexpectedly found in \[None\] : oops$']) def testAssertDictEqual(self): self.assertMessages('assertDictEqual', ({}, {'key': 'value'}), [r"\+ \{'key': 'value'\}$", "^oops$", r"\+ \{'key': 'value'\}$", r"\+ \{'key': 'value'\} : oops$"]) def testAssertDictContainsSubset(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}), ["^Missing: 'key'$", "^oops$", "^Missing: 'key'$", "^Missing: 'key' : oops$"]) def testAssertMultiLineEqual(self): self.assertMessages('assertMultiLineEqual', ("", "foo"), [r"\+ foo$", "^oops$", r"\+ foo$", r"\+ foo : oops$"]) def testAssertLess(self): self.assertMessages('assertLess', (2, 1), ["^2 not less than 1$", "^oops$", "^2 not less than 1$", "^2 not less than 1 : oops$"]) def testAssertLessEqual(self): self.assertMessages('assertLessEqual', (2, 1), ["^2 not less than or equal to 1$", "^oops$", "^2 not less than or equal to 1$", "^2 not less than or equal to 1 : oops$"]) def testAssertGreater(self): self.assertMessages('assertGreater', (1, 2), ["^1 not greater than 2$", "^oops$", "^1 not greater than 2$", "^1 not greater than 2 : oops$"]) def testAssertGreaterEqual(self): self.assertMessages('assertGreaterEqual', (1, 2), ["^1 not greater than or equal to 2$", "^oops$", "^1 not greater than or equal to 2$", "^1 not greater than or equal to 2 : oops$"]) def testAssertIsNone(self): self.assertMessages('assertIsNone', ('not None',), ["^'not None' is not None$", "^oops$", "^'not None' is not None$", "^'not None' is not None : oops$"]) def testAssertIsNotNone(self): self.assertMessages('assertIsNotNone', (None,), ["^unexpectedly None$", "^oops$", "^unexpectedly None$", "^unexpectedly None : oops$"]) def testAssertIs(self): self.assertMessages('assertIs', (None, 'foo'), ["^None is not 'foo'$", "^oops$", "^None is not 'foo'$", "^None is not 'foo' : oops$"]) def testAssertIsNot(self): self.assertMessages('assertIsNot', (None, None), ["^unexpectedly identical: None$", "^oops$", "^unexpectedly identical: None$", "^unexpectedly identical: None : oops$"]) def testAssertRegex(self): self.assertMessages('assertRegex', ('foo', 'bar'), ["^Regex didn't match:", "^oops$", "^Regex didn't match:", "^Regex didn't match: (.*) : oops$"]) def testAssertNotRegex(self): self.assertMessages('assertNotRegex', ('foo', 'foo'), ["^Regex matched:", "^oops$", "^Regex matched:", "^Regex matched: (.*) : oops$"]) def assertMessagesCM(self, methodName, args, func, errors): """ Check that the correct error messages are raised while executing: with method(*args): func() *errors* should be a list of 4 regex that match the error when: 1) longMessage = False and no msg passed; 2) longMessage = False and msg passed; 3) longMessage = True and no msg passed; 4) longMessage = True and msg passed; """ p = product((self.testableFalse, self.testableTrue), ({}, {"msg": "oops"})) for (cls, kwargs), err in zip(p, errors): method = getattr(cls, methodName) with self.assertRaisesRegex(cls.failureException, err): with method(*args, **kwargs) as cm: func() def testAssertRaises(self): self.assertMessagesCM('assertRaises', (TypeError,), lambda: None, ['^TypeError not raised$', '^oops$', '^TypeError not raised$', '^TypeError not raised : oops$']) def testAssertRaisesRegex(self): # test error not raised self.assertMessagesCM('assertRaisesRegex', (TypeError, 'unused regex'), lambda: None, ['^TypeError not raised$', '^oops$', '^TypeError not raised$', '^TypeError not raised : oops$']) # test error raised but with wrong message def raise_wrong_message(): raise TypeError('foo') self.assertMessagesCM('assertRaisesRegex', (TypeError, 'regex'), raise_wrong_message, ['^"regex" does not match "foo"$', '^oops$', '^"regex" does not match "foo"$', '^"regex" does not match "foo" : oops$']) def testAssertWarns(self): self.assertMessagesCM('assertWarns', (UserWarning,), lambda: None, ['^UserWarning not triggered$', '^oops$', '^UserWarning not triggered$', '^UserWarning not triggered : oops$']) def testAssertWarnsRegex(self): # test error not raised self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'unused regex'), lambda: None, ['^UserWarning not triggered$', '^oops$', '^UserWarning not triggered$', '^UserWarning not triggered : oops$']) # test warning raised but with wrong message def raise_wrong_message(): warnings.warn('foo') self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'regex'), raise_wrong_message, ['^"regex" does not match "foo"$', '^oops$', '^"regex" does not match "foo"$', '^"regex" does not match "foo" : oops$']) if __name__ == "__main__": unittest.main()
17,030
412
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_functiontestcase.py
import unittest from unittest.test.support import LoggingResult class Test_FunctionTestCase(unittest.TestCase): # "Return the number of tests represented by the this test object. For # TestCase instances, this will always be 1" def test_countTestCases(self): test = unittest.FunctionTestCase(lambda: None) self.assertEqual(test.countTestCases(), 1) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if setUp() raises # an exception. def test_run_call_order__error_in_setUp(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') raise RuntimeError('raised by setUp') def test(): events.append('test') def tearDown(): events.append('tearDown') expected = ['startTest', 'setUp', 'addError', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test raises # an error (as opposed to a failure). def test_run_call_order__error_in_test(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') def test(): events.append('test') raise RuntimeError('raised by test') def tearDown(): events.append('tearDown') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test signals # a failure (as opposed to an error). def test_run_call_order__failure_in_test(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') def test(): events.append('test') self.fail('raised by test') def tearDown(): events.append('tearDown') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addFailure', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if tearDown() raises # an exception. def test_run_call_order__error_in_tearDown(self): events = [] result = LoggingResult(events) def setUp(): events.append('setUp') def test(): events.append('test') def tearDown(): events.append('tearDown') raise RuntimeError('raised by tearDown') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] unittest.FunctionTestCase(test, setUp, tearDown).run(result) self.assertEqual(events, expected) # "Return a string identifying the specific test case." # # Because of the vague nature of the docs, I'm not going to lock this # test down too much. Really all that can be asserted is that the id() # will be a string (either 8-byte or unicode -- again, because the docs # just say "string") def test_id(self): test = unittest.FunctionTestCase(lambda: None) self.assertIsInstance(test.id(), str) # "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 test method's docstring, if available, or None." def test_shortDescription__no_docstring(self): test = unittest.FunctionTestCase(lambda: None) self.assertEqual(test.shortDescription(), 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 test method's docstring, if available, or None." def test_shortDescription__singleline_docstring(self): desc = "this tests foo" test = unittest.FunctionTestCase(lambda: None, description=desc) self.assertEqual(test.shortDescription(), "this tests foo") if __name__ == "__main__": unittest.main()
5,540
149
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/support.py
import unittest class TestEquality(object): """Used as a mixin for TestCase""" # Check for a valid __eq__ implementation def test_eq(self): for obj_1, obj_2 in self.eq_pairs: self.assertEqual(obj_1, obj_2) self.assertEqual(obj_2, obj_1) # Check for a valid __ne__ implementation def test_ne(self): for obj_1, obj_2 in self.ne_pairs: self.assertNotEqual(obj_1, obj_2) self.assertNotEqual(obj_2, obj_1) class TestHashing(object): """Used as a mixin for TestCase""" # Check for a valid __hash__ implementation def test_hash(self): for obj_1, obj_2 in self.eq_pairs: try: if not hash(obj_1) == hash(obj_2): self.fail("%r and %r do not hash equal" % (obj_1, obj_2)) except Exception as e: self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e)) for obj_1, obj_2 in self.ne_pairs: try: if hash(obj_1) == hash(obj_2): self.fail("%s and %s hash equal, but shouldn't" % (obj_1, obj_2)) except Exception as e: self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) class _BaseLoggingResult(unittest.TestResult): def __init__(self, log): self._events = log super().__init__() def startTest(self, test): self._events.append('startTest') super().startTest(test) def startTestRun(self): self._events.append('startTestRun') super().startTestRun() def stopTest(self, test): self._events.append('stopTest') super().stopTest(test) def stopTestRun(self): self._events.append('stopTestRun') super().stopTestRun() def addFailure(self, *args): self._events.append('addFailure') super().addFailure(*args) def addSuccess(self, *args): self._events.append('addSuccess') super().addSuccess(*args) def addError(self, *args): self._events.append('addError') super().addError(*args) def addSkip(self, *args): self._events.append('addSkip') super().addSkip(*args) def addExpectedFailure(self, *args): self._events.append('addExpectedFailure') super().addExpectedFailure(*args) def addUnexpectedSuccess(self, *args): self._events.append('addUnexpectedSuccess') super().addUnexpectedSuccess(*args) class LegacyLoggingResult(_BaseLoggingResult): """ A legacy TestResult implementation, without an addSubTest method, which records its method calls. """ @property def addSubTest(self): raise AttributeError class LoggingResult(_BaseLoggingResult): """ A TestResult implementation which records its method calls. """ def addSubTest(self, test, subtest, err): if err is None: self._events.append('addSubTestSuccess') else: self._events.append('addSubTestFailure') super().addSubTest(test, subtest, err) class ResultWithNoStartTestRunStopTestRun(object): """An object honouring TestResult before startTestRun/stopTestRun.""" def __init__(self): self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False def startTest(self, test): pass def stopTest(self, test): pass def addError(self, test): pass def addFailure(self, test): pass def addSuccess(self, test): pass def wasSuccessful(self): return True
3,752
139
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/_test_warnings.py
# helper module for test_runner.Test_TextTestRunner.test_warnings """ This module has a number of tests that raise different kinds of warnings. When the tests are run, the warnings are caught and their messages are printed to stdout. This module also accepts an arg that is then passed to unittest.main to affect the behavior of warnings. Test_TextTestRunner.test_warnings executes this script with different combinations of warnings args and -W flags and check that the output is correct. See #10535. """ import sys import unittest import warnings def warnfun(): warnings.warn('rw', RuntimeWarning) class TestWarnings(unittest.TestCase): # unittest warnings will be printed at most once per type (max one message # for the fail* methods, and one for the assert* methods) def test_assert(self): self.assertEquals(2+2, 4) self.assertEquals(2*2, 4) self.assertEquals(2**2, 4) def test_fail(self): self.failUnless(1) self.failUnless(True) def test_other_unittest(self): self.assertAlmostEqual(2+2, 4) self.assertNotAlmostEqual(4+4, 2) # these warnings are normally silenced, but they are printed in unittest def test_deprecation(self): warnings.warn('dw', DeprecationWarning) warnings.warn('dw', DeprecationWarning) warnings.warn('dw', DeprecationWarning) def test_import(self): warnings.warn('iw', ImportWarning) warnings.warn('iw', ImportWarning) warnings.warn('iw', ImportWarning) # user warnings should always be printed def test_warning(self): warnings.warn('uw') warnings.warn('uw') warnings.warn('uw') # these warnings come from the same place; they will be printed # only once by default or three times if the 'always' filter is used def test_function(self): warnfun() warnfun() warnfun() if __name__ == '__main__': with warnings.catch_warnings(record=True) as ws: # if an arg is provided pass it to unittest.main as 'warnings' if len(sys.argv) == 2: unittest.main(exit=False, warnings=sys.argv.pop()) else: unittest.main(exit=False) # print all the warning messages collected for w in ws: print(w.message)
2,304
74
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/__main__.py
import os import unittest def load_tests(loader, standard_tests, pattern): # top level directory cached on loader instance this_dir = os.path.dirname(__file__) pattern = pattern or "test_*.py" # We are inside unittest.test, so the top-level is two notches up top_level_dir = os.path.dirname(os.path.dirname(this_dir)) package_tests = loader.discover(start_dir=this_dir, pattern=pattern, top_level_dir=top_level_dir) standard_tests.addTests(package_tests) return standard_tests if __name__ == '__main__': unittest.main()
596
19
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_suite.py
import unittest import gc import sys import weakref from unittest.test.support import LoggingResult, TestEquality ### Support code for Test_TestSuite ################################################################ class Test(object): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def test_3(self): pass def runTest(self): pass def _mk_TestSuite(*names): return unittest.TestSuite(Test.Foo(n) for n in names) ################################################################ class Test_TestSuite(unittest.TestCase, TestEquality): ### Set up attributes needed by inherited tests ################################################################ # Used by TestEquality.test_eq eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()) ,(unittest.TestSuite(), unittest.TestSuite([])) ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))] # Used by TestEquality.test_ne ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')) ,(unittest.TestSuite([]), _mk_TestSuite('test_1')) ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')) ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))] ################################################################ ### /Set up attributes needed by inherited tests ### Tests for TestSuite.__init__ ################################################################ # "class TestSuite([tests])" # # The tests iterable should be optional def test_init__tests_optional(self): suite = unittest.TestSuite() self.assertEqual(suite.countTestCases(), 0) # countTestCases() still works after tests are run suite.run(unittest.TestResult()) self.assertEqual(suite.countTestCases(), 0) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # TestSuite should deal with empty tests iterables by allowing the # creation of an empty suite def test_init__empty_tests(self): suite = unittest.TestSuite([]) self.assertEqual(suite.countTestCases(), 0) # countTestCases() still works after tests are run suite.run(unittest.TestResult()) self.assertEqual(suite.countTestCases(), 0) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # TestSuite should allow any iterable to provide tests def test_init__tests_from_any_iterable(self): def tests(): yield unittest.FunctionTestCase(lambda: None) yield unittest.FunctionTestCase(lambda: None) suite_1 = unittest.TestSuite(tests()) self.assertEqual(suite_1.countTestCases(), 2) suite_2 = unittest.TestSuite(suite_1) self.assertEqual(suite_2.countTestCases(), 2) suite_3 = unittest.TestSuite(set(suite_1)) self.assertEqual(suite_3.countTestCases(), 2) # countTestCases() still works after tests are run suite_1.run(unittest.TestResult()) self.assertEqual(suite_1.countTestCases(), 2) suite_2.run(unittest.TestResult()) self.assertEqual(suite_2.countTestCases(), 2) suite_3.run(unittest.TestResult()) self.assertEqual(suite_3.countTestCases(), 2) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # Does TestSuite() also allow other TestSuite() instances to be present # in the tests iterable? def test_init__TestSuite_instances_in_tests(self): def tests(): ftc = unittest.FunctionTestCase(lambda: None) yield unittest.TestSuite([ftc]) yield unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite(tests()) self.assertEqual(suite.countTestCases(), 2) # countTestCases() still works after tests are run suite.run(unittest.TestResult()) self.assertEqual(suite.countTestCases(), 2) ################################################################ ### /Tests for TestSuite.__init__ # Container types should support the iter protocol def test_iter(self): test1 = unittest.FunctionTestCase(lambda: None) test2 = unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite((test1, test2)) self.assertEqual(list(suite), [test1, test2]) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Presumably an empty TestSuite returns 0? def test_countTestCases_zero_simple(self): suite = unittest.TestSuite() self.assertEqual(suite.countTestCases(), 0) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Presumably an empty TestSuite (even if it contains other empty # TestSuite instances) returns 0? def test_countTestCases_zero_nested(self): class Test1(unittest.TestCase): def test(self): pass suite = unittest.TestSuite([unittest.TestSuite()]) self.assertEqual(suite.countTestCases(), 0) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" def test_countTestCases_simple(self): test1 = unittest.FunctionTestCase(lambda: None) test2 = unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite((test1, test2)) self.assertEqual(suite.countTestCases(), 2) # countTestCases() still works after tests are run suite.run(unittest.TestResult()) self.assertEqual(suite.countTestCases(), 2) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Make sure this holds for nested TestSuite instances, too def test_countTestCases_nested(self): class Test1(unittest.TestCase): def test1(self): pass def test2(self): pass test2 = unittest.FunctionTestCase(lambda: None) test3 = unittest.FunctionTestCase(lambda: None) child = unittest.TestSuite((Test1('test2'), test2)) parent = unittest.TestSuite((test3, child, Test1('test1'))) self.assertEqual(parent.countTestCases(), 4) # countTestCases() still works after tests are run parent.run(unittest.TestResult()) self.assertEqual(parent.countTestCases(), 4) self.assertEqual(child.countTestCases(), 2) # "Run the tests associated with this suite, collecting the result into # the test result object passed as result." # # And if there are no tests? What then? def test_run__empty_suite(self): events = [] result = LoggingResult(events) suite = unittest.TestSuite() suite.run(result) self.assertEqual(events, []) # "Note that unlike TestCase.run(), TestSuite.run() requires the # "result object to be passed in." def test_run__requires_result(self): suite = unittest.TestSuite() try: suite.run() except TypeError: pass else: self.fail("Failed to raise TypeError") # "Run the tests associated with this suite, collecting the result into # the test result object passed as result." def test_run(self): events = [] result = LoggingResult(events) class LoggingCase(unittest.TestCase): def run(self, result): events.append('run %s' % self._testMethodName) def test1(self): pass def test2(self): pass tests = [LoggingCase('test1'), LoggingCase('test2')] unittest.TestSuite(tests).run(result) self.assertEqual(events, ['run test1', 'run test2']) # "Add a TestCase ... to the suite" def test_addTest__TestCase(self): class Foo(unittest.TestCase): def test(self): pass test = Foo('test') suite = unittest.TestSuite() suite.addTest(test) self.assertEqual(suite.countTestCases(), 1) self.assertEqual(list(suite), [test]) # countTestCases() still works after tests are run suite.run(unittest.TestResult()) self.assertEqual(suite.countTestCases(), 1) # "Add a ... TestSuite to the suite" def test_addTest__TestSuite(self): class Foo(unittest.TestCase): def test(self): pass suite_2 = unittest.TestSuite([Foo('test')]) suite = unittest.TestSuite() suite.addTest(suite_2) self.assertEqual(suite.countTestCases(), 1) self.assertEqual(list(suite), [suite_2]) # countTestCases() still works after tests are run suite.run(unittest.TestResult()) self.assertEqual(suite.countTestCases(), 1) # "Add all the tests from an iterable of TestCase and TestSuite # instances to this test suite." # # "This is equivalent to iterating over tests, calling addTest() for # each element" def test_addTests(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass test_1 = Foo('test_1') test_2 = Foo('test_2') inner_suite = unittest.TestSuite([test_2]) def gen(): yield test_1 yield test_2 yield inner_suite suite_1 = unittest.TestSuite() suite_1.addTests(gen()) self.assertEqual(list(suite_1), list(gen())) # "This is equivalent to iterating over tests, calling addTest() for # each element" suite_2 = unittest.TestSuite() for t in gen(): suite_2.addTest(t) self.assertEqual(suite_1, suite_2) # "Add all the tests from an iterable of TestCase and TestSuite # instances to this test suite." # # What happens if it doesn't get an iterable? def test_addTest__noniterable(self): suite = unittest.TestSuite() try: suite.addTests(5) except TypeError: pass else: self.fail("Failed to raise TypeError") def test_addTest__noncallable(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTest, 5) def test_addTest__casesuiteclass(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTest, Test_TestSuite) self.assertRaises(TypeError, suite.addTest, unittest.TestSuite) def test_addTests__string(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTests, "foo") def test_function_in_suite(self): def f(_): pass suite = unittest.TestSuite() suite.addTest(f) # when the bug is fixed this line will not crash suite.run(unittest.TestResult()) def test_remove_test_at_index(self): if not unittest.BaseTestSuite._cleanup: raise unittest.SkipTest("Suite cleanup is disabled") suite = unittest.TestSuite() suite._tests = [1, 2, 3] suite._removeTestAtIndex(1) self.assertEqual([1, None, 3], suite._tests) def test_remove_test_at_index_not_indexable(self): if not unittest.BaseTestSuite._cleanup: raise unittest.SkipTest("Suite cleanup is disabled") suite = unittest.TestSuite() suite._tests = None # if _removeAtIndex raises for noniterables this next line will break suite._removeTestAtIndex(2) def assert_garbage_collect_test_after_run(self, TestSuiteClass): if not unittest.BaseTestSuite._cleanup: raise unittest.SkipTest("Suite cleanup is disabled") class Foo(unittest.TestCase): def test_nothing(self): pass test = Foo('test_nothing') wref = weakref.ref(test) suite = TestSuiteClass([wref()]) suite.run(unittest.TestResult()) del test # for the benefit of non-reference counting implementations gc.collect() self.assertEqual(suite._tests, [None]) self.assertIsNone(wref()) def test_garbage_collect_test_after_run_BaseTestSuite(self): self.assert_garbage_collect_test_after_run(unittest.BaseTestSuite) def test_garbage_collect_test_after_run_TestSuite(self): self.assert_garbage_collect_test_after_run(unittest.TestSuite) def test_basetestsuite(self): class Test(unittest.TestCase): wasSetUp = False wasTornDown = False @classmethod def setUpClass(cls): cls.wasSetUp = True @classmethod def tearDownClass(cls): cls.wasTornDown = True def testPass(self): pass def testFail(self): fail class Module(object): wasSetUp = False wasTornDown = False @staticmethod def setUpModule(): Module.wasSetUp = True @staticmethod def tearDownModule(): Module.wasTornDown = True Test.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.BaseTestSuite() suite.addTests([Test('testPass'), Test('testFail')]) self.assertEqual(suite.countTestCases(), 2) result = unittest.TestResult() suite.run(result) self.assertFalse(Module.wasSetUp) self.assertFalse(Module.wasTornDown) self.assertFalse(Test.wasSetUp) self.assertFalse(Test.wasTornDown) self.assertEqual(len(result.errors), 1) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 2) self.assertEqual(suite.countTestCases(), 2) def test_overriding_call(self): class MySuite(unittest.TestSuite): called = False def __call__(self, *args, **kw): self.called = True unittest.TestSuite.__call__(self, *args, **kw) suite = MySuite() result = unittest.TestResult() wrapper = unittest.TestSuite() wrapper.addTest(suite) wrapper(result) self.assertTrue(suite.called) # reusing results should be permitted even if abominable self.assertFalse(result._testRunEntered) if __name__ == '__main__': unittest.main()
15,184
448
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_program.py
import io import os import sys from test import support import unittest import unittest.test class Test_TestProgram(unittest.TestCase): def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False def _find_tests(start_dir, pattern): self.wasRun = True self.assertEqual(start_dir, expectedPath) return tests loader._find_tests = _find_tests suite = loader.discover('unittest.test') self.assertTrue(self.wasRun) self.assertEqual(suite._tests, tests) # Horrible white box test def testNoExit(self): result = object() test = object() class FakeRunner(object): def run(self, test): self.test = test return result runner = FakeRunner() oldParseArgs = unittest.TestProgram.parseArgs def restoreParseArgs(): unittest.TestProgram.parseArgs = oldParseArgs unittest.TestProgram.parseArgs = lambda *args: None self.addCleanup(restoreParseArgs) def removeTest(): del unittest.TestProgram.test unittest.TestProgram.test = test self.addCleanup(removeTest) program = unittest.TestProgram(testRunner=runner, exit=False, verbosity=2) self.assertEqual(program.result, result) self.assertEqual(runner.test, test) self.assertEqual(program.verbosity, 2) class FooBar(unittest.TestCase): def testPass(self): assert True def testFail(self): assert False class FooBarLoader(unittest.TestLoader): """Test loader that returns a suite containing FooBar.""" def loadTestsFromModule(self, module): return self.suiteClass( [self.loadTestsFromTestCase(Test_TestProgram.FooBar)]) def loadTestsFromNames(self, names, module): return self.suiteClass( [self.loadTestsFromTestCase(Test_TestProgram.FooBar)]) def test_defaultTest_with_string(self): class FakeRunner(object): def run(self, test): self.test = test return True old_argv = sys.argv sys.argv = ['faketest'] runner = FakeRunner() program = unittest.TestProgram(testRunner=runner, exit=False, defaultTest='unittest.test', testLoader=self.FooBarLoader()) sys.argv = old_argv self.assertEqual(('unittest.test',), program.testNames) def test_defaultTest_with_iterable(self): class FakeRunner(object): def run(self, test): self.test = test return True old_argv = sys.argv sys.argv = ['faketest'] runner = FakeRunner() program = unittest.TestProgram( testRunner=runner, exit=False, defaultTest=['unittest.test', 'unittest.test2'], testLoader=self.FooBarLoader()) sys.argv = old_argv self.assertEqual(['unittest.test', 'unittest.test2'], program.testNames) def test_NonExit(self): program = unittest.main(exit=False, argv=["foobar"], testRunner=unittest.TextTestRunner(stream=io.StringIO()), testLoader=self.FooBarLoader()) self.assertTrue(hasattr(program, 'result')) def test_Exit(self): self.assertRaises( SystemExit, unittest.main, argv=["foobar"], testRunner=unittest.TextTestRunner(stream=io.StringIO()), exit=True, testLoader=self.FooBarLoader()) def test_ExitAsDefault(self): self.assertRaises( SystemExit, unittest.main, argv=["foobar"], testRunner=unittest.TextTestRunner(stream=io.StringIO()), testLoader=self.FooBarLoader()) class InitialisableProgram(unittest.TestProgram): exit = False result = None verbosity = 1 defaultTest = None tb_locals = False testRunner = None testLoader = unittest.defaultTestLoader module = '__main__' progName = 'test' test = 'test' def __init__(self, *args): pass RESULT = object() class FakeRunner(object): initArgs = None test = None raiseError = 0 def __init__(self, **kwargs): FakeRunner.initArgs = kwargs if FakeRunner.raiseError: FakeRunner.raiseError -= 1 raise TypeError def run(self, test): FakeRunner.test = test return RESULT class TestCommandLineArgs(unittest.TestCase): def setUp(self): self.program = InitialisableProgram() self.program.createTests = lambda: None FakeRunner.initArgs = None FakeRunner.test = None FakeRunner.raiseError = 0 def testVerbosity(self): program = self.program for opt in '-q', '--quiet': program.verbosity = 1 program.parseArgs([None, opt]) self.assertEqual(program.verbosity, 0) for opt in '-v', '--verbose': program.verbosity = 1 program.parseArgs([None, opt]) self.assertEqual(program.verbosity, 2) def testBufferCatchFailfast(self): program = self.program for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'), ('catch', 'catchbreak')): if attr == 'catch' and not hasInstallHandler: continue setattr(program, attr, None) program.parseArgs([None]) self.assertIs(getattr(program, attr), False) false = [] setattr(program, attr, false) program.parseArgs([None]) self.assertIs(getattr(program, attr), false) true = [42] setattr(program, attr, true) program.parseArgs([None]) self.assertIs(getattr(program, attr), true) short_opt = '-%s' % arg[0] long_opt = '--%s' % arg for opt in short_opt, long_opt: setattr(program, attr, None) program.parseArgs([None, opt]) self.assertIs(getattr(program, attr), True) setattr(program, attr, False) with support.captured_stderr() as stderr, \ self.assertRaises(SystemExit) as cm: program.parseArgs([None, opt]) self.assertEqual(cm.exception.args, (2,)) setattr(program, attr, True) with support.captured_stderr() as stderr, \ self.assertRaises(SystemExit) as cm: program.parseArgs([None, opt]) self.assertEqual(cm.exception.args, (2,)) def testWarning(self): """Test the warnings argument""" # see #10535 class FakeTP(unittest.TestProgram): def parseArgs(self, *args, **kw): pass def runTests(self, *args, **kw): pass warnoptions = sys.warnoptions[:] try: sys.warnoptions[:] = [] # no warn options, no arg -> default self.assertEqual(FakeTP().warnings, 'default') # no warn options, w/ arg -> arg value self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore') sys.warnoptions[:] = ['somevalue'] # warn options, no arg -> None # warn options, w/ arg -> arg value self.assertEqual(FakeTP().warnings, None) self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore') finally: sys.warnoptions[:] = warnoptions def testRunTestsRunnerClass(self): program = self.program program.testRunner = FakeRunner program.verbosity = 'verbosity' program.failfast = 'failfast' program.buffer = 'buffer' program.warnings = 'warnings' program.runTests() self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity', 'failfast': 'failfast', 'buffer': 'buffer', 'tb_locals': False, 'warnings': 'warnings'}) self.assertEqual(FakeRunner.test, 'test') self.assertIs(program.result, RESULT) def testRunTestsRunnerInstance(self): program = self.program program.testRunner = FakeRunner() FakeRunner.initArgs = None program.runTests() # A new FakeRunner should not have been instantiated self.assertIsNone(FakeRunner.initArgs) self.assertEqual(FakeRunner.test, 'test') self.assertIs(program.result, RESULT) def test_locals(self): program = self.program program.testRunner = FakeRunner program.parseArgs([None, '--locals']) self.assertEqual(True, program.tb_locals) program.runTests() self.assertEqual(FakeRunner.initArgs, {'buffer': False, 'failfast': False, 'tb_locals': True, 'verbosity': 1, 'warnings': None}) def testRunTestsOldRunnerClass(self): program = self.program # Two TypeErrors are needed to fall all the way back to old-style # runners - one to fail tb_locals, one to fail buffer etc. FakeRunner.raiseError = 2 program.testRunner = FakeRunner program.verbosity = 'verbosity' program.failfast = 'failfast' program.buffer = 'buffer' program.test = 'test' program.runTests() # If initialising raises a type error it should be retried # without the new keyword arguments self.assertEqual(FakeRunner.initArgs, {}) self.assertEqual(FakeRunner.test, 'test') self.assertIs(program.result, RESULT) def testCatchBreakInstallsHandler(self): module = sys.modules['unittest.main'] original = module.installHandler def restore(): module.installHandler = original self.addCleanup(restore) self.installed = False def fakeInstallHandler(): self.installed = True module.installHandler = fakeInstallHandler program = self.program program.catchbreak = True program.testRunner = FakeRunner program.runTests() self.assertTrue(self.installed) def _patch_isfile(self, names, exists=True): def isfile(path): return path in names original = os.path.isfile os.path.isfile = isfile def restore(): os.path.isfile = original self.addCleanup(restore) def testParseArgsFileNames(self): # running tests with filenames instead of module names program = self.program argv = ['progname', 'foo.py', 'bar.Py', 'baz.PY', 'wing.txt'] self._patch_isfile(argv) program.createTests = lambda: None program.parseArgs(argv) # note that 'wing.txt' is not a Python file so the name should # *not* be converted to a module name expected = ['foo', 'bar', 'baz', 'wing.txt'] self.assertEqual(program.testNames, expected) def testParseArgsFilePaths(self): program = self.program argv = ['progname', 'foo/bar/baz.py', 'green\\red.py'] self._patch_isfile(argv) program.createTests = lambda: None program.parseArgs(argv) expected = ['foo.bar.baz', 'green.red'] self.assertEqual(program.testNames, expected) def testParseArgsNonExistentFiles(self): program = self.program argv = ['progname', 'foo/bar/baz.py', 'green\\red.py'] self._patch_isfile([]) program.createTests = lambda: None program.parseArgs(argv) self.assertEqual(program.testNames, argv[1:]) def testParseArgsAbsolutePathsThatCanBeConverted(self): cur_dir = os.getcwd() program = self.program def _join(name): return os.path.join(cur_dir, name) argv = ['progname', _join('foo/bar/baz.py'), _join('green\\red.py')] self._patch_isfile(argv) program.createTests = lambda: None program.parseArgs(argv) expected = ['foo.bar.baz', 'green.red'] self.assertEqual(program.testNames, expected) def testParseArgsAbsolutePathsThatCannotBeConverted(self): program = self.program # even on Windows '/...' is considered absolute by os.path.abspath argv = ['progname', '/foo/bar/baz.py', '/green/red.py'] self._patch_isfile(argv) program.createTests = lambda: None program.parseArgs(argv) self.assertEqual(program.testNames, argv[1:]) # it may be better to use platform specific functions to normalise paths # rather than accepting '.PY' and '\' as file separator on Linux / Mac # it would also be better to check that a filename is a valid module # identifier (we have a regex for this in loader.py) # for invalid filenames should we raise a useful error rather than # leaving the current error message (import of filename fails) in place? if __name__ == '__main__': unittest.main()
13,721
415
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_skipping.py
import unittest from unittest.test.support import LoggingResult class Test_TestSkipping(unittest.TestCase): def test_skipping(self): class Foo(unittest.TestCase): def test_skip_me(self): self.skipTest("skip") events = [] result = LoggingResult(events) test = Foo("test_skip_me") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) self.assertEqual(result.skipped, [(test, "skip")]) # Try letting setUp skip the test now. class Foo(unittest.TestCase): def setUp(self): self.skipTest("testing") def test_nothing(self): pass events = [] result = LoggingResult(events) test = Foo("test_nothing") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(result.testsRun, 1) def test_skipping_subtests(self): class Foo(unittest.TestCase): def test_skip_me(self): with self.subTest(a=1): with self.subTest(b=2): self.skipTest("skip 1") self.skipTest("skip 2") self.skipTest("skip 3") events = [] result = LoggingResult(events) test = Foo("test_skip_me") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'addSkip', 'addSkip', 'stopTest']) self.assertEqual(len(result.skipped), 3) subtest, msg = result.skipped[0] self.assertEqual(msg, "skip 1") self.assertIsInstance(subtest, unittest.TestCase) self.assertIsNot(subtest, test) subtest, msg = result.skipped[1] self.assertEqual(msg, "skip 2") self.assertIsInstance(subtest, unittest.TestCase) self.assertIsNot(subtest, test) self.assertEqual(result.skipped[2], (test, "skip 3")) def test_skipping_decorators(self): op_table = ((unittest.skipUnless, False, True), (unittest.skipIf, True, False)) for deco, do_skip, dont_skip in op_table: class Foo(unittest.TestCase): @deco(do_skip, "testing") def test_skip(self): pass @deco(dont_skip, "testing") def test_dont_skip(self): pass test_do_skip = Foo("test_skip") test_dont_skip = Foo("test_dont_skip") suite = unittest.TestSuite([test_do_skip, test_dont_skip]) events = [] result = LoggingResult(events) suite.run(result) self.assertEqual(len(result.skipped), 1) expected = ['startTest', 'addSkip', 'stopTest', 'startTest', 'addSuccess', 'stopTest'] self.assertEqual(events, expected) self.assertEqual(result.testsRun, 2) self.assertEqual(result.skipped, [(test_do_skip, "testing")]) self.assertTrue(result.wasSuccessful()) def test_skip_class(self): @unittest.skip("testing") class Foo(unittest.TestCase): def test_1(self): record.append(1) record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_skip_non_unittest_class(self): @unittest.skip("testing") class Mixin: def test_1(self): record.append(1) class Foo(Mixin, unittest.TestCase): pass record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_expected_failure(self): class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): self.fail("help me!") events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addExpectedFailure', 'stopTest']) self.assertEqual(result.expectedFailures[0][0], test) self.assertTrue(result.wasSuccessful()) def test_expected_failure_with_wrapped_class(self): @unittest.expectedFailure class Foo(unittest.TestCase): def test_1(self): self.assertTrue(False) events = [] result = LoggingResult(events) test = Foo("test_1") test.run(result) self.assertEqual(events, ['startTest', 'addExpectedFailure', 'stopTest']) self.assertEqual(result.expectedFailures[0][0], test) self.assertTrue(result.wasSuccessful()) def test_expected_failure_with_wrapped_subclass(self): class Foo(unittest.TestCase): def test_1(self): self.assertTrue(False) @unittest.expectedFailure class Bar(Foo): pass events = [] result = LoggingResult(events) test = Bar("test_1") test.run(result) self.assertEqual(events, ['startTest', 'addExpectedFailure', 'stopTest']) self.assertEqual(result.expectedFailures[0][0], test) self.assertTrue(result.wasSuccessful()) def test_expected_failure_subtests(self): # A failure in any subtest counts as the expected failure of the # whole test. class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): with self.subTest(): # This one succeeds pass with self.subTest(): self.fail("help me!") with self.subTest(): # This one doesn't get executed self.fail("shouldn't come here") events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addSubTestSuccess', 'addExpectedFailure', 'stopTest']) self.assertEqual(len(result.expectedFailures), 1) self.assertIs(result.expectedFailures[0][0], test) self.assertTrue(result.wasSuccessful()) def test_unexpected_success(self): class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): pass events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addUnexpectedSuccess', 'stopTest']) self.assertFalse(result.failures) self.assertEqual(result.unexpectedSuccesses, [test]) self.assertFalse(result.wasSuccessful()) def test_unexpected_success_subtests(self): # Success in all subtests counts as the unexpected success of # the whole test. class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): with self.subTest(): # This one succeeds pass with self.subTest(): # So does this one pass events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addSubTestSuccess', 'addSubTestSuccess', 'addUnexpectedSuccess', 'stopTest']) self.assertFalse(result.failures) self.assertEqual(result.unexpectedSuccesses, [test]) self.assertFalse(result.wasSuccessful()) def test_skip_doesnt_run_setup(self): class Foo(unittest.TestCase): wasSetUp = False wasTornDown = False def setUp(self): Foo.wasSetUp = True def tornDown(self): Foo.wasTornDown = True @unittest.skip('testing') def test_1(self): pass result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertFalse(Foo.wasSetUp) self.assertFalse(Foo.wasTornDown) def test_decorated_skip(self): def decorator(func): def inner(*a): return func(*a) return inner class Foo(unittest.TestCase): @decorator @unittest.skip('testing') def test_1(self): pass result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) if __name__ == "__main__": unittest.main()
9,316
261
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_result.py
import io import sys import textwrap from test import support import traceback import unittest class MockTraceback(object): class TracebackException: def __init__(self, *args, **kwargs): self.capture_locals = kwargs.get('capture_locals', False) def format(self): result = ['A traceback'] if self.capture_locals: result.append('locals') return result def restore_traceback(): unittest.result.traceback = traceback class Test_TestResult(unittest.TestCase): # Note: there are not separate tests for TestResult.wasSuccessful(), # TestResult.errors, TestResult.failures, TestResult.testsRun or # TestResult.shouldStop because these only have meaning in terms of # other TestResult methods. # # Accordingly, tests for the aforenamed attributes are incorporated # in with the tests for the defining methods. ################################################################ def test_init(self): result = unittest.TestResult() self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 0) self.assertEqual(result.shouldStop, False) self.assertIsNone(result._stdout_buffer) self.assertIsNone(result._stderr_buffer) # "This method can be called to signal that the set of tests being # run should be aborted by setting the TestResult's shouldStop # attribute to True." def test_stop(self): result = unittest.TestResult() result.stop() self.assertEqual(result.shouldStop, True) # "Called when the test case test is about to be run. The default # implementation simply increments the instance's testsRun counter." def test_startTest(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') result = unittest.TestResult() result.startTest(test) self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) result.stopTest(test) # "Called after the test case test has been executed, regardless of # the outcome. The default implementation does nothing." def test_stopTest(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') result = unittest.TestResult() result.startTest(test) self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) result.stopTest(test) # Same tests as above; make sure nothing has changed self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) # "Called before and after tests are run. The default implementation does nothing." def test_startTestRun_stopTestRun(self): result = unittest.TestResult() result.startTestRun() result.stopTestRun() # "addSuccess(test)" # ... # "Called when the test case test succeeds" # ... # "wasSuccessful() - Returns True if all tests run so far have passed, # otherwise returns False" # ... # "testsRun - The total number of tests run so far." # ... # "errors - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test which raised an # unexpected exception. Contains formatted # tracebacks instead of sys.exc_info() results." # ... # "failures - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test where a failure was # explicitly signalled using the TestCase.fail*() or TestCase.assert*() # methods. Contains formatted tracebacks instead # of sys.exc_info() results." def test_addSuccess(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') result = unittest.TestResult() result.startTest(test) result.addSuccess(test) result.stopTest(test) self.assertTrue(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) # "addFailure(test, err)" # ... # "Called when the test case test signals a failure. err is a tuple of # the form returned by sys.exc_info(): (type, value, traceback)" # ... # "wasSuccessful() - Returns True if all tests run so far have passed, # otherwise returns False" # ... # "testsRun - The total number of tests run so far." # ... # "errors - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test which raised an # unexpected exception. Contains formatted # tracebacks instead of sys.exc_info() results." # ... # "failures - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test where a failure was # explicitly signalled using the TestCase.fail*() or TestCase.assert*() # methods. Contains formatted tracebacks instead # of sys.exc_info() results." def test_addFailure(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') try: test.fail("foo") except: exc_info_tuple = sys.exc_info() result = unittest.TestResult() result.startTest(test) result.addFailure(test, exc_info_tuple) result.stopTest(test) self.assertFalse(result.wasSuccessful()) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.failures), 1) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) test_case, formatted_exc = result.failures[0] self.assertIs(test_case, test) self.assertIsInstance(formatted_exc, str) # "addError(test, err)" # ... # "Called when the test case test raises an unexpected exception err # is a tuple of the form returned by sys.exc_info(): # (type, value, traceback)" # ... # "wasSuccessful() - Returns True if all tests run so far have passed, # otherwise returns False" # ... # "testsRun - The total number of tests run so far." # ... # "errors - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test which raised an # unexpected exception. Contains formatted # tracebacks instead of sys.exc_info() results." # ... # "failures - A list containing 2-tuples of TestCase instances and # formatted tracebacks. Each tuple represents a test where a failure was # explicitly signalled using the TestCase.fail*() or TestCase.assert*() # methods. Contains formatted tracebacks instead # of sys.exc_info() results." def test_addError(self): class Foo(unittest.TestCase): def test_1(self): pass test = Foo('test_1') try: raise TypeError() except: exc_info_tuple = sys.exc_info() result = unittest.TestResult() result.startTest(test) result.addError(test, exc_info_tuple) result.stopTest(test) self.assertFalse(result.wasSuccessful()) self.assertEqual(len(result.errors), 1) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) test_case, formatted_exc = result.errors[0] self.assertIs(test_case, test) self.assertIsInstance(formatted_exc, str) def test_addError_locals(self): class Foo(unittest.TestCase): def test_1(self): 1/0 test = Foo('test_1') result = unittest.TestResult() result.tb_locals = True unittest.result.traceback = MockTraceback self.addCleanup(restore_traceback) result.startTestRun() test.run(result) result.stopTestRun() self.assertEqual(len(result.errors), 1) test_case, formatted_exc = result.errors[0] self.assertEqual('A tracebacklocals', formatted_exc) def test_addSubTest(self): class Foo(unittest.TestCase): def test_1(self): nonlocal subtest with self.subTest(foo=1): subtest = self._subtest try: 1/0 except ZeroDivisionError: exc_info_tuple = sys.exc_info() # Register an error by hand (to check the API) result.addSubTest(test, subtest, exc_info_tuple) # Now trigger a failure self.fail("some recognizable failure") subtest = None test = Foo('test_1') result = unittest.TestResult() test.run(result) self.assertFalse(result.wasSuccessful()) self.assertEqual(len(result.errors), 1) self.assertEqual(len(result.failures), 1) self.assertEqual(result.testsRun, 1) self.assertEqual(result.shouldStop, False) test_case, formatted_exc = result.errors[0] self.assertIs(test_case, subtest) self.assertIn("ZeroDivisionError", formatted_exc) test_case, formatted_exc = result.failures[0] self.assertIs(test_case, subtest) self.assertIn("some recognizable failure", formatted_exc) def testGetDescriptionWithoutDocstring(self): result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self), 'testGetDescriptionWithoutDocstring (' + __name__ + '.Test_TestResult)') def testGetSubTestDescriptionWithoutDocstring(self): with self.subTest(foo=1, bar=2): result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self._subtest), 'testGetSubTestDescriptionWithoutDocstring (' + __name__ + '.Test_TestResult) (bar=2, foo=1)') with self.subTest('some message'): result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self._subtest), 'testGetSubTestDescriptionWithoutDocstring (' + __name__ + '.Test_TestResult) [some message]') def testGetSubTestDescriptionWithoutDocstringAndParams(self): with self.subTest(): result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self._subtest), 'testGetSubTestDescriptionWithoutDocstringAndParams ' '(' + __name__ + '.Test_TestResult) (<subtest>)') def testGetSubTestDescriptionForFalsyValues(self): expected = 'testGetSubTestDescriptionForFalsyValues (%s.Test_TestResult) [%s]' result = unittest.TextTestResult(None, True, 1) for arg in [0, None, []]: with self.subTest(arg): self.assertEqual( result.getDescription(self._subtest), expected % (__name__, arg) ) def testGetNestedSubTestDescriptionWithoutDocstring(self): with self.subTest(foo=1): with self.subTest(bar=2): result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self._subtest), 'testGetNestedSubTestDescriptionWithoutDocstring ' '(' + __name__ + '.Test_TestResult) (bar=2, foo=1)') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testGetDescriptionWithOneLineDocstring(self): """Tests getDescription() for a method with a docstring.""" result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self), ('testGetDescriptionWithOneLineDocstring ' '(' + __name__ + '.Test_TestResult)\n' 'Tests getDescription() for a method with a docstring.')) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testGetSubTestDescriptionWithOneLineDocstring(self): """Tests getDescription() for a method with a docstring.""" result = unittest.TextTestResult(None, True, 1) with self.subTest(foo=1, bar=2): self.assertEqual( result.getDescription(self._subtest), ('testGetSubTestDescriptionWithOneLineDocstring ' '(' + __name__ + '.Test_TestResult) (bar=2, foo=1)\n' 'Tests getDescription() for a method with a docstring.')) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testGetDescriptionWithMultiLineDocstring(self): """Tests getDescription() for a method with a longer docstring. The second line of the docstring. """ result = unittest.TextTestResult(None, True, 1) self.assertEqual( result.getDescription(self), ('testGetDescriptionWithMultiLineDocstring ' '(' + __name__ + '.Test_TestResult)\n' 'Tests getDescription() for a method with a longer ' 'docstring.')) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testGetSubTestDescriptionWithMultiLineDocstring(self): """Tests getDescription() for a method with a longer docstring. The second line of the docstring. """ result = unittest.TextTestResult(None, True, 1) with self.subTest(foo=1, bar=2): self.assertEqual( result.getDescription(self._subtest), ('testGetSubTestDescriptionWithMultiLineDocstring ' '(' + __name__ + '.Test_TestResult) (bar=2, foo=1)\n' 'Tests getDescription() for a method with a longer ' 'docstring.')) def testStackFrameTrimming(self): class Frame(object): class tb_frame(object): f_globals = {} result = unittest.TestResult() self.assertFalse(result._is_relevant_tb_level(Frame)) Frame.tb_frame.f_globals['__unittest'] = True self.assertTrue(result._is_relevant_tb_level(Frame)) def testFailFast(self): result = unittest.TestResult() result._exc_info_to_string = lambda *_: '' result.failfast = True result.addError(None, None) self.assertTrue(result.shouldStop) result = unittest.TestResult() result._exc_info_to_string = lambda *_: '' result.failfast = True result.addFailure(None, None) self.assertTrue(result.shouldStop) result = unittest.TestResult() result._exc_info_to_string = lambda *_: '' result.failfast = True result.addUnexpectedSuccess(None) self.assertTrue(result.shouldStop) def testFailFastSetByRunner(self): runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True) def test(result): self.assertTrue(result.failfast) result = runner.run(test) classDict = dict(unittest.TestResult.__dict__) for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess', '__init__'): del classDict[m] def __init__(self, stream=None, descriptions=None, verbosity=None): self.failures = [] self.errors = [] self.testsRun = 0 self.shouldStop = False self.buffer = False self.tb_locals = False classDict['__init__'] = __init__ OldResult = type('OldResult', (object,), classDict) class Test_OldTestResult(unittest.TestCase): def assertOldResultWarning(self, test, failures): with support.check_warnings(("TestResult has no add.+ method,", RuntimeWarning)): result = OldResult() test.run(result) self.assertEqual(len(result.failures), failures) def testOldTestResult(self): class Test(unittest.TestCase): def testSkip(self): self.skipTest('foobar') @unittest.expectedFailure def testExpectedFail(self): raise TypeError @unittest.expectedFailure def testUnexpectedSuccess(self): pass for test_name, should_pass in (('testSkip', True), ('testExpectedFail', True), ('testUnexpectedSuccess', False)): test = Test(test_name) self.assertOldResultWarning(test, int(not should_pass)) def testOldTestTesultSetup(self): class Test(unittest.TestCase): def setUp(self): self.skipTest('no reason') def testFoo(self): pass self.assertOldResultWarning(Test('testFoo'), 0) def testOldTestResultClass(self): @unittest.skip('no reason') class Test(unittest.TestCase): def testFoo(self): pass self.assertOldResultWarning(Test('testFoo'), 0) def testOldResultWithRunner(self): class Test(unittest.TestCase): def testFoo(self): pass runner = unittest.TextTestRunner(resultclass=OldResult, stream=io.StringIO()) # This will raise an exception if TextTestRunner can't handle old # test result objects runner.run(Test('testFoo')) class TestOutputBuffering(unittest.TestCase): def setUp(self): self._real_out = sys.stdout self._real_err = sys.stderr def tearDown(self): sys.stdout = self._real_out sys.stderr = self._real_err def testBufferOutputOff(self): real_out = self._real_out real_err = self._real_err result = unittest.TestResult() self.assertFalse(result.buffer) self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) result.startTest(self) self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) def testBufferOutputStartTestAddSuccess(self): real_out = self._real_out real_err = self._real_err result = unittest.TestResult() self.assertFalse(result.buffer) result.buffer = True self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) result.startTest(self) self.assertIsNot(real_out, sys.stdout) self.assertIsNot(real_err, sys.stderr) self.assertIsInstance(sys.stdout, io.StringIO) self.assertIsInstance(sys.stderr, io.StringIO) self.assertIsNot(sys.stdout, sys.stderr) out_stream = sys.stdout err_stream = sys.stderr result._original_stdout = io.StringIO() result._original_stderr = io.StringIO() print('foo') print('bar', file=sys.stderr) self.assertEqual(out_stream.getvalue(), 'foo\n') self.assertEqual(err_stream.getvalue(), 'bar\n') self.assertEqual(result._original_stdout.getvalue(), '') self.assertEqual(result._original_stderr.getvalue(), '') result.addSuccess(self) result.stopTest(self) self.assertIs(sys.stdout, result._original_stdout) self.assertIs(sys.stderr, result._original_stderr) self.assertEqual(result._original_stdout.getvalue(), '') self.assertEqual(result._original_stderr.getvalue(), '') self.assertEqual(out_stream.getvalue(), '') self.assertEqual(err_stream.getvalue(), '') def getStartedResult(self): result = unittest.TestResult() result.buffer = True result.startTest(self) return result def testBufferOutputAddErrorOrFailure(self): unittest.result.traceback = MockTraceback self.addCleanup(restore_traceback) for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), ('errors', 'addError', True), ('failures', 'addFailure', False) ]: result = self.getStartedResult() buffered_out = sys.stdout buffered_err = sys.stderr result._original_stdout = io.StringIO() result._original_stderr = io.StringIO() print('foo', file=sys.stdout) if include_error: print('bar', file=sys.stderr) addFunction = getattr(result, add_attr) addFunction(self, (None, None, None)) result.stopTest(self) result_list = getattr(result, message_attr) self.assertEqual(len(result_list), 1) test, message = result_list[0] expectedOutMessage = textwrap.dedent(""" Stdout: foo """) expectedErrMessage = '' if include_error: expectedErrMessage = textwrap.dedent(""" Stderr: bar """) expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage) self.assertIs(test, self) self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage) self.assertEqual(result._original_stderr.getvalue(), expectedErrMessage) self.assertMultiLineEqual(message, expectedFullMessage) def testBufferSetupClass(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): @classmethod def setUpClass(cls): 1/0 def test_foo(self): pass suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) def testBufferTearDownClass(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): @classmethod def tearDownClass(cls): 1/0 def test_foo(self): pass suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) def testBufferSetUpModule(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): def test_foo(self): pass class Module(object): @staticmethod def setUpModule(): 1/0 Foo.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) def testBufferTearDownModule(self): result = unittest.TestResult() result.buffer = True class Foo(unittest.TestCase): def test_foo(self): pass class Module(object): @staticmethod def tearDownModule(): 1/0 Foo.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.TestSuite([Foo('test_foo')]) suite(result) self.assertEqual(len(result.errors), 1) if __name__ == '__main__': unittest.main()
24,497
696
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_runner.py
import io import os import sys import pickle import subprocess import unittest from unittest.case import _Outcome from unittest.test.support import (LoggingResult, ResultWithNoStartTestRunStopTestRun) class TestCleanUp(unittest.TestCase): def testCleanUp(self): class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') self.assertEqual(test._cleanups, []) cleanups = [] def cleanup1(*args, **kwargs): cleanups.append((1, args, kwargs)) def cleanup2(*args, **kwargs): cleanups.append((2, args, kwargs)) test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye') test.addCleanup(cleanup2) self.assertEqual(test._cleanups, [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')), (cleanup2, (), {})]) self.assertTrue(test.doCleanups()) self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))]) def testCleanUpWithErrors(self): class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') outcome = test._outcome = _Outcome() exc1 = Exception('foo') exc2 = Exception('bar') def cleanup1(): raise exc1 def cleanup2(): raise exc2 test.addCleanup(cleanup1) test.addCleanup(cleanup2) self.assertFalse(test.doCleanups()) self.assertFalse(outcome.success) ((_, (Type1, instance1, _)), (_, (Type2, instance2, _))) = reversed(outcome.errors) self.assertEqual((Type1, instance1), (Exception, exc1)) self.assertEqual((Type2, instance2), (Exception, exc2)) def testCleanupInRun(self): blowUp = False ordering = [] class TestableTest(unittest.TestCase): def setUp(self): ordering.append('setUp') if blowUp: raise Exception('foo') def testNothing(self): ordering.append('test') def tearDown(self): ordering.append('tearDown') test = TestableTest('testNothing') def cleanup1(): ordering.append('cleanup1') def cleanup2(): ordering.append('cleanup2') test.addCleanup(cleanup1) test.addCleanup(cleanup2) def success(some_test): self.assertEqual(some_test, test) ordering.append('success') result = unittest.TestResult() result.addSuccess = success test.run(result) self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup2', 'cleanup1', 'success']) blowUp = True ordering = [] test = TestableTest('testNothing') test.addCleanup(cleanup1) test.run(result) self.assertEqual(ordering, ['setUp', 'cleanup1']) def testTestCaseDebugExecutesCleanups(self): ordering = [] class TestableTest(unittest.TestCase): def setUp(self): ordering.append('setUp') self.addCleanup(cleanup1) def testNothing(self): ordering.append('test') def tearDown(self): ordering.append('tearDown') test = TestableTest('testNothing') def cleanup1(): ordering.append('cleanup1') test.addCleanup(cleanup2) def cleanup2(): ordering.append('cleanup2') test.debug() self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup1', 'cleanup2']) class Test_TextTestRunner(unittest.TestCase): """Tests for TextTestRunner.""" def setUp(self): # clean the environment from pre-existing PYTHONWARNINGS to make # test_warnings results consistent self.pythonwarnings = os.environ.get('PYTHONWARNINGS') if self.pythonwarnings: del os.environ['PYTHONWARNINGS'] def tearDown(self): # bring back pre-existing PYTHONWARNINGS if present if self.pythonwarnings: os.environ['PYTHONWARNINGS'] = self.pythonwarnings def test_init(self): runner = unittest.TextTestRunner() self.assertFalse(runner.failfast) self.assertFalse(runner.buffer) self.assertEqual(runner.verbosity, 1) self.assertEqual(runner.warnings, None) self.assertTrue(runner.descriptions) self.assertEqual(runner.resultclass, unittest.TextTestResult) self.assertFalse(runner.tb_locals) def test_multiple_inheritance(self): class AResult(unittest.TestResult): def __init__(self, stream, descriptions, verbosity): super(AResult, self).__init__(stream, descriptions, verbosity) class ATextResult(unittest.TextTestResult, AResult): pass # This used to raise an exception due to TextTestResult not passing # on arguments in its __init__ super call ATextResult(None, None, 1) def testBufferAndFailfast(self): class Test(unittest.TestCase): def testFoo(self): pass result = unittest.TestResult() runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True, buffer=True) # Use our result object runner._makeResult = lambda: result runner.run(Test('testFoo')) self.assertTrue(result.failfast) self.assertTrue(result.buffer) def test_locals(self): runner = unittest.TextTestRunner(stream=io.StringIO(), tb_locals=True) result = runner.run(unittest.TestSuite()) self.assertEqual(True, result.tb_locals) def testRunnerRegistersResult(self): class Test(unittest.TestCase): def testFoo(self): pass originalRegisterResult = unittest.runner.registerResult def cleanup(): unittest.runner.registerResult = originalRegisterResult self.addCleanup(cleanup) result = unittest.TestResult() runner = unittest.TextTestRunner(stream=io.StringIO()) # Use our result object runner._makeResult = lambda: result self.wasRegistered = 0 def fakeRegisterResult(thisResult): self.wasRegistered += 1 self.assertEqual(thisResult, result) unittest.runner.registerResult = fakeRegisterResult runner.run(unittest.TestSuite()) self.assertEqual(self.wasRegistered, 1) def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(ResultWithNoStartTestRunStopTestRun): separator2 = '' def printErrors(self): pass class Runner(unittest.TextTestRunner): def __init__(self): super(Runner, self).__init__(io.StringIO()) def _makeResult(self): return OldTextResult() runner = Runner() runner.run(unittest.TestSuite()) def test_startTestRun_stopTestRun_called(self): class LoggingTextResult(LoggingResult): separator2 = '' def printErrors(self): pass class LoggingRunner(unittest.TextTestRunner): def __init__(self, events): super(LoggingRunner, self).__init__(io.StringIO()) self._events = events def _makeResult(self): return LoggingTextResult(self._events) events = [] runner = LoggingRunner(events) runner.run(unittest.TestSuite()) expected = ['startTestRun', 'stopTestRun'] self.assertEqual(events, expected) def test_pickle_unpickle(self): # Issue #7197: a TextTestRunner should be (un)pickleable. This is # required by test_multiprocessing under Windows (in verbose mode). stream = io.StringIO("foo") runner = unittest.TextTestRunner(stream) for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(runner, protocol) obj = pickle.loads(s) # StringIO objects never compare equal, a cheap test instead. self.assertEqual(obj.stream.getvalue(), stream.getvalue()) def test_resultclass(self): def MockResultClass(*args): return args STREAM = object() DESCRIPTIONS = object() VERBOSITY = object() runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY, resultclass=MockResultClass) self.assertEqual(runner.resultclass, MockResultClass) expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY) self.assertEqual(runner._makeResult(), expectedresult) def test_warnings(self): """ Check that warnings argument of TextTestRunner correctly affects the behavior of the warnings. """ # see #10535 and the _test_warnings file for more information def get_parse_out_err(p): return [b.splitlines() for b in p.communicate()] opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(__file__)) ae_msg = b'Please use assertEqual instead.' at_msg = b'Please use assertTrue instead.' # no args -> all the warnings are printed, unittest warnings only once p = subprocess.Popen([sys.executable, '_test_warnings.py'], **opts) with p: out, err = get_parse_out_err(p) self.assertIn(b'OK', err) # check that the total number of warnings in the output is correct self.assertEqual(len(out), 12) # check that the numbers of the different kind of warnings is correct for msg in [b'dw', b'iw', b'uw']: self.assertEqual(out.count(msg), 3) for msg in [ae_msg, at_msg, b'rw']: self.assertEqual(out.count(msg), 1) args_list = ( # passing 'ignore' as warnings arg -> no warnings [sys.executable, '_test_warnings.py', 'ignore'], # -W doesn't affect the result if the arg is passed [sys.executable, '-Wa', '_test_warnings.py', 'ignore'], # -W affects the result if the arg is not passed [sys.executable, '-Wi', '_test_warnings.py'] ) # in all these cases no warnings are printed for args in args_list: p = subprocess.Popen(args, **opts) with p: out, err = get_parse_out_err(p) self.assertIn(b'OK', err) self.assertEqual(len(out), 0) # passing 'always' as warnings arg -> all the warnings printed, # unittest warnings only once p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'], **opts) with p: out, err = get_parse_out_err(p) self.assertIn(b'OK', err) self.assertEqual(len(out), 14) for msg in [b'dw', b'iw', b'uw', b'rw']: self.assertEqual(out.count(msg), 3) for msg in [ae_msg, at_msg]: self.assertEqual(out.count(msg), 1) def testStdErrLookedUpAtInstantiationTime(self): # see issue 10786 old_stderr = sys.stderr f = io.StringIO() sys.stderr = f try: runner = unittest.TextTestRunner() self.assertTrue(runner.stream.stream is f) finally: sys.stderr = old_stderr def testSpecifiedStreamUsed(self): # see issue 10786 f = io.StringIO() runner = unittest.TextTestRunner(f) self.assertTrue(runner.stream.stream is f) if __name__ == "__main__": unittest.main()
12,013
354
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/test_discovery.py
import os.path from os.path import abspath import re import sys import types import pickle from test import support import test.test_importlib.util import unittest import unittest.mock import unittest.test class TestableTestProgram(unittest.TestProgram): module = None exit = True defaultTest = failfast = catchbreak = buffer = None verbosity = 1 progName = '' testRunner = testLoader = None def __init__(self): pass class TestDiscovery(unittest.TestCase): # Heavily mocked tests so I can avoid hitting the filesystem def test_get_name_from_path(self): loader = unittest.TestLoader() loader._top_level_dir = '/foo' name = loader._get_name_from_path('/foo/bar/baz.py') self.assertEqual(name, 'bar.baz') if not __debug__: # asserts are off return with self.assertRaises(AssertionError): loader._get_name_from_path('/bar/baz.py') def test_find_tests(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir path_lists = [['test2.py', 'test1.py', 'not_a_test.py', 'test_dir', 'test.foo', 'test-not-a-module.py', 'another_dir'], ['test4.py', 'test3.py', ]] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) def isdir(path): return path.endswith('dir') os.path.isdir = isdir self.addCleanup(restore_isdir) def isfile(path): # another_dir is not a package and so shouldn't be recursed into return not path.endswith('dir') and not 'another_dir' in path os.path.isfile = isfile self.addCleanup(restore_isfile) loader._get_module_from_name = lambda path: path + ' module' orig_load_tests = loader.loadTestsFromModule def loadTestsFromModule(module, pattern=None): # This is where load_tests is called. base = orig_load_tests(module, pattern=pattern) return base + [module + ' tests'] loader.loadTestsFromModule = loadTestsFromModule loader.suiteClass = lambda thing: thing top_level = os.path.abspath('/foo') loader._top_level_dir = top_level suite = list(loader._find_tests(top_level, 'test*.py')) # The test suites found should be sorted alphabetically for reliable # execution order. expected = [[name + ' module tests'] for name in ('test1', 'test2', 'test_dir')] expected.extend([[('test_dir.%s' % name) + ' module tests'] for name in ('test3', 'test4')]) self.assertEqual(suite, expected) def test_find_tests_socket(self): # A socket is neither a directory nor a regular file. # https://bugs.python.org/issue25320 loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir path_lists = [['socket']] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) os.path.isdir = lambda path: False self.addCleanup(restore_isdir) os.path.isfile = lambda path: False self.addCleanup(restore_isfile) loader._get_module_from_name = lambda path: path + ' module' orig_load_tests = loader.loadTestsFromModule def loadTestsFromModule(module, pattern=None): # This is where load_tests is called. base = orig_load_tests(module, pattern=pattern) return base + [module + ' tests'] loader.loadTestsFromModule = loadTestsFromModule loader.suiteClass = lambda thing: thing top_level = os.path.abspath('/foo') loader._top_level_dir = top_level suite = list(loader._find_tests(top_level, 'test*.py')) self.assertEqual(suite, []) def test_find_tests_with_package(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir directories = ['a_directory', 'test_directory', 'test_directory2'] path_lists = [directories, [], [], []] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) os.path.isdir = lambda path: True self.addCleanup(restore_isdir) os.path.isfile = lambda path: os.path.basename(path) not in directories self.addCleanup(restore_isfile) class Module(object): paths = [] load_tests_args = [] def __init__(self, path): self.path = path self.paths.append(path) if os.path.basename(path) == 'test_directory': def load_tests(loader, tests, pattern): self.load_tests_args.append((loader, tests, pattern)) return [self.path + ' load_tests'] self.load_tests = load_tests def __eq__(self, other): return self.path == other.path loader._get_module_from_name = lambda name: Module(name) orig_load_tests = loader.loadTestsFromModule def loadTestsFromModule(module, pattern=None): # This is where load_tests is called. base = orig_load_tests(module, pattern=pattern) return base + [module.path + ' module tests'] loader.loadTestsFromModule = loadTestsFromModule loader.suiteClass = lambda thing: thing loader._top_level_dir = '/foo' # this time no '.py' on the pattern so that it can match # a test package suite = list(loader._find_tests('/foo', 'test*')) # We should have loaded tests from the a_directory and test_directory2 # directly and via load_tests for the test_directory package, which # still calls the baseline module loader. self.assertEqual(suite, [['a_directory module tests'], ['test_directory load_tests', 'test_directory module tests'], ['test_directory2 module tests']]) # The test module paths should be sorted for reliable execution order self.assertEqual(Module.paths, ['a_directory', 'test_directory', 'test_directory2']) # load_tests should have been called once with loader, tests and pattern # (but there are no tests in our stub module itself, so that is [] at # the time of call). self.assertEqual(Module.load_tests_args, [(loader, [], 'test*')]) def test_find_tests_default_calls_package_load_tests(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir directories = ['a_directory', 'test_directory', 'test_directory2'] path_lists = [directories, [], [], []] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) os.path.isdir = lambda path: True self.addCleanup(restore_isdir) os.path.isfile = lambda path: os.path.basename(path) not in directories self.addCleanup(restore_isfile) class Module(object): paths = [] load_tests_args = [] def __init__(self, path): self.path = path self.paths.append(path) if os.path.basename(path) == 'test_directory': def load_tests(loader, tests, pattern): self.load_tests_args.append((loader, tests, pattern)) return [self.path + ' load_tests'] self.load_tests = load_tests def __eq__(self, other): return self.path == other.path loader._get_module_from_name = lambda name: Module(name) orig_load_tests = loader.loadTestsFromModule def loadTestsFromModule(module, pattern=None): # This is where load_tests is called. base = orig_load_tests(module, pattern=pattern) return base + [module.path + ' module tests'] loader.loadTestsFromModule = loadTestsFromModule loader.suiteClass = lambda thing: thing loader._top_level_dir = '/foo' # this time no '.py' on the pattern so that it can match # a test package suite = list(loader._find_tests('/foo', 'test*.py')) # We should have loaded tests from the a_directory and test_directory2 # directly and via load_tests for the test_directory package, which # still calls the baseline module loader. self.assertEqual(suite, [['a_directory module tests'], ['test_directory load_tests', 'test_directory module tests'], ['test_directory2 module tests']]) # The test module paths should be sorted for reliable execution order self.assertEqual(Module.paths, ['a_directory', 'test_directory', 'test_directory2']) # load_tests should have been called once with loader, tests and pattern self.assertEqual(Module.load_tests_args, [(loader, [], 'test*.py')]) def test_find_tests_customize_via_package_pattern(self): # This test uses the example 'do-nothing' load_tests from # https://docs.python.org/3/library/unittest.html#load-tests-protocol # to make sure that that actually works. # Housekeeping original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir self.addCleanup(restore_listdir) original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile self.addCleanup(restore_isfile) original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir self.addCleanup(restore_isdir) self.addCleanup(sys.path.remove, abspath('/foo')) # Test data: we expect the following: # a listdir to find our package, and isfile and isdir checks on it. # a module-from-name call to turn that into a module # followed by load_tests. # then our load_tests will call discover() which is messy # but that finally chains into find_tests again for the child dir - # which is why we don't have an infinite loop. # We expect to see: # the module load tests for both package and plain module called, # and the plain module result nested by the package module load_tests # indicating that it was processed and could have been mutated. vfs = {abspath('/foo'): ['my_package'], abspath('/foo/my_package'): ['__init__.py', 'test_module.py']} def list_dir(path): return list(vfs[path]) os.listdir = list_dir os.path.isdir = lambda path: not path.endswith('.py') os.path.isfile = lambda path: path.endswith('.py') class Module(object): paths = [] load_tests_args = [] def __init__(self, path): self.path = path self.paths.append(path) if path.endswith('test_module'): def load_tests(loader, tests, pattern): self.load_tests_args.append((loader, tests, pattern)) return [self.path + ' load_tests'] else: def load_tests(loader, tests, pattern): self.load_tests_args.append((loader, tests, pattern)) # top level directory cached on loader instance __file__ = '/foo/my_package/__init__.py' this_dir = os.path.dirname(__file__) pkg_tests = loader.discover( start_dir=this_dir, pattern=pattern) return [self.path + ' load_tests', tests ] + pkg_tests self.load_tests = load_tests def __eq__(self, other): return self.path == other.path loader = unittest.TestLoader() loader._get_module_from_name = lambda name: Module(name) loader.suiteClass = lambda thing: thing loader._top_level_dir = abspath('/foo') # this time no '.py' on the pattern so that it can match # a test package suite = list(loader._find_tests(abspath('/foo'), 'test*.py')) # We should have loaded tests from both my_package and # my_package.test_module, and also run the load_tests hook in both. # (normally this would be nested TestSuites.) self.assertEqual(suite, [['my_package load_tests', [], ['my_package.test_module load_tests']]]) # Parents before children. self.assertEqual(Module.paths, ['my_package', 'my_package.test_module']) # load_tests should have been called twice with loader, tests and pattern self.assertEqual(Module.load_tests_args, [(loader, [], 'test*.py'), (loader, [], 'test*.py')]) def test_discover(self): loader = unittest.TestLoader() original_isfile = os.path.isfile original_isdir = os.path.isdir def restore_isfile(): os.path.isfile = original_isfile os.path.isfile = lambda path: False self.addCleanup(restore_isfile) orig_sys_path = sys.path[:] def restore_path(): sys.path[:] = orig_sys_path self.addCleanup(restore_path) full_path = os.path.abspath(os.path.normpath('/foo')) with self.assertRaises(ImportError): loader.discover('/foo/bar', top_level_dir='/foo') self.assertEqual(loader._top_level_dir, full_path) self.assertIn(full_path, sys.path) os.path.isfile = lambda path: True os.path.isdir = lambda path: True def restore_isdir(): os.path.isdir = original_isdir self.addCleanup(restore_isdir) _find_tests_args = [] def _find_tests(start_dir, pattern, namespace=None): _find_tests_args.append((start_dir, pattern)) return ['tests'] loader._find_tests = _find_tests loader.suiteClass = str suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar') top_level_dir = os.path.abspath('/foo/bar') start_dir = os.path.abspath('/foo/bar/baz') self.assertEqual(suite, "['tests']") self.assertEqual(loader._top_level_dir, top_level_dir) self.assertEqual(_find_tests_args, [(start_dir, 'pattern')]) self.assertIn(top_level_dir, sys.path) def test_discover_start_dir_is_package_calls_package_load_tests(self): # This test verifies that the package load_tests in a package is indeed # invoked when the start_dir is a package (and not the top level). # http://bugs.python.org/issue22457 # Test data: we expect the following: # an isfile to verify the package, then importing and scanning # as per _find_tests' normal behaviour. # We expect to see our load_tests hook called once. vfs = {abspath('/toplevel'): ['startdir'], abspath('/toplevel/startdir'): ['__init__.py']} def list_dir(path): return list(vfs[path]) self.addCleanup(setattr, os, 'listdir', os.listdir) os.listdir = list_dir self.addCleanup(setattr, os.path, 'isfile', os.path.isfile) os.path.isfile = lambda path: path.endswith('.py') self.addCleanup(setattr, os.path, 'isdir', os.path.isdir) os.path.isdir = lambda path: not path.endswith('.py') self.addCleanup(sys.path.remove, abspath('/toplevel')) class Module(object): paths = [] load_tests_args = [] def __init__(self, path): self.path = path def load_tests(self, loader, tests, pattern): return ['load_tests called ' + self.path] def __eq__(self, other): return self.path == other.path loader = unittest.TestLoader() loader._get_module_from_name = lambda name: Module(name) loader.suiteClass = lambda thing: thing suite = loader.discover('/toplevel/startdir', top_level_dir='/toplevel') # We should have loaded tests from the package __init__. # (normally this would be nested TestSuites.) self.assertEqual(suite, [['load_tests called startdir']]) def setup_import_issue_tests(self, fakefile): listdir = os.listdir os.listdir = lambda _: [fakefile] isfile = os.path.isfile os.path.isfile = lambda _: True orig_sys_path = sys.path[:] def restore(): os.path.isfile = isfile os.listdir = listdir sys.path[:] = orig_sys_path self.addCleanup(restore) def setup_import_issue_package_tests(self, vfs): self.addCleanup(setattr, os, 'listdir', os.listdir) self.addCleanup(setattr, os.path, 'isfile', os.path.isfile) self.addCleanup(setattr, os.path, 'isdir', os.path.isdir) self.addCleanup(sys.path.__setitem__, slice(None), list(sys.path)) def list_dir(path): return list(vfs[path]) os.listdir = list_dir os.path.isdir = lambda path: not path.endswith('.py') os.path.isfile = lambda path: path.endswith('.py') def test_discover_with_modules_that_fail_to_import(self): loader = unittest.TestLoader() self.setup_import_issue_tests('test_this_does_not_exist.py') suite = loader.discover('.') self.assertIn(os.getcwd(), sys.path) self.assertEqual(suite.countTestCases(), 1) # Errors loading the suite are also captured for introspection. self.assertNotEqual([], loader.errors) self.assertEqual(1, len(loader.errors)) error = loader.errors[0] self.assertTrue( 'Failed to import test module: test_this_does_not_exist' in error, 'missing error string in %r' % error) test = list(list(suite)[0])[0] # extract test from suite with self.assertRaises(ImportError): test.test_this_does_not_exist() def test_discover_with_init_modules_that_fail_to_import(self): vfs = {abspath('/foo'): ['my_package'], abspath('/foo/my_package'): ['__init__.py', 'test_module.py']} self.setup_import_issue_package_tests(vfs) import_calls = [] def _get_module_from_name(name): import_calls.append(name) raise ImportError("Cannot import Name") loader = unittest.TestLoader() loader._get_module_from_name = _get_module_from_name suite = loader.discover(abspath('/foo')) self.assertIn(abspath('/foo'), sys.path) self.assertEqual(suite.countTestCases(), 1) # Errors loading the suite are also captured for introspection. self.assertNotEqual([], loader.errors) self.assertEqual(1, len(loader.errors)) error = loader.errors[0] self.assertTrue( 'Failed to import test module: my_package' in error, 'missing error string in %r' % error) test = list(list(suite)[0])[0] # extract test from suite with self.assertRaises(ImportError): test.my_package() self.assertEqual(import_calls, ['my_package']) # Check picklability for proto in range(pickle.HIGHEST_PROTOCOL + 1): pickle.loads(pickle.dumps(test, proto)) def test_discover_with_module_that_raises_SkipTest_on_import(self): if not unittest.BaseTestSuite._cleanup: raise unittest.SkipTest("Suite cleanup is disabled") loader = unittest.TestLoader() def _get_module_from_name(name): raise unittest.SkipTest('skipperoo') loader._get_module_from_name = _get_module_from_name self.setup_import_issue_tests('test_skip_dummy.py') suite = loader.discover('.') self.assertEqual(suite.countTestCases(), 1) result = unittest.TestResult() suite.run(result) self.assertEqual(len(result.skipped), 1) # Check picklability for proto in range(pickle.HIGHEST_PROTOCOL + 1): pickle.loads(pickle.dumps(suite, proto)) def test_discover_with_init_module_that_raises_SkipTest_on_import(self): if not unittest.BaseTestSuite._cleanup: raise unittest.SkipTest("Suite cleanup is disabled") vfs = {abspath('/foo'): ['my_package'], abspath('/foo/my_package'): ['__init__.py', 'test_module.py']} self.setup_import_issue_package_tests(vfs) import_calls = [] def _get_module_from_name(name): import_calls.append(name) raise unittest.SkipTest('skipperoo') loader = unittest.TestLoader() loader._get_module_from_name = _get_module_from_name suite = loader.discover(abspath('/foo')) self.assertIn(abspath('/foo'), sys.path) self.assertEqual(suite.countTestCases(), 1) result = unittest.TestResult() suite.run(result) self.assertEqual(len(result.skipped), 1) self.assertEqual(result.testsRun, 1) self.assertEqual(import_calls, ['my_package']) # Check picklability for proto in range(pickle.HIGHEST_PROTOCOL + 1): pickle.loads(pickle.dumps(suite, proto)) def test_command_line_handling_parseArgs(self): program = TestableTestProgram() args = [] program._do_discovery = args.append program.parseArgs(['something', 'discover']) self.assertEqual(args, [[]]) args[:] = [] program.parseArgs(['something', 'discover', 'foo', 'bar']) self.assertEqual(args, [['foo', 'bar']]) def test_command_line_handling_discover_by_default(self): program = TestableTestProgram() args = [] program._do_discovery = args.append program.parseArgs(['something']) self.assertEqual(args, [[]]) self.assertEqual(program.verbosity, 1) self.assertIs(program.buffer, False) self.assertIs(program.catchbreak, False) self.assertIs(program.failfast, False) def test_command_line_handling_discover_by_default_with_options(self): program = TestableTestProgram() args = [] program._do_discovery = args.append program.parseArgs(['something', '-v', '-b', '-v', '-c', '-f']) self.assertEqual(args, [[]]) self.assertEqual(program.verbosity, 2) self.assertIs(program.buffer, True) self.assertIs(program.catchbreak, True) self.assertIs(program.failfast, True) def test_command_line_handling_do_discovery_too_many_arguments(self): program = TestableTestProgram() program.testLoader = None with support.captured_stderr() as stderr, \ self.assertRaises(SystemExit) as cm: # too many args program._do_discovery(['one', 'two', 'three', 'four']) self.assertEqual(cm.exception.args, (2,)) self.assertIn('usage:', stderr.getvalue()) def test_command_line_handling_do_discovery_uses_default_loader(self): program = object.__new__(unittest.TestProgram) program._initArgParsers() class Loader(object): args = [] def discover(self, start_dir, pattern, top_level_dir): self.args.append((start_dir, pattern, top_level_dir)) return 'tests' program.testLoader = Loader() program._do_discovery(['-v']) self.assertEqual(Loader.args, [('.', 'test*.py', None)]) def test_command_line_handling_do_discovery_calls_loader(self): program = TestableTestProgram() class Loader(object): args = [] def discover(self, start_dir, pattern, top_level_dir): self.args.append((start_dir, pattern, top_level_dir)) return 'tests' program._do_discovery(['-v'], Loader=Loader) self.assertEqual(program.verbosity, 2) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['--verbose'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery([], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['fish', 'eggs'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-s', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-t', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-p', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'fish', None)]) self.assertFalse(program.failfast) self.assertFalse(program.catchbreak) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f', '-c'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', None)]) self.assertEqual(program.verbosity, 2) self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) def setup_module_clash(self): class Module(object): __file__ = 'bar/foo.py' sys.modules['foo'] = Module full_path = os.path.abspath('foo') original_listdir = os.listdir original_isfile = os.path.isfile original_isdir = os.path.isdir def cleanup(): os.listdir = original_listdir os.path.isfile = original_isfile os.path.isdir = original_isdir del sys.modules['foo'] if full_path in sys.path: sys.path.remove(full_path) self.addCleanup(cleanup) def listdir(_): return ['foo.py'] def isfile(_): return True def isdir(_): return True os.listdir = listdir os.path.isfile = isfile os.path.isdir = isdir return full_path def test_detect_module_clash(self): full_path = self.setup_module_clash() loader = unittest.TestLoader() mod_dir = os.path.abspath('bar') expected_dir = os.path.abspath('foo') msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " "Is this module globally installed?" % (mod_dir, expected_dir)) self.assertRaisesRegex( ImportError, '^%s$' % msg, loader.discover, start_dir='foo', pattern='foo.py' ) self.assertEqual(sys.path[0], full_path) def test_module_symlink_ok(self): full_path = self.setup_module_clash() original_realpath = os.path.realpath mod_dir = os.path.abspath('bar') expected_dir = os.path.abspath('foo') def cleanup(): os.path.realpath = original_realpath self.addCleanup(cleanup) def realpath(path): if path == os.path.join(mod_dir, 'foo.py'): return os.path.join(expected_dir, 'foo.py') return path os.path.realpath = realpath loader = unittest.TestLoader() loader.discover(start_dir='foo', pattern='foo.py') def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False def _find_tests(start_dir, pattern, namespace=None): self.wasRun = True self.assertEqual(start_dir, expectedPath) return tests loader._find_tests = _find_tests suite = loader.discover('unittest.test') self.assertTrue(self.wasRun) self.assertEqual(suite._tests, tests) def test_discovery_from_dotted_path_builtin_modules(self): loader = unittest.TestLoader() listdir = os.listdir os.listdir = lambda _: ['test_this_does_not_exist.py'] isfile = os.path.isfile isdir = os.path.isdir os.path.isdir = lambda _: False orig_sys_path = sys.path[:] def restore(): os.path.isfile = isfile os.path.isdir = isdir os.listdir = listdir sys.path[:] = orig_sys_path self.addCleanup(restore) with self.assertRaises(TypeError) as cm: loader.discover('sys') self.assertEqual(str(cm.exception), 'Can not use builtin modules ' 'as dotted module names') def test_discovery_from_dotted_namespace_packages(self): loader = unittest.TestLoader() package = types.ModuleType('package') package.__path__ = ['/a', '/b'] package.__spec__ = types.SimpleNamespace( loader=None, submodule_search_locations=['/a', '/b'] ) def _import(packagename, *args, **kwargs): sys.modules[packagename] = package return package _find_tests_args = [] def _find_tests(start_dir, pattern, namespace=None): _find_tests_args.append((start_dir, pattern)) return ['%s/tests' % start_dir] loader._find_tests = _find_tests loader.suiteClass = list with unittest.mock.patch('builtins.__import__', _import): # Since loader.discover() can modify sys.path, restore it when done. with support.DirsOnSysPath(): # Make sure to remove 'package' from sys.modules when done. with test.test_importlib.util.uncache('package'): suite = loader.discover('package') self.assertEqual(suite, ['/a/tests', '/b/tests']) def test_discovery_failed_discovery(self): loader = unittest.TestLoader() package = types.ModuleType('package') def _import(packagename, *args, **kwargs): sys.modules[packagename] = package return package with unittest.mock.patch('builtins.__import__', _import): # Since loader.discover() can modify sys.path, restore it when done. with support.DirsOnSysPath(): # Make sure to remove 'package' from sys.modules when done. with test.test_importlib.util.uncache('package'): with self.assertRaises(TypeError) as cm: loader.discover('package') self.assertEqual(str(cm.exception), 'don\'t know how to discover from {!r}' .format(package)) if __name__ == '__main__': unittest.main()
33,693
874
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/__init__.py
import os import sys import unittest here = os.path.dirname(__file__) loader = unittest.defaultTestLoader def suite(): suite = unittest.TestSuite() for fn in os.listdir(here): if fn.startswith("test") and fn.endswith(".py"): modname = "unittest.test." + fn[:-3] __import__(modname) module = sys.modules[modname] suite.addTest(loader.loadTestsFromModule(module)) suite.addTest(loader.loadTestsFromName('unittest.test.testmock')) return suite if __name__ == "__main__": unittest.main(defaultTest="suite")
584
23
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testhelpers.py
import time import types import unittest from unittest.mock import ( call, _Call, create_autospec, MagicMock, Mock, ANY, _CallList, patch, PropertyMock ) from datetime import datetime class SomeClass(object): def one(self, a, b): pass def two(self): pass def three(self, a=None): pass class AnyTest(unittest.TestCase): def test_any(self): self.assertEqual(ANY, object()) mock = Mock() mock(ANY) mock.assert_called_with(ANY) mock = Mock() mock(foo=ANY) mock.assert_called_with(foo=ANY) def test_repr(self): self.assertEqual(repr(ANY), '<ANY>') self.assertEqual(str(ANY), '<ANY>') def test_any_and_datetime(self): mock = Mock() mock(datetime.now(), foo=datetime.now()) mock.assert_called_with(ANY, foo=ANY) def test_any_mock_calls_comparison_order(self): mock = Mock() d = datetime.now() class Foo(object): def __eq__(self, other): return False def __ne__(self, other): return True for d in datetime.now(), Foo(): mock.reset_mock() mock(d, foo=d, bar=d) mock.method(d, zinga=d, alpha=d) mock().method(a1=d, z99=d) expected = [ call(ANY, foo=ANY, bar=ANY), call.method(ANY, zinga=ANY, alpha=ANY), call(), call().method(a1=ANY, z99=ANY) ] self.assertEqual(expected, mock.mock_calls) self.assertEqual(mock.mock_calls, expected) class CallTest(unittest.TestCase): def test_call_with_call(self): kall = _Call() self.assertEqual(kall, _Call()) self.assertEqual(kall, _Call(('',))) self.assertEqual(kall, _Call(((),))) self.assertEqual(kall, _Call(({},))) self.assertEqual(kall, _Call(('', ()))) self.assertEqual(kall, _Call(('', {}))) self.assertEqual(kall, _Call(('', (), {}))) self.assertEqual(kall, _Call(('foo',))) self.assertEqual(kall, _Call(('bar', ()))) self.assertEqual(kall, _Call(('baz', {}))) self.assertEqual(kall, _Call(('spam', (), {}))) kall = _Call(((1, 2, 3),)) self.assertEqual(kall, _Call(((1, 2, 3),))) self.assertEqual(kall, _Call(('', (1, 2, 3)))) self.assertEqual(kall, _Call(((1, 2, 3), {}))) self.assertEqual(kall, _Call(('', (1, 2, 3), {}))) kall = _Call(((1, 2, 4),)) self.assertNotEqual(kall, _Call(('', (1, 2, 3)))) self.assertNotEqual(kall, _Call(('', (1, 2, 3), {}))) kall = _Call(('foo', (1, 2, 4),)) self.assertNotEqual(kall, _Call(('', (1, 2, 4)))) self.assertNotEqual(kall, _Call(('', (1, 2, 4), {}))) self.assertNotEqual(kall, _Call(('bar', (1, 2, 4)))) self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {}))) kall = _Call(({'a': 3},)) self.assertEqual(kall, _Call(('', (), {'a': 3}))) self.assertEqual(kall, _Call(('', {'a': 3}))) self.assertEqual(kall, _Call(((), {'a': 3}))) self.assertEqual(kall, _Call(({'a': 3},))) def test_empty__Call(self): args = _Call() self.assertEqual(args, ()) self.assertEqual(args, ('foo',)) self.assertEqual(args, ((),)) self.assertEqual(args, ('foo', ())) self.assertEqual(args, ('foo',(), {})) self.assertEqual(args, ('foo', {})) self.assertEqual(args, ({},)) def test_named_empty_call(self): args = _Call(('foo', (), {})) self.assertEqual(args, ('foo',)) self.assertEqual(args, ('foo', ())) self.assertEqual(args, ('foo',(), {})) self.assertEqual(args, ('foo', {})) self.assertNotEqual(args, ((),)) self.assertNotEqual(args, ()) self.assertNotEqual(args, ({},)) self.assertNotEqual(args, ('bar',)) self.assertNotEqual(args, ('bar', ())) self.assertNotEqual(args, ('bar', {})) def test_call_with_args(self): args = _Call(((1, 2, 3), {})) self.assertEqual(args, ((1, 2, 3),)) self.assertEqual(args, ('foo', (1, 2, 3))) self.assertEqual(args, ('foo', (1, 2, 3), {})) self.assertEqual(args, ((1, 2, 3), {})) def test_named_call_with_args(self): args = _Call(('foo', (1, 2, 3), {})) self.assertEqual(args, ('foo', (1, 2, 3))) self.assertEqual(args, ('foo', (1, 2, 3), {})) self.assertNotEqual(args, ((1, 2, 3),)) self.assertNotEqual(args, ((1, 2, 3), {})) def test_call_with_kwargs(self): args = _Call(((), dict(a=3, b=4))) self.assertEqual(args, (dict(a=3, b=4),)) self.assertEqual(args, ('foo', dict(a=3, b=4))) self.assertEqual(args, ('foo', (), dict(a=3, b=4))) self.assertEqual(args, ((), dict(a=3, b=4))) def test_named_call_with_kwargs(self): args = _Call(('foo', (), dict(a=3, b=4))) self.assertEqual(args, ('foo', dict(a=3, b=4))) self.assertEqual(args, ('foo', (), dict(a=3, b=4))) self.assertNotEqual(args, (dict(a=3, b=4),)) self.assertNotEqual(args, ((), dict(a=3, b=4))) def test_call_with_args_call_empty_name(self): args = _Call(((1, 2, 3), {})) self.assertEqual(args, call(1, 2, 3)) self.assertEqual(call(1, 2, 3), args) self.assertIn(call(1, 2, 3), [args]) def test_call_ne(self): self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2)) self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3)) self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3)) def test_call_non_tuples(self): kall = _Call(((1, 2, 3),)) for value in 1, None, self, int: self.assertNotEqual(kall, value) self.assertFalse(kall == value) def test_repr(self): self.assertEqual(repr(_Call()), 'call()') self.assertEqual(repr(_Call(('foo',))), 'call.foo()') self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))), "call(1, 2, 3, a='b')") self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))), "call.bar(1, 2, 3, a='b')") self.assertEqual(repr(call), 'call') self.assertEqual(str(call), 'call') self.assertEqual(repr(call()), 'call()') self.assertEqual(repr(call(1)), 'call(1)') self.assertEqual(repr(call(zz='thing')), "call(zz='thing')") self.assertEqual(repr(call().foo), 'call().foo') self.assertEqual(repr(call(1).foo.bar(a=3).bing), 'call().foo.bar().bing') self.assertEqual( repr(call().foo(1, 2, a=3)), "call().foo(1, 2, a=3)" ) self.assertEqual(repr(call()()), "call()()") self.assertEqual(repr(call(1)(2)), "call()(2)") self.assertEqual( repr(call()().bar().baz.beep(1)), "call()().bar().baz.beep(1)" ) def test_call(self): self.assertEqual(call(), ('', (), {})) self.assertEqual(call('foo', 'bar', one=3, two=4), ('', ('foo', 'bar'), {'one': 3, 'two': 4})) mock = Mock() mock(1, 2, 3) mock(a=3, b=6) self.assertEqual(mock.call_args_list, [call(1, 2, 3), call(a=3, b=6)]) def test_attribute_call(self): self.assertEqual(call.foo(1), ('foo', (1,), {})) self.assertEqual(call.bar.baz(fish='eggs'), ('bar.baz', (), {'fish': 'eggs'})) mock = Mock() mock.foo(1, 2 ,3) mock.bar.baz(a=3, b=6) self.assertEqual(mock.method_calls, [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)]) def test_extended_call(self): result = call(1).foo(2).bar(3, a=4) self.assertEqual(result, ('().foo().bar', (3,), dict(a=4))) mock = MagicMock() mock(1, 2, a=3, b=4) self.assertEqual(mock.call_args, call(1, 2, a=3, b=4)) self.assertNotEqual(mock.call_args, call(1, 2, 3)) self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)]) self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)]) mock = MagicMock() mock.foo(1).bar()().baz.beep(a=6) last_call = call.foo(1).bar()().baz.beep(a=6) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock.mock_calls, last_call.call_list()) def test_extended_not_equal(self): a = call(x=1).foo b = call(x=2).foo self.assertEqual(a, a) self.assertEqual(b, b) self.assertNotEqual(a, b) def test_nested_calls_not_equal(self): a = call(x=1).foo().bar b = call(x=2).foo().bar self.assertEqual(a, a) self.assertEqual(b, b) self.assertNotEqual(a, b) def test_call_list(self): mock = MagicMock() mock(1) self.assertEqual(call(1).call_list(), mock.mock_calls) mock = MagicMock() mock(1).method(2) self.assertEqual(call(1).method(2).call_list(), mock.mock_calls) mock = MagicMock() mock(1).method(2)(3) self.assertEqual(call(1).method(2)(3).call_list(), mock.mock_calls) mock = MagicMock() int(mock(1).method(2)(3).foo.bar.baz(4)(5)) kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__() self.assertEqual(kall.call_list(), mock.mock_calls) def test_call_any(self): self.assertEqual(call, ANY) m = MagicMock() int(m) self.assertEqual(m.mock_calls, [ANY]) self.assertEqual([ANY], m.mock_calls) def test_two_args_call(self): args = _Call(((1, 2), {'a': 3}), two=True) self.assertEqual(len(args), 2) self.assertEqual(args[0], (1, 2)) self.assertEqual(args[1], {'a': 3}) other_args = _Call(((1, 2), {'a': 3})) self.assertEqual(args, other_args) def test_call_with_name(self): self.assertEqual(_Call((), 'foo')[0], 'foo') self.assertEqual(_Call((('bar', 'barz'),),)[0], '') self.assertEqual(_Call((('bar', 'barz'), {'hello': 'world'}),)[0], '') class SpecSignatureTest(unittest.TestCase): def _check_someclass_mock(self, mock): self.assertRaises(AttributeError, getattr, mock, 'foo') mock.one(1, 2) mock.one.assert_called_with(1, 2) self.assertRaises(AssertionError, mock.one.assert_called_with, 3, 4) self.assertRaises(TypeError, mock.one, 1) mock.two() mock.two.assert_called_with() self.assertRaises(AssertionError, mock.two.assert_called_with, 3) self.assertRaises(TypeError, mock.two, 1) mock.three() mock.three.assert_called_with() self.assertRaises(AssertionError, mock.three.assert_called_with, 3) self.assertRaises(TypeError, mock.three, 3, 2) mock.three(1) mock.three.assert_called_with(1) mock.three(a=1) mock.three.assert_called_with(a=1) def test_basic(self): mock = create_autospec(SomeClass) self._check_someclass_mock(mock) mock = create_autospec(SomeClass()) self._check_someclass_mock(mock) def test_create_autospec_return_value(self): def f(): pass mock = create_autospec(f, return_value='foo') self.assertEqual(mock(), 'foo') class Foo(object): pass mock = create_autospec(Foo, return_value='foo') self.assertEqual(mock(), 'foo') def test_autospec_reset_mock(self): m = create_autospec(int) int(m) m.reset_mock() self.assertEqual(m.__int__.call_count, 0) def test_mocking_unbound_methods(self): class Foo(object): def foo(self, foo): pass p = patch.object(Foo, 'foo') mock_foo = p.start() Foo().foo(1) mock_foo.assert_called_with(1) def test_create_autospec_unbound_methods(self): # see mock issue 128 # this is expected to fail until the issue is fixed return class Foo(object): def foo(self): pass klass = create_autospec(Foo) instance = klass() self.assertRaises(TypeError, instance.foo, 1) # Note: no type checking on the "self" parameter klass.foo(1) klass.foo.assert_called_with(1) self.assertRaises(TypeError, klass.foo) def test_create_autospec_keyword_arguments(self): class Foo(object): a = 3 m = create_autospec(Foo, a='3') self.assertEqual(m.a, '3') def test_create_autospec_keyword_only_arguments(self): def foo(a, *, b=None): pass m = create_autospec(foo) m(1) m.assert_called_with(1) self.assertRaises(TypeError, m, 1, 2) m(2, b=3) m.assert_called_with(2, b=3) def test_function_as_instance_attribute(self): obj = SomeClass() def f(a): pass obj.f = f mock = create_autospec(obj) mock.f('bing') mock.f.assert_called_with('bing') def test_spec_as_list(self): # because spec as a list of strings in the mock constructor means # something very different we treat a list instance as the type. mock = create_autospec([]) mock.append('foo') mock.append.assert_called_with('foo') self.assertRaises(AttributeError, getattr, mock, 'foo') class Foo(object): foo = [] mock = create_autospec(Foo) mock.foo.append(3) mock.foo.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock.foo, 'foo') def test_attributes(self): class Sub(SomeClass): attr = SomeClass() sub_mock = create_autospec(Sub) for mock in (sub_mock, sub_mock.attr): self._check_someclass_mock(mock) def test_builtin_functions_types(self): # we could replace builtin functions / methods with a function # with *args / **kwargs signature. Using the builtin method type # as a spec seems to work fairly well though. class BuiltinSubclass(list): def bar(self, arg): pass sorted = sorted attr = {} mock = create_autospec(BuiltinSubclass) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock.append, 'foo') mock.bar('foo') mock.bar.assert_called_with('foo') self.assertRaises(TypeError, mock.bar, 'foo', 'bar') self.assertRaises(AttributeError, getattr, mock.bar, 'foo') mock.sorted([1, 2]) mock.sorted.assert_called_with([1, 2]) self.assertRaises(AttributeError, getattr, mock.sorted, 'foo') mock.attr.pop(3) mock.attr.pop.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock.attr, 'foo') def test_method_calls(self): class Sub(SomeClass): attr = SomeClass() mock = create_autospec(Sub) mock.one(1, 2) mock.two() mock.three(3) expected = [call.one(1, 2), call.two(), call.three(3)] self.assertEqual(mock.method_calls, expected) mock.attr.one(1, 2) mock.attr.two() mock.attr.three(3) expected.extend( [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)] ) self.assertEqual(mock.method_calls, expected) def test_magic_methods(self): class BuiltinSubclass(list): attr = {} mock = create_autospec(BuiltinSubclass) self.assertEqual(list(mock), []) self.assertRaises(TypeError, int, mock) self.assertRaises(TypeError, int, mock.attr) self.assertEqual(list(mock), []) self.assertIsInstance(mock['foo'], MagicMock) self.assertIsInstance(mock.attr['foo'], MagicMock) def test_spec_set(self): class Sub(SomeClass): attr = SomeClass() for spec in (Sub, Sub()): mock = create_autospec(spec, spec_set=True) self._check_someclass_mock(mock) self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar') self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar') def test_descriptors(self): class Foo(object): @classmethod def f(cls, a, b): pass @staticmethod def g(a, b): pass class Bar(Foo): pass class Baz(SomeClass, Bar): pass for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()): mock = create_autospec(spec) mock.f(1, 2) mock.f.assert_called_once_with(1, 2) mock.g(3, 4) mock.g.assert_called_once_with(3, 4) def test_recursive(self): class A(object): def a(self): pass foo = 'foo bar baz' bar = foo A.B = A mock = create_autospec(A) mock() self.assertFalse(mock.B.called) mock.a() mock.B.a() self.assertEqual(mock.method_calls, [call.a(), call.B.a()]) self.assertIs(A.foo, A.bar) self.assertIsNot(mock.foo, mock.bar) mock.foo.lower() self.assertRaises(AssertionError, mock.bar.lower.assert_called_with) def test_spec_inheritance_for_classes(self): class Foo(object): def a(self, x): pass class Bar(object): def f(self, y): pass class_mock = create_autospec(Foo) self.assertIsNot(class_mock, class_mock()) for this_mock in class_mock, class_mock(): this_mock.a(x=5) this_mock.a.assert_called_with(x=5) this_mock.a.assert_called_with(5) self.assertRaises(TypeError, this_mock.a, 'foo', 'bar') self.assertRaises(AttributeError, getattr, this_mock, 'b') instance_mock = create_autospec(Foo()) instance_mock.a(5) instance_mock.a.assert_called_with(5) instance_mock.a.assert_called_with(x=5) self.assertRaises(TypeError, instance_mock.a, 'foo', 'bar') self.assertRaises(AttributeError, getattr, instance_mock, 'b') # The return value isn't isn't callable self.assertRaises(TypeError, instance_mock) instance_mock.Bar.f(6) instance_mock.Bar.f.assert_called_with(6) instance_mock.Bar.f.assert_called_with(y=6) self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g') instance_mock.Bar().f(6) instance_mock.Bar().f.assert_called_with(6) instance_mock.Bar().f.assert_called_with(y=6) self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g') def test_inherit(self): class Foo(object): a = 3 Foo.Foo = Foo # class mock = create_autospec(Foo) instance = mock() self.assertRaises(AttributeError, getattr, instance, 'b') attr_instance = mock.Foo() self.assertRaises(AttributeError, getattr, attr_instance, 'b') # instance mock = create_autospec(Foo()) self.assertRaises(AttributeError, getattr, mock, 'b') self.assertRaises(TypeError, mock) # attribute instance call_result = mock.Foo() self.assertRaises(AttributeError, getattr, call_result, 'b') def test_builtins(self): # used to fail with infinite recursion create_autospec(1) create_autospec(int) create_autospec('foo') create_autospec(str) create_autospec({}) create_autospec(dict) create_autospec([]) create_autospec(list) create_autospec(set()) create_autospec(set) create_autospec(1.0) create_autospec(float) create_autospec(1j) create_autospec(complex) create_autospec(False) create_autospec(True) def test_function(self): def f(a, b): pass mock = create_autospec(f) self.assertRaises(TypeError, mock) mock(1, 2) mock.assert_called_with(1, 2) mock.assert_called_with(1, b=2) mock.assert_called_with(a=1, b=2) f.f = f mock = create_autospec(f) self.assertRaises(TypeError, mock.f) mock.f(3, 4) mock.f.assert_called_with(3, 4) mock.f.assert_called_with(a=3, b=4) def test_skip_attributeerrors(self): class Raiser(object): def __get__(self, obj, type=None): if obj is None: raise AttributeError('Can only be accessed via an instance') class RaiserClass(object): raiser = Raiser() @staticmethod def existing(a, b): return a + b s = create_autospec(RaiserClass) self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3)) s.existing(1, 2) self.assertRaises(AttributeError, lambda: s.nonexisting) # check we can fetch the raiser attribute and it has no spec obj = s.raiser obj.foo, obj.bar def test_signature_class(self): class Foo(object): def __init__(self, a, b=3): pass mock = create_autospec(Foo) self.assertRaises(TypeError, mock) mock(1) mock.assert_called_once_with(1) mock.assert_called_once_with(a=1) self.assertRaises(AssertionError, mock.assert_called_once_with, 2) mock(4, 5) mock.assert_called_with(4, 5) mock.assert_called_with(a=4, b=5) self.assertRaises(AssertionError, mock.assert_called_with, a=5, b=4) def test_class_with_no_init(self): # this used to raise an exception # due to trying to get a signature from object.__init__ class Foo(object): pass create_autospec(Foo) def test_signature_callable(self): class Callable(object): def __init__(self, x, y): pass def __call__(self, a): pass mock = create_autospec(Callable) mock(1, 2) mock.assert_called_once_with(1, 2) mock.assert_called_once_with(x=1, y=2) self.assertRaises(TypeError, mock, 'a') instance = mock(1, 2) self.assertRaises(TypeError, instance) instance(a='a') instance.assert_called_once_with('a') instance.assert_called_once_with(a='a') instance('a') instance.assert_called_with('a') instance.assert_called_with(a='a') mock = create_autospec(Callable(1, 2)) mock(a='a') mock.assert_called_once_with(a='a') self.assertRaises(TypeError, mock) mock('a') mock.assert_called_with('a') def test_signature_noncallable(self): class NonCallable(object): def __init__(self): pass mock = create_autospec(NonCallable) instance = mock() mock.assert_called_once_with() self.assertRaises(TypeError, mock, 'a') self.assertRaises(TypeError, instance) self.assertRaises(TypeError, instance, 'a') mock = create_autospec(NonCallable()) self.assertRaises(TypeError, mock) self.assertRaises(TypeError, mock, 'a') def test_create_autospec_none(self): class Foo(object): bar = None mock = create_autospec(Foo) none = mock.bar self.assertNotIsInstance(none, type(None)) none.foo() none.foo.assert_called_once_with() def test_autospec_functions_with_self_in_odd_place(self): class Foo(object): def f(a, self): pass a = create_autospec(Foo) a.f(10) a.f.assert_called_with(10) a.f.assert_called_with(self=10) a.f(self=10) a.f.assert_called_with(10) a.f.assert_called_with(self=10) def test_autospec_data_descriptor(self): class Descriptor(object): def __init__(self, value): self.value = value def __get__(self, obj, cls=None): if obj is None: return self return self.value def __set__(self, obj, value): pass class MyProperty(property): pass class Foo(object): __slots__ = ['slot'] @property def prop(self): return 3 @MyProperty def subprop(self): return 4 desc = Descriptor(42) foo = create_autospec(Foo) def check_data_descriptor(mock_attr): # Data descriptors don't have a spec. self.assertIsInstance(mock_attr, MagicMock) mock_attr(1, 2, 3) mock_attr.abc(4, 5, 6) mock_attr.assert_called_once_with(1, 2, 3) mock_attr.abc.assert_called_once_with(4, 5, 6) # property check_data_descriptor(foo.prop) # property subclass check_data_descriptor(foo.subprop) # class __slot__ check_data_descriptor(foo.slot) # plain data descriptor check_data_descriptor(foo.desc) def test_autospec_on_bound_builtin_function(self): meth = types.MethodType(time.ctime, time.time()) self.assertIsInstance(meth(), str) mocked = create_autospec(meth) # no signature, so no spec to check against mocked() mocked.assert_called_once_with() mocked.reset_mock() mocked(4, 5, 6) mocked.assert_called_once_with(4, 5, 6) class TestCallList(unittest.TestCase): def test_args_list_contains_call_list(self): mock = Mock() self.assertIsInstance(mock.call_args_list, _CallList) mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) for kall in call(1, 2), call(a=3), call(3, 4), call(b=6): self.assertIn(kall, mock.call_args_list) calls = [call(a=3), call(3, 4)] self.assertIn(calls, mock.call_args_list) calls = [call(1, 2), call(a=3)] self.assertIn(calls, mock.call_args_list) calls = [call(3, 4), call(b=6)] self.assertIn(calls, mock.call_args_list) calls = [call(3, 4)] self.assertIn(calls, mock.call_args_list) self.assertNotIn(call('fish'), mock.call_args_list) self.assertNotIn([call('fish')], mock.call_args_list) def test_call_list_str(self): mock = Mock() mock(1, 2) mock.foo(a=3) mock.foo.bar().baz('fish', cat='dog') expected = ( "[call(1, 2),\n" " call.foo(a=3),\n" " call.foo.bar(),\n" " call.foo.bar().baz('fish', cat='dog')]" ) self.assertEqual(str(mock.mock_calls), expected) def test_propertymock(self): p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock) mock = p.start() try: SomeClass.one mock.assert_called_once_with() s = SomeClass() s.one mock.assert_called_with() self.assertEqual(mock.mock_calls, [call(), call()]) s.one = 3 self.assertEqual(mock.mock_calls, [call(), call(), call(3)]) finally: p.stop() def test_propertymock_returnvalue(self): m = MagicMock() p = PropertyMock() type(m).foo = p returned = m.foo p.assert_called_once_with() self.assertIsInstance(returned, MagicMock) self.assertNotIsInstance(returned, PropertyMock) if __name__ == '__main__': unittest.main()
28,210
963
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testpatch.py
# Copyright (C) 2007-2012 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # http://www.voidspace.org.uk/python/mock/ import os import sys import unittest from unittest.test.testmock import support from unittest.test.testmock.support import SomeClass, is_instance from test.test_importlib.util import uncache from unittest.mock import ( NonCallableMock, CallableMixin, sentinel, MagicMock, Mock, NonCallableMagicMock, patch, _patch, DEFAULT, call, _get_target ) builtin_string = 'builtins' PTModule = sys.modules[__name__] MODNAME = '%s.PTModule' % __name__ def _get_proxy(obj, get_only=True): class Proxy(object): def __getattr__(self, name): return getattr(obj, name) if not get_only: def __setattr__(self, name, value): setattr(obj, name, value) def __delattr__(self, name): delattr(obj, name) Proxy.__setattr__ = __setattr__ Proxy.__delattr__ = __delattr__ return Proxy() # for use in the test something = sentinel.Something something_else = sentinel.SomethingElse class Foo(object): def __init__(self, a): pass def f(self, a): pass def g(self): pass foo = 'bar' class Bar(object): def a(self): pass foo_name = '%s.Foo' % __name__ def function(a, b=Foo): pass class Container(object): def __init__(self): self.values = {} def __getitem__(self, name): return self.values[name] def __setitem__(self, name, value): self.values[name] = value def __delitem__(self, name): del self.values[name] def __iter__(self): return iter(self.values) class PatchTest(unittest.TestCase): def assertNotCallable(self, obj, magic=True): MockClass = NonCallableMagicMock if not magic: MockClass = NonCallableMock self.assertRaises(TypeError, obj) self.assertTrue(is_instance(obj, MockClass)) self.assertFalse(is_instance(obj, CallableMixin)) def test_single_patchobject(self): class Something(object): attribute = sentinel.Original @patch.object(Something, 'attribute', sentinel.Patched) def test(): self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") test() self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") def test_patchobject_with_none(self): class Something(object): attribute = sentinel.Original @patch.object(Something, 'attribute', None) def test(): self.assertIsNone(Something.attribute, "unpatched") test() self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") def test_multiple_patchobject(self): class Something(object): attribute = sentinel.Original next_attribute = sentinel.Original2 @patch.object(Something, 'attribute', sentinel.Patched) @patch.object(Something, 'next_attribute', sentinel.Patched2) def test(): self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") self.assertEqual(Something.next_attribute, sentinel.Patched2, "unpatched") test() self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") self.assertEqual(Something.next_attribute, sentinel.Original2, "patch not restored") def test_object_lookup_is_quite_lazy(self): global something original = something @patch('%s.something' % __name__, sentinel.Something2) def test(): pass try: something = sentinel.replacement_value test() self.assertEqual(something, sentinel.replacement_value) finally: something = original def test_patch(self): @patch('%s.something' % __name__, sentinel.Something2) def test(): self.assertEqual(PTModule.something, sentinel.Something2, "unpatched") test() self.assertEqual(PTModule.something, sentinel.Something, "patch not restored") @patch('%s.something' % __name__, sentinel.Something2) @patch('%s.something_else' % __name__, sentinel.SomethingElse) def test(): self.assertEqual(PTModule.something, sentinel.Something2, "unpatched") self.assertEqual(PTModule.something_else, sentinel.SomethingElse, "unpatched") self.assertEqual(PTModule.something, sentinel.Something, "patch not restored") self.assertEqual(PTModule.something_else, sentinel.SomethingElse, "patch not restored") # Test the patching and restoring works a second time test() self.assertEqual(PTModule.something, sentinel.Something, "patch not restored") self.assertEqual(PTModule.something_else, sentinel.SomethingElse, "patch not restored") mock = Mock() mock.return_value = sentinel.Handle @patch('%s.open' % builtin_string, mock) def test(): self.assertEqual(open('filename', 'r'), sentinel.Handle, "open not patched") test() test() self.assertNotEqual(open, mock, "patch not restored") def test_patch_class_attribute(self): @patch('%s.SomeClass.class_attribute' % __name__, sentinel.ClassAttribute) def test(): self.assertEqual(PTModule.SomeClass.class_attribute, sentinel.ClassAttribute, "unpatched") test() self.assertIsNone(PTModule.SomeClass.class_attribute, "patch not restored") def test_patchobject_with_default_mock(self): class Test(object): something = sentinel.Original something2 = sentinel.Original2 @patch.object(Test, 'something') def test(mock): self.assertEqual(mock, Test.something, "Mock not passed into test function") self.assertIsInstance(mock, MagicMock, "patch with two arguments did not create a mock") test() @patch.object(Test, 'something') @patch.object(Test, 'something2') def test(this1, this2, mock1, mock2): self.assertEqual(this1, sentinel.this1, "Patched function didn't receive initial argument") self.assertEqual(this2, sentinel.this2, "Patched function didn't receive second argument") self.assertEqual(mock1, Test.something2, "Mock not passed into test function") self.assertEqual(mock2, Test.something, "Second Mock not passed into test function") self.assertIsInstance(mock2, MagicMock, "patch with two arguments did not create a mock") self.assertIsInstance(mock2, MagicMock, "patch with two arguments did not create a mock") # A hack to test that new mocks are passed the second time self.assertNotEqual(outerMock1, mock1, "unexpected value for mock1") self.assertNotEqual(outerMock2, mock2, "unexpected value for mock1") return mock1, mock2 outerMock1 = outerMock2 = None outerMock1, outerMock2 = test(sentinel.this1, sentinel.this2) # Test that executing a second time creates new mocks test(sentinel.this1, sentinel.this2) def test_patch_with_spec(self): @patch('%s.SomeClass' % __name__, spec=SomeClass) def test(MockSomeClass): self.assertEqual(SomeClass, MockSomeClass) self.assertTrue(is_instance(SomeClass.wibble, MagicMock)) self.assertRaises(AttributeError, lambda: SomeClass.not_wibble) test() def test_patchobject_with_spec(self): @patch.object(SomeClass, 'class_attribute', spec=SomeClass) def test(MockAttribute): self.assertEqual(SomeClass.class_attribute, MockAttribute) self.assertTrue(is_instance(SomeClass.class_attribute.wibble, MagicMock)) self.assertRaises(AttributeError, lambda: SomeClass.class_attribute.not_wibble) test() def test_patch_with_spec_as_list(self): @patch('%s.SomeClass' % __name__, spec=['wibble']) def test(MockSomeClass): self.assertEqual(SomeClass, MockSomeClass) self.assertTrue(is_instance(SomeClass.wibble, MagicMock)) self.assertRaises(AttributeError, lambda: SomeClass.not_wibble) test() def test_patchobject_with_spec_as_list(self): @patch.object(SomeClass, 'class_attribute', spec=['wibble']) def test(MockAttribute): self.assertEqual(SomeClass.class_attribute, MockAttribute) self.assertTrue(is_instance(SomeClass.class_attribute.wibble, MagicMock)) self.assertRaises(AttributeError, lambda: SomeClass.class_attribute.not_wibble) test() def test_nested_patch_with_spec_as_list(self): # regression test for nested decorators @patch('%s.open' % builtin_string) @patch('%s.SomeClass' % __name__, spec=['wibble']) def test(MockSomeClass, MockOpen): self.assertEqual(SomeClass, MockSomeClass) self.assertTrue(is_instance(SomeClass.wibble, MagicMock)) self.assertRaises(AttributeError, lambda: SomeClass.not_wibble) test() def test_patch_with_spec_as_boolean(self): @patch('%s.SomeClass' % __name__, spec=True) def test(MockSomeClass): self.assertEqual(SomeClass, MockSomeClass) # Should not raise attribute error MockSomeClass.wibble self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble) test() def test_patch_object_with_spec_as_boolean(self): @patch.object(PTModule, 'SomeClass', spec=True) def test(MockSomeClass): self.assertEqual(SomeClass, MockSomeClass) # Should not raise attribute error MockSomeClass.wibble self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble) test() def test_patch_class_acts_with_spec_is_inherited(self): @patch('%s.SomeClass' % __name__, spec=True) def test(MockSomeClass): self.assertTrue(is_instance(MockSomeClass, MagicMock)) instance = MockSomeClass() self.assertNotCallable(instance) # Should not raise attribute error instance.wibble self.assertRaises(AttributeError, lambda: instance.not_wibble) test() def test_patch_with_create_mocks_non_existent_attributes(self): @patch('%s.frooble' % builtin_string, sentinel.Frooble, create=True) def test(): self.assertEqual(frooble, sentinel.Frooble) test() self.assertRaises(NameError, lambda: frooble) def test_patchobject_with_create_mocks_non_existent_attributes(self): @patch.object(SomeClass, 'frooble', sentinel.Frooble, create=True) def test(): self.assertEqual(SomeClass.frooble, sentinel.Frooble) test() self.assertFalse(hasattr(SomeClass, 'frooble')) def test_patch_wont_create_by_default(self): try: @patch('%s.frooble' % builtin_string, sentinel.Frooble) def test(): self.assertEqual(frooble, sentinel.Frooble) test() except AttributeError: pass else: self.fail('Patching non existent attributes should fail') self.assertRaises(NameError, lambda: frooble) def test_patchobject_wont_create_by_default(self): try: @patch.object(SomeClass, 'ord', sentinel.Frooble) def test(): self.fail('Patching non existent attributes should fail') test() except AttributeError: pass else: self.fail('Patching non existent attributes should fail') self.assertFalse(hasattr(SomeClass, 'ord')) def test_patch_builtins_without_create(self): @patch(__name__+'.ord') def test_ord(mock_ord): mock_ord.return_value = 101 return ord('c') @patch(__name__+'.open') def test_open(mock_open): m = mock_open.return_value m.read.return_value = 'abcd' fobj = open('doesnotexists.txt') data = fobj.read() fobj.close() return data self.assertEqual(test_ord(), 101) self.assertEqual(test_open(), 'abcd') def test_patch_with_static_methods(self): class Foo(object): @staticmethod def woot(): return sentinel.Static @patch.object(Foo, 'woot', staticmethod(lambda: sentinel.Patched)) def anonymous(): self.assertEqual(Foo.woot(), sentinel.Patched) anonymous() self.assertEqual(Foo.woot(), sentinel.Static) def test_patch_local(self): foo = sentinel.Foo @patch.object(sentinel, 'Foo', 'Foo') def anonymous(): self.assertEqual(sentinel.Foo, 'Foo') anonymous() self.assertEqual(sentinel.Foo, foo) def test_patch_slots(self): class Foo(object): __slots__ = ('Foo',) foo = Foo() foo.Foo = sentinel.Foo @patch.object(foo, 'Foo', 'Foo') def anonymous(): self.assertEqual(foo.Foo, 'Foo') anonymous() self.assertEqual(foo.Foo, sentinel.Foo) def test_patchobject_class_decorator(self): class Something(object): attribute = sentinel.Original class Foo(object): def test_method(other_self): self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") def not_test_method(other_self): self.assertEqual(Something.attribute, sentinel.Original, "non-test method patched") Foo = patch.object(Something, 'attribute', sentinel.Patched)(Foo) f = Foo() f.test_method() f.not_test_method() self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") def test_patch_class_decorator(self): class Something(object): attribute = sentinel.Original class Foo(object): def test_method(other_self, mock_something): self.assertEqual(PTModule.something, mock_something, "unpatched") def not_test_method(other_self): self.assertEqual(PTModule.something, sentinel.Something, "non-test method patched") Foo = patch('%s.something' % __name__)(Foo) f = Foo() f.test_method() f.not_test_method() self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") self.assertEqual(PTModule.something, sentinel.Something, "patch not restored") def test_patchobject_twice(self): class Something(object): attribute = sentinel.Original next_attribute = sentinel.Original2 @patch.object(Something, 'attribute', sentinel.Patched) @patch.object(Something, 'attribute', sentinel.Patched) def test(): self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") test() self.assertEqual(Something.attribute, sentinel.Original, "patch not restored") def test_patch_dict(self): foo = {'initial': object(), 'other': 'something'} original = foo.copy() @patch.dict(foo) def test(): foo['a'] = 3 del foo['initial'] foo['other'] = 'something else' test() self.assertEqual(foo, original) @patch.dict(foo, {'a': 'b'}) def test(): self.assertEqual(len(foo), 3) self.assertEqual(foo['a'], 'b') test() self.assertEqual(foo, original) @patch.dict(foo, [('a', 'b')]) def test(): self.assertEqual(len(foo), 3) self.assertEqual(foo['a'], 'b') test() self.assertEqual(foo, original) def test_patch_dict_with_container_object(self): foo = Container() foo['initial'] = object() foo['other'] = 'something' original = foo.values.copy() @patch.dict(foo) def test(): foo['a'] = 3 del foo['initial'] foo['other'] = 'something else' test() self.assertEqual(foo.values, original) @patch.dict(foo, {'a': 'b'}) def test(): self.assertEqual(len(foo.values), 3) self.assertEqual(foo['a'], 'b') test() self.assertEqual(foo.values, original) def test_patch_dict_with_clear(self): foo = {'initial': object(), 'other': 'something'} original = foo.copy() @patch.dict(foo, clear=True) def test(): self.assertEqual(foo, {}) foo['a'] = 3 foo['other'] = 'something else' test() self.assertEqual(foo, original) @patch.dict(foo, {'a': 'b'}, clear=True) def test(): self.assertEqual(foo, {'a': 'b'}) test() self.assertEqual(foo, original) @patch.dict(foo, [('a', 'b')], clear=True) def test(): self.assertEqual(foo, {'a': 'b'}) test() self.assertEqual(foo, original) def test_patch_dict_with_container_object_and_clear(self): foo = Container() foo['initial'] = object() foo['other'] = 'something' original = foo.values.copy() @patch.dict(foo, clear=True) def test(): self.assertEqual(foo.values, {}) foo['a'] = 3 foo['other'] = 'something else' test() self.assertEqual(foo.values, original) @patch.dict(foo, {'a': 'b'}, clear=True) def test(): self.assertEqual(foo.values, {'a': 'b'}) test() self.assertEqual(foo.values, original) def test_name_preserved(self): foo = {} @patch('%s.SomeClass' % __name__, object()) @patch('%s.SomeClass' % __name__, object(), autospec=True) @patch.object(SomeClass, object()) @patch.dict(foo) def some_name(): pass self.assertEqual(some_name.__name__, 'some_name') def test_patch_with_exception(self): foo = {} @patch.dict(foo, {'a': 'b'}) def test(): raise NameError('Konrad') try: test() except NameError: pass else: self.fail('NameError not raised by test') self.assertEqual(foo, {}) def test_patch_dict_with_string(self): @patch.dict('os.environ', {'konrad_delong': 'some value'}) def test(): self.assertIn('konrad_delong', os.environ) test() def test_patch_descriptor(self): # would be some effort to fix this - we could special case the # builtin descriptors: classmethod, property, staticmethod return class Nothing(object): foo = None class Something(object): foo = {} @patch.object(Nothing, 'foo', 2) @classmethod def klass(cls): self.assertIs(cls, Something) @patch.object(Nothing, 'foo', 2) @staticmethod def static(arg): return arg @patch.dict(foo) @classmethod def klass_dict(cls): self.assertIs(cls, Something) @patch.dict(foo) @staticmethod def static_dict(arg): return arg # these will raise exceptions if patching descriptors is broken self.assertEqual(Something.static('f00'), 'f00') Something.klass() self.assertEqual(Something.static_dict('f00'), 'f00') Something.klass_dict() something = Something() self.assertEqual(something.static('f00'), 'f00') something.klass() self.assertEqual(something.static_dict('f00'), 'f00') something.klass_dict() def test_patch_spec_set(self): @patch('%s.SomeClass' % __name__, spec=SomeClass, spec_set=True) def test(MockClass): MockClass.z = 'foo' self.assertRaises(AttributeError, test) @patch.object(support, 'SomeClass', spec=SomeClass, spec_set=True) def test(MockClass): MockClass.z = 'foo' self.assertRaises(AttributeError, test) @patch('%s.SomeClass' % __name__, spec_set=True) def test(MockClass): MockClass.z = 'foo' self.assertRaises(AttributeError, test) @patch.object(support, 'SomeClass', spec_set=True) def test(MockClass): MockClass.z = 'foo' self.assertRaises(AttributeError, test) def test_spec_set_inherit(self): @patch('%s.SomeClass' % __name__, spec_set=True) def test(MockClass): instance = MockClass() instance.z = 'foo' self.assertRaises(AttributeError, test) def test_patch_start_stop(self): original = something patcher = patch('%s.something' % __name__) self.assertIs(something, original) mock = patcher.start() try: self.assertIsNot(mock, original) self.assertIs(something, mock) finally: patcher.stop() self.assertIs(something, original) def test_stop_without_start(self): patcher = patch(foo_name, 'bar', 3) # calling stop without start used to produce a very obscure error self.assertRaises(RuntimeError, patcher.stop) def test_patchobject_start_stop(self): original = something patcher = patch.object(PTModule, 'something', 'foo') self.assertIs(something, original) replaced = patcher.start() try: self.assertEqual(replaced, 'foo') self.assertIs(something, replaced) finally: patcher.stop() self.assertIs(something, original) def test_patch_dict_start_stop(self): d = {'foo': 'bar'} original = d.copy() patcher = patch.dict(d, [('spam', 'eggs')], clear=True) self.assertEqual(d, original) patcher.start() try: self.assertEqual(d, {'spam': 'eggs'}) finally: patcher.stop() self.assertEqual(d, original) def test_patch_dict_class_decorator(self): this = self d = {'spam': 'eggs'} original = d.copy() class Test(object): def test_first(self): this.assertEqual(d, {'foo': 'bar'}) def test_second(self): this.assertEqual(d, {'foo': 'bar'}) Test = patch.dict(d, {'foo': 'bar'}, clear=True)(Test) self.assertEqual(d, original) test = Test() test.test_first() self.assertEqual(d, original) test.test_second() self.assertEqual(d, original) test = Test() test.test_first() self.assertEqual(d, original) test.test_second() self.assertEqual(d, original) def test_get_only_proxy(self): class Something(object): foo = 'foo' class SomethingElse: foo = 'foo' for thing in Something, SomethingElse, Something(), SomethingElse: proxy = _get_proxy(thing) @patch.object(proxy, 'foo', 'bar') def test(): self.assertEqual(proxy.foo, 'bar') test() self.assertEqual(proxy.foo, 'foo') self.assertEqual(thing.foo, 'foo') self.assertNotIn('foo', proxy.__dict__) def test_get_set_delete_proxy(self): class Something(object): foo = 'foo' class SomethingElse: foo = 'foo' for thing in Something, SomethingElse, Something(), SomethingElse: proxy = _get_proxy(Something, get_only=False) @patch.object(proxy, 'foo', 'bar') def test(): self.assertEqual(proxy.foo, 'bar') test() self.assertEqual(proxy.foo, 'foo') self.assertEqual(thing.foo, 'foo') self.assertNotIn('foo', proxy.__dict__) def test_patch_keyword_args(self): kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} patcher = patch(foo_name, **kwargs) mock = patcher.start() patcher.stop() self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) def test_patch_object_keyword_args(self): kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} patcher = patch.object(Foo, 'f', **kwargs) mock = patcher.start() patcher.stop() self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) def test_patch_dict_keyword_args(self): original = {'foo': 'bar'} copy = original.copy() patcher = patch.dict(original, foo=3, bar=4, baz=5) patcher.start() try: self.assertEqual(original, dict(foo=3, bar=4, baz=5)) finally: patcher.stop() self.assertEqual(original, copy) def test_autospec(self): class Boo(object): def __init__(self, a): pass def f(self, a): pass def g(self): pass foo = 'bar' class Bar(object): def a(self): pass def _test(mock): mock(1) mock.assert_called_with(1) self.assertRaises(TypeError, mock) def _test2(mock): mock.f(1) mock.f.assert_called_with(1) self.assertRaises(TypeError, mock.f) mock.g() mock.g.assert_called_with() self.assertRaises(TypeError, mock.g, 1) self.assertRaises(AttributeError, getattr, mock, 'h') mock.foo.lower() mock.foo.lower.assert_called_with() self.assertRaises(AttributeError, getattr, mock.foo, 'bar') mock.Bar() mock.Bar.assert_called_with() mock.Bar.a() mock.Bar.a.assert_called_with() self.assertRaises(TypeError, mock.Bar.a, 1) mock.Bar().a() mock.Bar().a.assert_called_with() self.assertRaises(TypeError, mock.Bar().a, 1) self.assertRaises(AttributeError, getattr, mock.Bar, 'b') self.assertRaises(AttributeError, getattr, mock.Bar(), 'b') def function(mock): _test(mock) _test2(mock) _test2(mock(1)) self.assertIs(mock, Foo) return mock test = patch(foo_name, autospec=True)(function) mock = test() self.assertIsNot(Foo, mock) # test patching a second time works test() module = sys.modules[__name__] test = patch.object(module, 'Foo', autospec=True)(function) mock = test() self.assertIsNot(Foo, mock) # test patching a second time works test() def test_autospec_function(self): @patch('%s.function' % __name__, autospec=True) def test(mock): function.assert_not_called() self.assertRaises(AssertionError, function.assert_called) self.assertRaises(AssertionError, function.assert_called_once) function(1) self.assertRaises(AssertionError, function.assert_not_called) function.assert_called_with(1) function.assert_called() function.assert_called_once() function(2, 3) function.assert_called_with(2, 3) self.assertRaises(TypeError, function) self.assertRaises(AttributeError, getattr, function, 'foo') test() def test_autospec_keywords(self): @patch('%s.function' % __name__, autospec=True, return_value=3) def test(mock_function): #self.assertEqual(function.abc, 'foo') return function(1, 2) result = test() self.assertEqual(result, 3) def test_autospec_with_new(self): patcher = patch('%s.function' % __name__, new=3, autospec=True) self.assertRaises(TypeError, patcher.start) module = sys.modules[__name__] patcher = patch.object(module, 'function', new=3, autospec=True) self.assertRaises(TypeError, patcher.start) def test_autospec_with_object(self): class Bar(Foo): extra = [] patcher = patch(foo_name, autospec=Bar) mock = patcher.start() try: self.assertIsInstance(mock, Bar) self.assertIsInstance(mock.extra, list) finally: patcher.stop() def test_autospec_inherits(self): FooClass = Foo patcher = patch(foo_name, autospec=True) mock = patcher.start() try: self.assertIsInstance(mock, FooClass) self.assertIsInstance(mock(3), FooClass) finally: patcher.stop() def test_autospec_name(self): patcher = patch(foo_name, autospec=True) mock = patcher.start() try: self.assertIn(" name='Foo'", repr(mock)) self.assertIn(" name='Foo.f'", repr(mock.f)) self.assertIn(" name='Foo()'", repr(mock(None))) self.assertIn(" name='Foo().f'", repr(mock(None).f)) finally: patcher.stop() def test_tracebacks(self): @patch.object(Foo, 'f', object()) def test(): raise AssertionError try: test() except: err = sys.exc_info() result = unittest.TextTestResult(None, None, 0) traceback = result._exc_info_to_string(err, self) self.assertIn('raise AssertionError', traceback) def test_new_callable_patch(self): patcher = patch(foo_name, new_callable=NonCallableMagicMock) m1 = patcher.start() patcher.stop() m2 = patcher.start() patcher.stop() self.assertIsNot(m1, m2) for mock in m1, m2: self.assertNotCallable(m1) def test_new_callable_patch_object(self): patcher = patch.object(Foo, 'f', new_callable=NonCallableMagicMock) m1 = patcher.start() patcher.stop() m2 = patcher.start() patcher.stop() self.assertIsNot(m1, m2) for mock in m1, m2: self.assertNotCallable(m1) def test_new_callable_keyword_arguments(self): class Bar(object): kwargs = None def __init__(self, **kwargs): Bar.kwargs = kwargs patcher = patch(foo_name, new_callable=Bar, arg1=1, arg2=2) m = patcher.start() try: self.assertIs(type(m), Bar) self.assertEqual(Bar.kwargs, dict(arg1=1, arg2=2)) finally: patcher.stop() def test_new_callable_spec(self): class Bar(object): kwargs = None def __init__(self, **kwargs): Bar.kwargs = kwargs patcher = patch(foo_name, new_callable=Bar, spec=Bar) patcher.start() try: self.assertEqual(Bar.kwargs, dict(spec=Bar)) finally: patcher.stop() patcher = patch(foo_name, new_callable=Bar, spec_set=Bar) patcher.start() try: self.assertEqual(Bar.kwargs, dict(spec_set=Bar)) finally: patcher.stop() def test_new_callable_create(self): non_existent_attr = '%s.weeeee' % foo_name p = patch(non_existent_attr, new_callable=NonCallableMock) self.assertRaises(AttributeError, p.start) p = patch(non_existent_attr, new_callable=NonCallableMock, create=True) m = p.start() try: self.assertNotCallable(m, magic=False) finally: p.stop() def test_new_callable_incompatible_with_new(self): self.assertRaises( ValueError, patch, foo_name, new=object(), new_callable=MagicMock ) self.assertRaises( ValueError, patch.object, Foo, 'f', new=object(), new_callable=MagicMock ) def test_new_callable_incompatible_with_autospec(self): self.assertRaises( ValueError, patch, foo_name, new_callable=MagicMock, autospec=True ) self.assertRaises( ValueError, patch.object, Foo, 'f', new_callable=MagicMock, autospec=True ) def test_new_callable_inherit_for_mocks(self): class MockSub(Mock): pass MockClasses = ( NonCallableMock, NonCallableMagicMock, MagicMock, Mock, MockSub ) for Klass in MockClasses: for arg in 'spec', 'spec_set': kwargs = {arg: True} p = patch(foo_name, new_callable=Klass, **kwargs) m = p.start() try: instance = m.return_value self.assertRaises(AttributeError, getattr, instance, 'x') finally: p.stop() def test_new_callable_inherit_non_mock(self): class NotAMock(object): def __init__(self, spec): self.spec = spec p = patch(foo_name, new_callable=NotAMock, spec=True) m = p.start() try: self.assertTrue(is_instance(m, NotAMock)) self.assertRaises(AttributeError, getattr, m, 'return_value') finally: p.stop() self.assertEqual(m.spec, Foo) def test_new_callable_class_decorating(self): test = self original = Foo class SomeTest(object): def _test(self, mock_foo): test.assertIsNot(Foo, original) test.assertIs(Foo, mock_foo) test.assertIsInstance(Foo, SomeClass) def test_two(self, mock_foo): self._test(mock_foo) def test_one(self, mock_foo): self._test(mock_foo) SomeTest = patch(foo_name, new_callable=SomeClass)(SomeTest) SomeTest().test_one() SomeTest().test_two() self.assertIs(Foo, original) def test_patch_multiple(self): original_foo = Foo original_f = Foo.f original_g = Foo.g patcher1 = patch.multiple(foo_name, f=1, g=2) patcher2 = patch.multiple(Foo, f=1, g=2) for patcher in patcher1, patcher2: patcher.start() try: self.assertIs(Foo, original_foo) self.assertEqual(Foo.f, 1) self.assertEqual(Foo.g, 2) finally: patcher.stop() self.assertIs(Foo, original_foo) self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) @patch.multiple(foo_name, f=3, g=4) def test(): self.assertIs(Foo, original_foo) self.assertEqual(Foo.f, 3) self.assertEqual(Foo.g, 4) test() def test_patch_multiple_no_kwargs(self): self.assertRaises(ValueError, patch.multiple, foo_name) self.assertRaises(ValueError, patch.multiple, Foo) def test_patch_multiple_create_mocks(self): original_foo = Foo original_f = Foo.f original_g = Foo.g @patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT) def test(f, foo): self.assertIs(Foo, original_foo) self.assertIs(Foo.f, f) self.assertEqual(Foo.g, 3) self.assertIs(Foo.foo, foo) self.assertTrue(is_instance(f, MagicMock)) self.assertTrue(is_instance(foo, MagicMock)) test() self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_patch_multiple_create_mocks_different_order(self): # bug revealed by Jython! original_f = Foo.f original_g = Foo.g patcher = patch.object(Foo, 'f', 3) patcher.attribute_name = 'f' other = patch.object(Foo, 'g', DEFAULT) other.attribute_name = 'g' patcher.additional_patchers = [other] @patcher def test(g): self.assertIs(Foo.g, g) self.assertEqual(Foo.f, 3) test() self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_patch_multiple_stacked_decorators(self): original_foo = Foo original_f = Foo.f original_g = Foo.g @patch.multiple(foo_name, f=DEFAULT) @patch.multiple(foo_name, foo=DEFAULT) @patch(foo_name + '.g') def test1(g, **kwargs): _test(g, **kwargs) @patch.multiple(foo_name, f=DEFAULT) @patch(foo_name + '.g') @patch.multiple(foo_name, foo=DEFAULT) def test2(g, **kwargs): _test(g, **kwargs) @patch(foo_name + '.g') @patch.multiple(foo_name, f=DEFAULT) @patch.multiple(foo_name, foo=DEFAULT) def test3(g, **kwargs): _test(g, **kwargs) def _test(g, **kwargs): f = kwargs.pop('f') foo = kwargs.pop('foo') self.assertFalse(kwargs) self.assertIs(Foo, original_foo) self.assertIs(Foo.f, f) self.assertIs(Foo.g, g) self.assertIs(Foo.foo, foo) self.assertTrue(is_instance(f, MagicMock)) self.assertTrue(is_instance(g, MagicMock)) self.assertTrue(is_instance(foo, MagicMock)) test1() test2() test3() self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_patch_multiple_create_mocks_patcher(self): original_foo = Foo original_f = Foo.f original_g = Foo.g patcher = patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT) result = patcher.start() try: f = result['f'] foo = result['foo'] self.assertEqual(set(result), set(['f', 'foo'])) self.assertIs(Foo, original_foo) self.assertIs(Foo.f, f) self.assertIs(Foo.foo, foo) self.assertTrue(is_instance(f, MagicMock)) self.assertTrue(is_instance(foo, MagicMock)) finally: patcher.stop() self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_patch_multiple_decorating_class(self): test = self original_foo = Foo original_f = Foo.f original_g = Foo.g class SomeTest(object): def _test(self, f, foo): test.assertIs(Foo, original_foo) test.assertIs(Foo.f, f) test.assertEqual(Foo.g, 3) test.assertIs(Foo.foo, foo) test.assertTrue(is_instance(f, MagicMock)) test.assertTrue(is_instance(foo, MagicMock)) def test_two(self, f, foo): self._test(f, foo) def test_one(self, f, foo): self._test(f, foo) SomeTest = patch.multiple( foo_name, f=DEFAULT, g=3, foo=DEFAULT )(SomeTest) thing = SomeTest() thing.test_one() thing.test_two() self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_patch_multiple_create(self): patcher = patch.multiple(Foo, blam='blam') self.assertRaises(AttributeError, patcher.start) patcher = patch.multiple(Foo, blam='blam', create=True) patcher.start() try: self.assertEqual(Foo.blam, 'blam') finally: patcher.stop() self.assertFalse(hasattr(Foo, 'blam')) def test_patch_multiple_spec_set(self): # if spec_set works then we can assume that spec and autospec also # work as the underlying machinery is the same patcher = patch.multiple(Foo, foo=DEFAULT, spec_set=['a', 'b']) result = patcher.start() try: self.assertEqual(Foo.foo, result['foo']) Foo.foo.a(1) Foo.foo.b(2) Foo.foo.a.assert_called_with(1) Foo.foo.b.assert_called_with(2) self.assertRaises(AttributeError, setattr, Foo.foo, 'c', None) finally: patcher.stop() def test_patch_multiple_new_callable(self): class Thing(object): pass patcher = patch.multiple( Foo, f=DEFAULT, g=DEFAULT, new_callable=Thing ) result = patcher.start() try: self.assertIs(Foo.f, result['f']) self.assertIs(Foo.g, result['g']) self.assertIsInstance(Foo.f, Thing) self.assertIsInstance(Foo.g, Thing) self.assertIsNot(Foo.f, Foo.g) finally: patcher.stop() def test_nested_patch_failure(self): original_f = Foo.f original_g = Foo.g @patch.object(Foo, 'g', 1) @patch.object(Foo, 'missing', 1) @patch.object(Foo, 'f', 1) def thing1(): pass @patch.object(Foo, 'missing', 1) @patch.object(Foo, 'g', 1) @patch.object(Foo, 'f', 1) def thing2(): pass @patch.object(Foo, 'g', 1) @patch.object(Foo, 'f', 1) @patch.object(Foo, 'missing', 1) def thing3(): pass for func in thing1, thing2, thing3: self.assertRaises(AttributeError, func) self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_new_callable_failure(self): original_f = Foo.f original_g = Foo.g original_foo = Foo.foo def crasher(): raise NameError('crasher') @patch.object(Foo, 'g', 1) @patch.object(Foo, 'foo', new_callable=crasher) @patch.object(Foo, 'f', 1) def thing1(): pass @patch.object(Foo, 'foo', new_callable=crasher) @patch.object(Foo, 'g', 1) @patch.object(Foo, 'f', 1) def thing2(): pass @patch.object(Foo, 'g', 1) @patch.object(Foo, 'f', 1) @patch.object(Foo, 'foo', new_callable=crasher) def thing3(): pass for func in thing1, thing2, thing3: self.assertRaises(NameError, func) self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) self.assertEqual(Foo.foo, original_foo) def test_patch_multiple_failure(self): original_f = Foo.f original_g = Foo.g patcher = patch.object(Foo, 'f', 1) patcher.attribute_name = 'f' good = patch.object(Foo, 'g', 1) good.attribute_name = 'g' bad = patch.object(Foo, 'missing', 1) bad.attribute_name = 'missing' for additionals in [good, bad], [bad, good]: patcher.additional_patchers = additionals @patcher def func(): pass self.assertRaises(AttributeError, func) self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) def test_patch_multiple_new_callable_failure(self): original_f = Foo.f original_g = Foo.g original_foo = Foo.foo def crasher(): raise NameError('crasher') patcher = patch.object(Foo, 'f', 1) patcher.attribute_name = 'f' good = patch.object(Foo, 'g', 1) good.attribute_name = 'g' bad = patch.object(Foo, 'foo', new_callable=crasher) bad.attribute_name = 'foo' for additionals in [good, bad], [bad, good]: patcher.additional_patchers = additionals @patcher def func(): pass self.assertRaises(NameError, func) self.assertEqual(Foo.f, original_f) self.assertEqual(Foo.g, original_g) self.assertEqual(Foo.foo, original_foo) def test_patch_multiple_string_subclasses(self): Foo = type('Foo', (str,), {'fish': 'tasty'}) foo = Foo() @patch.multiple(foo, fish='nearly gone') def test(): self.assertEqual(foo.fish, 'nearly gone') test() self.assertEqual(foo.fish, 'tasty') @patch('unittest.mock.patch.TEST_PREFIX', 'foo') def test_patch_test_prefix(self): class Foo(object): thing = 'original' def foo_one(self): return self.thing def foo_two(self): return self.thing def test_one(self): return self.thing def test_two(self): return self.thing Foo = patch.object(Foo, 'thing', 'changed')(Foo) foo = Foo() self.assertEqual(foo.foo_one(), 'changed') self.assertEqual(foo.foo_two(), 'changed') self.assertEqual(foo.test_one(), 'original') self.assertEqual(foo.test_two(), 'original') @patch('unittest.mock.patch.TEST_PREFIX', 'bar') def test_patch_dict_test_prefix(self): class Foo(object): def bar_one(self): return dict(the_dict) def bar_two(self): return dict(the_dict) def test_one(self): return dict(the_dict) def test_two(self): return dict(the_dict) the_dict = {'key': 'original'} Foo = patch.dict(the_dict, key='changed')(Foo) foo =Foo() self.assertEqual(foo.bar_one(), {'key': 'changed'}) self.assertEqual(foo.bar_two(), {'key': 'changed'}) self.assertEqual(foo.test_one(), {'key': 'original'}) self.assertEqual(foo.test_two(), {'key': 'original'}) def test_patch_with_spec_mock_repr(self): for arg in ('spec', 'autospec', 'spec_set'): p = patch('%s.SomeClass' % __name__, **{arg: True}) m = p.start() try: self.assertIn(" name='SomeClass'", repr(m)) self.assertIn(" name='SomeClass.class_attribute'", repr(m.class_attribute)) self.assertIn(" name='SomeClass()'", repr(m())) self.assertIn(" name='SomeClass().class_attribute'", repr(m().class_attribute)) finally: p.stop() def test_patch_nested_autospec_repr(self): with patch('unittest.test.testmock.support', autospec=True) as m: self.assertIn(" name='support.SomeClass.wibble()'", repr(m.SomeClass.wibble())) self.assertIn(" name='support.SomeClass().wibble()'", repr(m.SomeClass().wibble())) def test_mock_calls_with_patch(self): for arg in ('spec', 'autospec', 'spec_set'): p = patch('%s.SomeClass' % __name__, **{arg: True}) m = p.start() try: m.wibble() kalls = [call.wibble()] self.assertEqual(m.mock_calls, kalls) self.assertEqual(m.method_calls, kalls) self.assertEqual(m.wibble.mock_calls, [call()]) result = m() kalls.append(call()) self.assertEqual(m.mock_calls, kalls) result.wibble() kalls.append(call().wibble()) self.assertEqual(m.mock_calls, kalls) self.assertEqual(result.mock_calls, [call.wibble()]) self.assertEqual(result.wibble.mock_calls, [call()]) self.assertEqual(result.method_calls, [call.wibble()]) finally: p.stop() def test_patch_imports_lazily(self): p1 = patch('squizz.squozz') self.assertRaises(ImportError, p1.start) with uncache('squizz'): squizz = Mock() sys.modules['squizz'] = squizz squizz.squozz = 6 p1 = patch('squizz.squozz') squizz.squozz = 3 p1.start() p1.stop() self.assertEqual(squizz.squozz, 3) def test_patch_propogrates_exc_on_exit(self): class holder: exc_info = None, None, None class custom_patch(_patch): def __exit__(self, etype=None, val=None, tb=None): _patch.__exit__(self, etype, val, tb) holder.exc_info = etype, val, tb stop = __exit__ def with_custom_patch(target): getter, attribute = _get_target(target) return custom_patch( getter, attribute, DEFAULT, None, False, None, None, None, {} ) @with_custom_patch('squizz.squozz') def test(mock): raise RuntimeError with uncache('squizz'): squizz = Mock() sys.modules['squizz'] = squizz self.assertRaises(RuntimeError, test) self.assertIs(holder.exc_info[0], RuntimeError) self.assertIsNotNone(holder.exc_info[1], 'exception value not propgated') self.assertIsNotNone(holder.exc_info[2], 'exception traceback not propgated') def test_create_and_specs(self): for kwarg in ('spec', 'spec_set', 'autospec'): p = patch('%s.doesnotexist' % __name__, create=True, **{kwarg: True}) self.assertRaises(TypeError, p.start) self.assertRaises(NameError, lambda: doesnotexist) # check that spec with create is innocuous if the original exists p = patch(MODNAME, create=True, **{kwarg: True}) p.start() p.stop() def test_multiple_specs(self): original = PTModule for kwarg in ('spec', 'spec_set'): p = patch(MODNAME, autospec=0, **{kwarg: 0}) self.assertRaises(TypeError, p.start) self.assertIs(PTModule, original) for kwarg in ('spec', 'autospec'): p = patch(MODNAME, spec_set=0, **{kwarg: 0}) self.assertRaises(TypeError, p.start) self.assertIs(PTModule, original) for kwarg in ('spec_set', 'autospec'): p = patch(MODNAME, spec=0, **{kwarg: 0}) self.assertRaises(TypeError, p.start) self.assertIs(PTModule, original) def test_specs_false_instead_of_none(self): p = patch(MODNAME, spec=False, spec_set=False, autospec=False) mock = p.start() try: # no spec should have been set, so attribute access should not fail mock.does_not_exist mock.does_not_exist = 3 finally: p.stop() def test_falsey_spec(self): for kwarg in ('spec', 'autospec', 'spec_set'): p = patch(MODNAME, **{kwarg: 0}) m = p.start() try: self.assertRaises(AttributeError, getattr, m, 'doesnotexit') finally: p.stop() def test_spec_set_true(self): for kwarg in ('spec', 'autospec'): p = patch(MODNAME, spec_set=True, **{kwarg: True}) m = p.start() try: self.assertRaises(AttributeError, setattr, m, 'doesnotexist', 'something') self.assertRaises(AttributeError, getattr, m, 'doesnotexist') finally: p.stop() def test_callable_spec_as_list(self): spec = ('__call__',) p = patch(MODNAME, spec=spec) m = p.start() try: self.assertTrue(callable(m)) finally: p.stop() def test_not_callable_spec_as_list(self): spec = ('foo', 'bar') p = patch(MODNAME, spec=spec) m = p.start() try: self.assertFalse(callable(m)) finally: p.stop() def test_patch_stopall(self): unlink = os.unlink chdir = os.chdir path = os.path patch('os.unlink', something).start() patch('os.chdir', something_else).start() @patch('os.path') def patched(mock_path): patch.stopall() self.assertIs(os.path, mock_path) self.assertIs(os.unlink, unlink) self.assertIs(os.chdir, chdir) patched() self.assertIs(os.path, path) def test_stopall_lifo(self): stopped = [] class thing(object): one = two = three = None def get_patch(attribute): class mypatch(_patch): def stop(self): stopped.append(attribute) return super(mypatch, self).stop() return mypatch(lambda: thing, attribute, None, None, False, None, None, None, {}) [get_patch(val).start() for val in ("one", "two", "three")] patch.stopall() self.assertEqual(stopped, ["three", "two", "one"]) def test_special_attrs(self): def foo(x=0): """TEST""" return x with patch.object(foo, '__defaults__', (1, )): self.assertEqual(foo(), 1) self.assertEqual(foo(), 0) with patch.object(foo, '__doc__', "FUN"): self.assertEqual(foo.__doc__, "FUN") self.assertEqual(foo.__doc__, "TEST") with patch.object(foo, '__module__', "testpatch2"): self.assertEqual(foo.__module__, "testpatch2") self.assertEqual(foo.__module__, 'unittest.test.testmock.testpatch') with patch.object(foo, '__annotations__', dict([('s', 1, )])): self.assertEqual(foo.__annotations__, dict([('s', 1, )])) self.assertEqual(foo.__annotations__, dict()) def foo(*a, x=0): return x with patch.object(foo, '__kwdefaults__', dict([('x', 1, )])): self.assertEqual(foo(), 1) self.assertEqual(foo(), 0) if __name__ == '__main__': unittest.main()
55,727
1,859
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/support.py
def is_instance(obj, klass): """Version of is_instance that doesn't access __class__""" return issubclass(type(obj), klass) class SomeClass(object): class_attribute = None def wibble(self): pass class X(object): pass def examine_warnings(func): def wrapper(): with catch_warnings(record=True) as ws: func(ws) return wrapper
387
22
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/__main__.py
import os import unittest def load_tests(loader, standard_tests, pattern): # top level directory cached on loader instance this_dir = os.path.dirname(__file__) pattern = pattern or "test*.py" # We are inside unittest.test.testmock, so the top-level is three notches up top_level_dir = os.path.dirname(os.path.dirname(os.path.dirname(this_dir))) package_tests = loader.discover(start_dir=this_dir, pattern=pattern, top_level_dir=top_level_dir) standard_tests.addTests(package_tests) return standard_tests if __name__ == '__main__': unittest.main()
623
19
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testmock.py
import copy import sys import tempfile import unittest from unittest.test.testmock.support import is_instance from unittest import mock from unittest.mock import ( call, DEFAULT, patch, sentinel, MagicMock, Mock, NonCallableMock, NonCallableMagicMock, _Call, _CallList, create_autospec ) class Iter(object): def __init__(self): self.thing = iter(['this', 'is', 'an', 'iter']) def __iter__(self): return self def next(self): return next(self.thing) __next__ = next class Something(object): def meth(self, a, b, c, d=None): pass @classmethod def cmeth(cls, a, b, c, d=None): pass @staticmethod def smeth(a, b, c, d=None): pass class MockTest(unittest.TestCase): def test_all(self): # if __all__ is badly defined then import * will raise an error # We have to exec it because you can't import * inside a method # in Python 3 exec("from unittest.mock import *") def test_constructor(self): mock = Mock() self.assertFalse(mock.called, "called not initialised correctly") self.assertEqual(mock.call_count, 0, "call_count not initialised correctly") self.assertTrue(is_instance(mock.return_value, Mock), "return_value not initialised correctly") self.assertEqual(mock.call_args, None, "call_args not initialised correctly") self.assertEqual(mock.call_args_list, [], "call_args_list not initialised correctly") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly") # Can't use hasattr for this test as it always returns True on a mock self.assertNotIn('_items', mock.__dict__, "default mock should not have '_items' attribute") self.assertIsNone(mock._mock_parent, "parent not initialised correctly") self.assertIsNone(mock._mock_methods, "methods not initialised correctly") self.assertEqual(mock._mock_children, {}, "children not initialised incorrectly") def test_return_value_in_constructor(self): mock = Mock(return_value=None) self.assertIsNone(mock.return_value, "return value in constructor not honoured") def test_repr(self): mock = Mock(name='foo') self.assertIn('foo', repr(mock)) self.assertIn("'%s'" % id(mock), repr(mock)) mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] for mock, name in mocks: self.assertIn('%s.bar' % name, repr(mock.bar)) self.assertIn('%s.foo()' % name, repr(mock.foo())) self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) self.assertIn('%s()' % name, repr(mock())) self.assertIn('%s()()' % name, repr(mock()())) self.assertIn('%s()().foo.bar.baz().bing' % name, repr(mock()().foo.bar.baz().bing)) def test_repr_with_spec(self): class X(object): pass mock = Mock(spec=X) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec=X()) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec_set=X) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec_set=X()) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec=X, name='foo') self.assertIn(" spec='X' ", repr(mock)) self.assertIn(" name='foo' ", repr(mock)) mock = Mock(name='foo') self.assertNotIn("spec", repr(mock)) mock = Mock() self.assertNotIn("spec", repr(mock)) mock = Mock(spec=['foo']) self.assertNotIn("spec", repr(mock)) def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN) def test_autospec_side_effect(self): # Test for issue17826 results = [1, 2, 3] def effect(): return results.pop() def f(): pass mock = create_autospec(f) mock.side_effect = [1, 2, 3] self.assertEqual([mock(), mock(), mock()], [1, 2, 3], "side effect not used correctly in create_autospec") # Test where side effect is a callable results = [1, 2, 3] mock = create_autospec(f) mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "callable side effect not used correctly") def test_autospec_side_effect_exception(self): # Test for issue 23661 def f(): pass mock = create_autospec(f) mock.side_effect = ValueError('Bazinga!') self.assertRaisesRegex(ValueError, 'Bazinga!', mock) @unittest.skipUnless('java' in sys.platform, 'This test only applies to Jython') def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3) def test_reset_mock(self): parent = Mock() spec = ["something"] mock = Mock(name="child", parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, "child", "name incorrectly reset") self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset") self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset") self.assertFalse(mock.called, "called not reset") self.assertEqual(mock.call_count, 0, "call_count not reset") self.assertEqual(mock.call_args, None, "call_args not reset") self.assertEqual(mock.call_args_list, [], "call_args_list not reset") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset") self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset") self.assertFalse(return_value.called, "return value mock not reset") self.assertEqual(mock._mock_children, {'something': something}, "children reset incorrectly") self.assertEqual(mock.something, something, "children incorrectly cleared") self.assertFalse(mock.something.called, "child not reset") def test_reset_mock_recursion(self): mock = Mock() mock.return_value = mock # used to cause recursion mock.reset_mock() def test_reset_mock_on_mock_open_issue_18622(self): a = mock.mock_open() a.reset_mock() def test_call(self): mock = Mock() self.assertTrue(is_instance(mock.return_value, Mock), "Default return_value should be a Mock") result = mock() self.assertEqual(mock(), result, "different result from consecutive calls") mock.reset_mock() ret_val = mock(sentinel.Arg) self.assertTrue(mock.called, "called not set") self.assertEqual(mock.call_count, 1, "call_count incoreect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set") self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly") mock.return_value = sentinel.ReturnValue ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value") self.assertEqual(mock.call_count, 2, "call_count incorrect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {'key': sentinel.KeyArg}), "call_args not set") self.assertEqual(mock.call_args_list, [ ((sentinel.Arg,), {}), ((sentinel.Arg,), {'key': sentinel.KeyArg}) ], "call_args_list not set") def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [ (), ((sentinel.Arg,),), ({"kw": sentinel.Kwarg},), ((sentinel.Arg,), {"kw": sentinel.Kwarg}) ]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {"kw": sentinel.Kwarg})) # Comparing call_args to a long sequence should not raise # an exception. See issue 24857. self.assertFalse(mock.call_args == "a long sequence") def test_calls_equal_with_any(self): # Check that equality and non-equality is consistent even when # comparing with mock.ANY mm = mock.MagicMock() self.assertTrue(mm == mm) self.assertFalse(mm != mm) self.assertFalse(mm == mock.MagicMock()) self.assertTrue(mm != mock.MagicMock()) self.assertTrue(mm == mock.ANY) self.assertFalse(mm != mock.ANY) self.assertTrue(mock.ANY == mm) self.assertFalse(mock.ANY != mm) call1 = mock.call(mock.MagicMock()) call2 = mock.call(mock.ANY) self.assertTrue(call1 == call2) self.assertFalse(call1 != call2) self.assertTrue(call2 == call1) self.assertFalse(call2 != call1) def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing') def test_assert_called_with_any(self): m = MagicMock() m(MagicMock()) m.assert_called_with(mock.ANY) def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_assert_called_with_method_spec(self): def _check(mock): mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) mock = Mock(spec=Something().meth) _check(mock) mock = Mock(spec=Something.cmeth) _check(mock) mock = Mock(spec=Something().cmeth) _check(mock) mock = Mock(spec=Something.smeth) _check(mock) mock = Mock(spec=Something().smeth) _check(mock) def test_assert_called_once_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises( AssertionError, lambda: mock.assert_called_once_with('bob', 'bar', baz=2) ) def test_assert_called_once_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_once_with(1, 2, 3) mock.assert_called_once_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_once_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) # Mock called more than once => always fails mock(4, 5, 6) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, 2, 3) self.assertRaises(AssertionError, mock.assert_called_once_with, 4, 5, 6) def test_attribute_access_returns_mocks(self): mock = Mock() something = mock.something self.assertTrue(is_instance(something, Mock), "attribute isn't a mock") self.assertEqual(mock.something, something, "different attributes returned for same name") # Usage example mock = Mock() mock.something.return_value = 3 self.assertEqual(mock.something(), 3, "method returned wrong value") self.assertTrue(mock.something.called, "method didn't record being called") def test_attributes_have_name_and_parent_set(self): mock = Mock() something = mock.something self.assertEqual(something._mock_name, "something", "attribute name not set correctly") self.assertEqual(something._mock_parent, mock, "attribute parent not set correctly") def test_method_calls_recorded(self): mock = Mock() mock.something(3, fish=None) mock.something_else.something(6, cake=sentinel.Cake) self.assertEqual(mock.something_else.method_calls, [("something", (6,), {'cake': sentinel.Cake})], "method calls not recorded correctly") self.assertEqual(mock.method_calls, [ ("something", (3,), {'fish': None}), ("something_else.something", (6,), {'cake': sentinel.Cake}) ], "method calls not recorded correctly") def test_method_calls_compare_easily(self): mock = Mock() mock.something() self.assertEqual(mock.method_calls, [('something',)]) self.assertEqual(mock.method_calls, [('something', (), {})]) mock = Mock() mock.something('different') self.assertEqual(mock.method_calls, [('something', ('different',))]) self.assertEqual(mock.method_calls, [('something', ('different',), {})]) mock = Mock() mock.something(x=1) self.assertEqual(mock.method_calls, [('something', {'x': 1})]) self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) mock = Mock() mock.something('different', some='more') self.assertEqual(mock.method_calls, [ ('something', ('different',), {'some': 'more'}) ]) def test_only_allowed_methods_exist(self): for spec in ['something'], ('something',): for arg in 'spec', 'spec_set': mock = Mock(**{arg: spec}) # this should be allowed mock.something self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'something_else'", getattr, mock, 'something_else' ) def test_from_spec(self): class Something(object): x = 3 __something__ = None def y(self): pass def test_attributes(mock): # should work mock.x mock.y mock.__something__ self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'z'", getattr, mock, 'z' ) self.assertRaisesRegex( AttributeError, "Mock object has no attribute '__foobar__'", getattr, mock, '__foobar__' ) test_attributes(Mock(spec=Something)) test_attributes(Mock(spec=Something())) def test_wraps_calls(self): real = Mock() mock = Mock(wraps=real) self.assertEqual(mock(), real()) real.reset_mock() mock(1, 2, fish=3) real.assert_called_with(1, 2, fish=3) def test_wraps_prevents_automatic_creation_of_mocks(self): class Real(object): pass real = Real() mock = Mock(wraps=real) self.assertRaises(AttributeError, lambda: mock.new_attr()) def test_wraps_call_with_nondefault_return_value(self): real = Mock() mock = Mock(wraps=real) mock.return_value = 3 self.assertEqual(mock(), 3) self.assertFalse(real.called) def test_wraps_attributes(self): class Real(object): attribute = Mock() real = Real() mock = Mock(wraps=real) self.assertEqual(mock.attribute(), real.attribute()) self.assertRaises(AttributeError, lambda: mock.fish) self.assertNotEqual(mock.attribute, real.attribute) result = mock.attribute.frog(1, 2, fish=3) Real.attribute.frog.assert_called_with(1, 2, fish=3) self.assertEqual(result, Real.attribute.frog()) def test_customize_wrapped_object_with_side_effect_iterable_with_default(self): class Real(object): def method(self): return sentinel.ORIGINAL_VALUE real = Real() mock = Mock(wraps=real) mock.method.side_effect = [sentinel.VALUE1, DEFAULT] self.assertEqual(mock.method(), sentinel.VALUE1) self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE) self.assertRaises(StopIteration, mock.method) def test_customize_wrapped_object_with_side_effect_iterable(self): class Real(object): def method(self): raise NotImplementedError() real = Real() mock = Mock(wraps=real) mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2] self.assertEqual(mock.method(), sentinel.VALUE1) self.assertEqual(mock.method(), sentinel.VALUE2) self.assertRaises(StopIteration, mock.method) def test_customize_wrapped_object_with_side_effect_exception(self): class Real(object): def method(self): raise NotImplementedError() real = Real() mock = Mock(wraps=real) mock.method.side_effect = RuntimeError self.assertRaises(RuntimeError, mock.method) def test_customize_wrapped_object_with_side_effect_function(self): class Real(object): def method(self): raise NotImplementedError() def side_effect(): return sentinel.VALUE real = Real() mock = Mock(wraps=real) mock.method.side_effect = side_effect self.assertEqual(mock.method(), sentinel.VALUE) def test_customize_wrapped_object_with_return_value(self): class Real(object): def method(self): raise NotImplementedError() real = Real() mock = Mock(wraps=real) mock.method.return_value = sentinel.VALUE self.assertEqual(mock.method(), sentinel.VALUE) def test_customize_wrapped_object_with_return_value_and_side_effect(self): # side_effect should always take precedence over return_value. class Real(object): def method(self): raise NotImplementedError() real = Real() mock = Mock(wraps=real) mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2] mock.method.return_value = sentinel.WRONG_VALUE self.assertEqual(mock.method(), sentinel.VALUE1) self.assertEqual(mock.method(), sentinel.VALUE2) self.assertRaises(StopIteration, mock.method) def test_customize_wrapped_object_with_return_value_and_side_effect2(self): # side_effect can return DEFAULT to default to return_value class Real(object): def method(self): raise NotImplementedError() real = Real() mock = Mock(wraps=real) mock.method.side_effect = lambda: DEFAULT mock.method.return_value = sentinel.VALUE self.assertEqual(mock.method(), sentinel.VALUE) def test_customize_wrapped_object_with_return_value_and_side_effect_default(self): class Real(object): def method(self): raise NotImplementedError() real = Real() mock = Mock(wraps=real) mock.method.side_effect = [sentinel.VALUE1, DEFAULT] mock.method.return_value = sentinel.RETURN self.assertEqual(mock.method(), sentinel.VALUE1) self.assertEqual(mock.method(), sentinel.RETURN) self.assertRaises(StopIteration, mock.method) def test_exceptional_side_effect(self): mock = Mock(side_effect=AttributeError) self.assertRaises(AttributeError, mock) mock = Mock(side_effect=AttributeError('foo')) self.assertRaises(AttributeError, mock) def test_baseexceptional_side_effect(self): mock = Mock(side_effect=KeyboardInterrupt) self.assertRaises(KeyboardInterrupt, mock) mock = Mock(side_effect=KeyboardInterrupt('foo')) self.assertRaises(KeyboardInterrupt, mock) def test_assert_called_with_message(self): mock = Mock() self.assertRaisesRegex(AssertionError, 'Not called', mock.assert_called_with) def test_assert_called_once_with_message(self): mock = Mock(name='geoffrey') self.assertRaisesRegex(AssertionError, r"Expected 'geoffrey' to be called once\.", mock.assert_called_once_with) def test__name__(self): mock = Mock() self.assertRaises(AttributeError, lambda: mock.__name__) mock.__name__ = 'foo' self.assertEqual(mock.__name__, 'foo') def test_spec_list_subclass(self): class Sub(list): pass mock = Mock(spec=Sub(['foo'])) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock, 'foo') def test_spec_class(self): class X(object): pass mock = Mock(spec=X) self.assertIsInstance(mock, X) mock = Mock(spec=X()) self.assertIsInstance(mock, X) self.assertIs(mock.__class__, X) self.assertEqual(Mock().__class__.__name__, 'Mock') mock = Mock(spec_set=X) self.assertIsInstance(mock, X) mock = Mock(spec_set=X()) self.assertIsInstance(mock, X) def test_setting_attribute_with_spec_set(self): class X(object): y = 3 mock = Mock(spec=X) mock.x = 'foo' mock = Mock(spec_set=X) def set_attr(): mock.x = 'foo' mock.y = 'foo' self.assertRaises(AttributeError, set_attr) def test_copy(self): current = sys.getrecursionlimit() self.addCleanup(sys.setrecursionlimit, current) # can't use sys.maxint as this doesn't exist in Python 3 sys.setrecursionlimit(int(10e8)) # this segfaults without the fix in place copy.copy(Mock()) def test_subclass_with_properties(self): class SubClass(Mock): def _get(self): return 3 def _set(self, value): raise NameError('strange error') some_attribute = property(_get, _set) s = SubClass(spec_set=SubClass) self.assertEqual(s.some_attribute, 3) def test(): s.some_attribute = 3 self.assertRaises(NameError, test) def test(): s.foo = 'bar' self.assertRaises(AttributeError, test) def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two') def test_dir(self): mock = Mock() attrs = set(dir(mock)) type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) # all public attributes from the type are included self.assertEqual(set(), type_attrs - attrs) # creates these attributes mock.a, mock.b self.assertIn('a', dir(mock)) self.assertIn('b', dir(mock)) # instance attributes mock.c = mock.d = None self.assertIn('c', dir(mock)) self.assertIn('d', dir(mock)) # magic methods mock.__iter__ = lambda s: iter([]) self.assertIn('__iter__', dir(mock)) def test_dir_from_spec(self): mock = Mock(spec=unittest.TestCase) testcase_attrs = set(dir(unittest.TestCase)) attrs = set(dir(mock)) # all attributes from the spec are included self.assertEqual(set(), testcase_attrs - attrs) # shadow a sys attribute mock.version = 3 self.assertEqual(dir(mock).count('version'), 1) def test_filter_dir(self): patcher = patch.object(mock, 'FILTER_DIR', False) patcher.start() try: attrs = set(dir(Mock())) type_attrs = set(dir(Mock)) # ALL attributes from the type are included self.assertEqual(set(), type_attrs - attrs) finally: patcher.stop() def test_configure_mock(self): mock = Mock(foo='bar') self.assertEqual(mock.foo, 'bar') mock = MagicMock(foo='bar') self.assertEqual(mock.foo, 'bar') kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} mock = Mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) mock = Mock() mock.configure_mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs): # needed because assertRaisesRegex doesn't work easily with newlines try: func(*args, **kwargs) except: instance = sys.exc_info()[1] self.assertIsInstance(instance, exception) else: self.fail('Exception %r not raised' % (exception,)) msg = str(instance) self.assertEqual(msg, message) def test_assert_called_with_failure_message(self): mock = NonCallableMock() expected = "mock(1, '2', 3, bar='foo')" message = 'Expected call: %s\nNot called' self.assertRaisesWithMsg( AssertionError, message % (expected,), mock.assert_called_with, 1, '2', 3, bar='foo' ) mock.foo(1, '2', 3, foo='foo') asserters = [ mock.foo.assert_called_with, mock.foo.assert_called_once_with ] for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, '2', 3, bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, '2', 3, bar='foo' ) # just kwargs for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, bar='foo' ) # just args for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, 2, 3)" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, 2, 3 ) # empty for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo()" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth ) def test_mock_calls(self): mock = MagicMock() # need to do this because MagicMock.mock_calls used to just return # a MagicMock which also returned a MagicMock when __eq__ was called self.assertIs(mock.mock_calls == [], True) mock = MagicMock() mock() expected = [('', (), {})] self.assertEqual(mock.mock_calls, expected) mock.foo() expected.append(call.foo()) self.assertEqual(mock.mock_calls, expected) # intermediate mock_calls work too self.assertEqual(mock.foo.mock_calls, [('', (), {})]) mock = MagicMock() mock().foo(1, 2, 3, a=4, b=5) expected = [ ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5)) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.return_value.foo.mock_calls, [('', (1, 2, 3), dict(a=4, b=5))]) self.assertEqual(mock.return_value.mock_calls, [('foo', (1, 2, 3), dict(a=4, b=5))]) mock = MagicMock() mock().foo.bar().baz() expected = [ ('', (), {}), ('().foo.bar', (), {}), ('().foo.bar().baz', (), {}) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock().mock_calls, call.foo.bar().baz().call_list()) for kwargs in dict(), dict(name='bar'): mock = MagicMock(**kwargs) int(mock.foo) expected = [('foo.__int__', (), {})] self.assertEqual(mock.mock_calls, expected) mock = MagicMock(**kwargs) mock.a()() expected = [('a', (), {}), ('a()', (), {})] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.a().mock_calls, [call()]) mock = MagicMock(**kwargs) mock(1)(2)(3) self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).call_list()) self.assertEqual(mock()().mock_calls, call(3).call_list()) mock = MagicMock(**kwargs) mock(1)(2)(3).a.b.c(4) self.assertEqual(mock.mock_calls, call(1)(2)(3).a.b.c(4).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).a.b.c(4).call_list()) self.assertEqual(mock()().mock_calls, call(3).a.b.c(4).call_list()) mock = MagicMock(**kwargs) int(mock().foo.bar().baz()) last_call = ('().foo.bar().baz().__int__', (), {}) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock().mock_calls, call.foo.bar().baz().__int__().call_list()) self.assertEqual(mock().foo.bar().mock_calls, call.baz().__int__().call_list()) self.assertEqual(mock().foo.bar().baz.mock_calls, call().__int__().call_list()) def test_child_mock_call_equal(self): m = Mock() result = m() result.wibble() # parent looks like this: self.assertEqual(m.mock_calls, [call(), call().wibble()]) # but child should look like this: self.assertEqual(result.mock_calls, [call.wibble()]) def test_mock_call_not_equal_leaf(self): m = Mock() m.foo().something() self.assertNotEqual(m.mock_calls[1], call.foo().different()) self.assertEqual(m.mock_calls[0], call.foo()) def test_mock_call_not_equal_non_leaf(self): m = Mock() m.foo().bar() self.assertNotEqual(m.mock_calls[1], call.baz().bar()) self.assertNotEqual(m.mock_calls[0], call.baz()) def test_mock_call_not_equal_non_leaf_params_different(self): m = Mock() m.foo(x=1).bar() # This isn't ideal, but there's no way to fix it without breaking backwards compatibility: self.assertEqual(m.mock_calls[1], call.foo(x=2).bar()) def test_mock_call_not_equal_non_leaf_attr(self): m = Mock() m.foo.bar() self.assertNotEqual(m.mock_calls[0], call.baz.bar()) def test_mock_call_not_equal_non_leaf_call_versus_attr(self): m = Mock() m.foo.bar() self.assertNotEqual(m.mock_calls[0], call.foo().bar()) def test_mock_call_repr(self): m = Mock() m.foo().bar().baz.bob() self.assertEqual(repr(m.mock_calls[0]), 'call.foo()') self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()') self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()') def test_subclassing(self): class Subclass(Mock): pass mock = Subclass() self.assertIsInstance(mock.foo, Subclass) self.assertIsInstance(mock(), Subclass) class Subclass(Mock): def _get_child_mock(self, **kwargs): return Mock(**kwargs) mock = Subclass() self.assertNotIsInstance(mock.foo, Subclass) self.assertNotIsInstance(mock(), Subclass) def test_arg_lists(self): mocks = [ Mock(), MagicMock(), NonCallableMock(), NonCallableMagicMock() ] def assert_attrs(mock): names = 'call_args_list', 'method_calls', 'mock_calls' for name in names: attr = getattr(mock, name) self.assertIsInstance(attr, _CallList) self.assertIsInstance(attr, list) self.assertEqual(attr, []) for mock in mocks: assert_attrs(mock) if callable(mock): mock() mock(1, 2) mock(a=3) mock.reset_mock() assert_attrs(mock) mock.foo() mock.foo.bar(1, a=3) mock.foo(1).bar().baz(3) mock.reset_mock() assert_attrs(mock) def test_call_args_two_tuple(self): mock = Mock() mock(1, a=3) mock(2, b=4) self.assertEqual(len(mock.call_args), 2) args, kwargs = mock.call_args self.assertEqual(args, (2,)) self.assertEqual(kwargs, dict(b=4)) expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] for expected, call_args in zip(expected_list, mock.call_args_list): self.assertEqual(len(call_args), 2) self.assertEqual(expected[0], call_args[0]) self.assertEqual(expected[1], call_args[1]) def test_side_effect_iterator(self): mock = Mock(side_effect=iter([1, 2, 3])) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) mock = MagicMock(side_effect=['a', 'b', 'c']) self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) mock = Mock(side_effect='ghi') self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) self.assertRaises(StopIteration, mock) class Foo(object): pass mock = MagicMock(side_effect=Foo) self.assertIsInstance(mock(), Foo) mock = Mock(side_effect=Iter()) self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) def test_side_effect_iterator_exceptions(self): for Klass in Mock, MagicMock: iterable = (ValueError, 3, KeyError, 6) m = Klass(side_effect=iterable) self.assertRaises(ValueError, m) self.assertEqual(m(), 3) self.assertRaises(KeyError, m) self.assertEqual(m(), 6) def test_side_effect_setting_iterator(self): mock = Mock() mock.side_effect = iter([1, 2, 3]) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) mock.side_effect = ['a', 'b', 'c'] self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) this_iter = Iter() mock.side_effect = this_iter self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) self.assertIs(mock.side_effect, this_iter) def test_side_effect_iterator_default(self): mock = Mock(return_value=2) mock.side_effect = iter([1, DEFAULT]) self.assertEqual([mock(), mock()], [1, 2]) def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [ call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', (1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3}) ] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': self.assertRaises( AssertionError, mock.assert_has_calls, [kall], any_order=True ) kall_lists = [ [call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)], ] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [ [call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], ] for kall_list in kall_lists: self.assertRaises( AssertionError, mock.assert_has_calls, kall_list, any_order=True ) def test_assert_has_calls(self): kalls1 = [ call(1, 2), ({'a': 3},), ((3, 4),), call(b=6), ('', (1,), {'b': 6}), ] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i:i+step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises( AssertionError, mock.assert_has_calls, list(reversed(these)) ) def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), {'d': 7}), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) def test_assert_any_call(self): mock = Mock() mock(1, 2) mock(a=3) mock(1, b=6) mock.assert_any_call(1, 2) mock.assert_any_call(a=3) mock.assert_any_call(1, b=6) self.assertRaises( AssertionError, mock.assert_any_call ) self.assertRaises( AssertionError, mock.assert_any_call, 1, 3 ) self.assertRaises( AssertionError, mock.assert_any_call, a=4 ) def test_assert_any_call_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock.assert_any_call(1, 2, 3) mock.assert_any_call(a=1, b=2, c=3) mock.assert_any_call(4, 5, 6, 7) mock.assert_any_call(a=4, b=5, c=6, d=7) self.assertRaises(AssertionError, mock.assert_any_call, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_any_call(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_mock_calls_create_autospec(self): def f(a, b): pass obj = Iter() obj.f = f funcs = [ create_autospec(f), create_autospec(obj).f ] for func in funcs: func(1, 2) func(3, 4) self.assertEqual( func.mock_calls, [call(1, 2), call(3, 4)] ) #Issue21222 def test_create_autospec_with_name(self): m = mock.create_autospec(object(), name='sweet_func') self.assertIn('sweet_func', repr(m)) #Issue21238 def test_mock_unsafe(self): m = Mock() with self.assertRaises(AttributeError): m.assert_foo_call() with self.assertRaises(AttributeError): m.assret_foo_call() m = Mock(unsafe=True) m.assert_foo_call() m.assret_foo_call() #Issue21262 def test_assert_not_called(self): m = Mock() m.hello.assert_not_called() m.hello() with self.assertRaises(AssertionError): m.hello.assert_not_called() def test_assert_called(self): m = Mock() with self.assertRaises(AssertionError): m.hello.assert_called() m.hello() m.hello.assert_called() m.hello() m.hello.assert_called() def test_assert_called_once(self): m = Mock() with self.assertRaises(AssertionError): m.hello.assert_called_once() m.hello() m.hello.assert_called_once() m.hello() with self.assertRaises(AssertionError): m.hello.assert_called_once() #Issue21256 printout of keyword args should be in deterministic order def test_sorted_call_signature(self): m = Mock() m.hello(name='hello', daddy='hero') text = "call(daddy='hero', name='hello')" self.assertEqual(repr(m.hello.call_args), text) #Issue21270 overrides tuple methods for mock.call objects def test_override_tuple_methods(self): c = call.count() i = call.index(132,'hello') m = Mock() m.count() m.index(132,"hello") self.assertEqual(m.method_calls[0], c) self.assertEqual(m.method_calls[1], i) def test_reset_return_sideeffect(self): m = Mock(return_value=10, side_effect=[2,3]) m.reset_mock(return_value=True, side_effect=True) self.assertIsInstance(m.return_value, Mock) self.assertEqual(m.side_effect, None) def test_reset_return(self): m = Mock(return_value=10, side_effect=[2,3]) m.reset_mock(return_value=True) self.assertIsInstance(m.return_value, Mock) self.assertNotEqual(m.side_effect, None) def test_reset_sideeffect(self): m = Mock(return_value=10, side_effect=[2,3]) m.reset_mock(side_effect=True) self.assertEqual(m.return_value, 10) self.assertEqual(m.side_effect, None) def test_mock_add_spec(self): class _One(object): one = 1 class _Two(object): two = 2 class Anything(object): one = two = three = 'four' klasses = [ Mock, MagicMock, NonCallableMock, NonCallableMagicMock ] for Klass in list(klasses): klasses.append(lambda K=Klass: K(spec=Anything)) klasses.append(lambda K=Klass: K(spec_set=Anything)) for Klass in klasses: for kwargs in dict(), dict(spec_set=True): mock = Klass() #no error mock.one, mock.two, mock.three for One, Two in [(_One, _Two), (['one'], ['two'])]: for kwargs in dict(), dict(spec_set=True): mock.mock_add_spec(One, **kwargs) mock.one self.assertRaises( AttributeError, getattr, mock, 'two' ) self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) mock.mock_add_spec(Two, **kwargs) self.assertRaises( AttributeError, getattr, mock, 'one' ) mock.two self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) # note that creating a mock, setting an instance attribute, and # *then* setting a spec doesn't work. Not the intended use case def test_mock_add_spec_magic_methods(self): for Klass in MagicMock, NonCallableMagicMock: mock = Klass() int(mock) mock.mock_add_spec(object) self.assertRaises(TypeError, int, mock) mock = Klass() mock['foo'] mock.__int__.return_value =4 mock.mock_add_spec(int) self.assertEqual(int(mock), 4) self.assertRaises(TypeError, lambda: mock['foo']) def test_adding_child_mock(self): for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock: mock = Klass() mock.foo = Mock() mock.foo() self.assertEqual(mock.method_calls, [call.foo()]) self.assertEqual(mock.mock_calls, [call.foo()]) mock = Klass() mock.bar = Mock(name='name') mock.bar() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) # mock with an existing _new_parent but no name mock = Klass() mock.baz = MagicMock()() mock.baz() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) def test_adding_return_value_mock(self): for Klass in Mock, MagicMock: mock = Klass() mock.return_value = MagicMock() mock()() self.assertEqual(mock.mock_calls, [call(), call()()]) def test_manager_mock(self): class Foo(object): one = 'one' two = 'two' manager = Mock() p1 = patch.object(Foo, 'one') p2 = patch.object(Foo, 'two') mock_one = p1.start() self.addCleanup(p1.stop) mock_two = p2.start() self.addCleanup(p2.stop) manager.attach_mock(mock_one, 'one') manager.attach_mock(mock_two, 'two') Foo.two() Foo.one() self.assertEqual(manager.mock_calls, [call.two(), call.one()]) def test_magic_methods_mock_calls(self): for Klass in Mock, MagicMock: m = Klass() m.__int__ = Mock(return_value=3) m.__float__ = MagicMock(return_value=3.0) int(m) float(m) self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()]) self.assertEqual(m.method_calls, []) def test_mock_open_reuse_issue_21750(self): mocked_open = mock.mock_open(read_data='data') f1 = mocked_open('a-name') f1_data = f1.read() f2 = mocked_open('another-name') f2_data = f2.read() self.assertEqual(f1_data, f2_data) def test_mock_open_write(self): # Test exception in file writing write() mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV')) with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp): mock_filehandle = mock_namedtemp.return_value mock_write = mock_filehandle.write mock_write.side_effect = OSError('Test 2 Error') def attempt(): tempfile.NamedTemporaryFile().write('asd') self.assertRaises(OSError, attempt) def test_mock_open_alter_readline(self): mopen = mock.mock_open(read_data='foo\nbarn') mopen.return_value.readline.side_effect = lambda *args:'abc' first = mopen().readline() second = mopen().readline() self.assertEqual('abc', first) self.assertEqual('abc', second) def test_mock_open_after_eof(self): # read, readline and readlines should work after end of file. _open = mock.mock_open(read_data='foo') h = _open('bar') h.read() self.assertEqual('', h.read()) self.assertEqual('', h.read()) self.assertEqual('', h.readline()) self.assertEqual('', h.readline()) self.assertEqual([], h.readlines()) self.assertEqual([], h.readlines()) def test_mock_parents(self): for Klass in Mock, MagicMock: m = Klass() original_repr = repr(m) m.return_value = m self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m.reset_mock() self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m = Klass() m.b = m.a self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m.reset_mock() self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m = Klass() original_repr = repr(m) m.a = m() m.a.return_value = m self.assertEqual(repr(m), original_repr) self.assertEqual(repr(m.a()), original_repr) def test_attach_mock(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in classes: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'bar') self.assertIs(m.bar, m2) self.assertIn("name='mock.bar'", repr(m2)) m.bar.baz(1) self.assertEqual(m.mock_calls, [call.bar.baz(1)]) self.assertEqual(m.method_calls, [call.bar.baz(1)]) def test_attach_mock_return_value(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in Mock, MagicMock: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'return_value') self.assertIs(m(), m2) self.assertIn("name='mock()'", repr(m2)) m2.foo() self.assertEqual(m.mock_calls, call().foo().call_list()) def test_attribute_deletion(self): for mock in (Mock(), MagicMock(), NonCallableMagicMock(), NonCallableMock()): self.assertTrue(hasattr(mock, 'm')) del mock.m self.assertFalse(hasattr(mock, 'm')) del mock.f self.assertFalse(hasattr(mock, 'f')) self.assertRaises(AttributeError, getattr, mock, 'f') def test_reset_mock_does_not_raise_on_attr_deletion(self): # bpo-31177: reset_mock should not raise AttributeError when attributes # were deleted in a mock instance mock = Mock() mock.child = True del mock.child mock.reset_mock() self.assertFalse(hasattr(mock, 'child')) def test_class_assignable(self): for mock in Mock(), MagicMock(): self.assertNotIsInstance(mock, int) mock.__class__ = int self.assertIsInstance(mock, int) mock.foo def test_name_attribute_of_call(self): # bpo-35357: _Call should not disclose any attributes whose names # may clash with popular ones (such as ".name") self.assertIsNotNone(call.name) self.assertEqual(type(call.name), _Call) self.assertEqual(type(call.name().name), _Call) def test_parent_attribute_of_call(self): # bpo-35357: _Call should not disclose any attributes whose names # may clash with popular ones (such as ".parent") self.assertIsNotNone(call.parent) self.assertEqual(type(call.parent), _Call) self.assertEqual(type(call.parent().parent), _Call) if __name__ == '__main__': unittest.main()
56,946
1,767
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testcallable.py
# Copyright (C) 2007-2012 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # http://www.voidspace.org.uk/python/mock/ import unittest from unittest.test.testmock.support import is_instance, X, SomeClass from unittest.mock import ( Mock, MagicMock, NonCallableMagicMock, NonCallableMock, patch, create_autospec, CallableMixin ) class TestCallable(unittest.TestCase): def assertNotCallable(self, mock): self.assertTrue(is_instance(mock, NonCallableMagicMock)) self.assertFalse(is_instance(mock, CallableMixin)) def test_non_callable(self): for mock in NonCallableMagicMock(), NonCallableMock(): self.assertRaises(TypeError, mock) self.assertFalse(hasattr(mock, '__call__')) self.assertIn(mock.__class__.__name__, repr(mock)) def test_hierarchy(self): self.assertTrue(issubclass(MagicMock, Mock)) self.assertTrue(issubclass(NonCallableMagicMock, NonCallableMock)) def test_attributes(self): one = NonCallableMock() self.assertTrue(issubclass(type(one.one), Mock)) two = NonCallableMagicMock() self.assertTrue(issubclass(type(two.two), MagicMock)) def test_subclasses(self): class MockSub(Mock): pass one = MockSub() self.assertTrue(issubclass(type(one.one), MockSub)) class MagicSub(MagicMock): pass two = MagicSub() self.assertTrue(issubclass(type(two.two), MagicSub)) def test_patch_spec(self): patcher = patch('%s.X' % __name__, spec=True) mock = patcher.start() self.addCleanup(patcher.stop) instance = mock() mock.assert_called_once_with() self.assertNotCallable(instance) self.assertRaises(TypeError, instance) def test_patch_spec_set(self): patcher = patch('%s.X' % __name__, spec_set=True) mock = patcher.start() self.addCleanup(patcher.stop) instance = mock() mock.assert_called_once_with() self.assertNotCallable(instance) self.assertRaises(TypeError, instance) def test_patch_spec_instance(self): patcher = patch('%s.X' % __name__, spec=X()) mock = patcher.start() self.addCleanup(patcher.stop) self.assertNotCallable(mock) self.assertRaises(TypeError, mock) def test_patch_spec_set_instance(self): patcher = patch('%s.X' % __name__, spec_set=X()) mock = patcher.start() self.addCleanup(patcher.stop) self.assertNotCallable(mock) self.assertRaises(TypeError, mock) def test_patch_spec_callable_class(self): class CallableX(X): def __call__(self): pass class Sub(CallableX): pass class Multi(SomeClass, Sub): pass for arg in 'spec', 'spec_set': for Klass in CallableX, Sub, Multi: with patch('%s.X' % __name__, **{arg: Klass}) as mock: instance = mock() mock.assert_called_once_with() self.assertTrue(is_instance(instance, MagicMock)) # inherited spec self.assertRaises(AttributeError, getattr, instance, 'foobarbaz') result = instance() # instance is callable, result has no spec instance.assert_called_once_with() result(3, 2, 1) result.assert_called_once_with(3, 2, 1) result.foo(3, 2, 1) result.foo.assert_called_once_with(3, 2, 1) def test_create_autospec(self): mock = create_autospec(X) instance = mock() self.assertRaises(TypeError, instance) mock = create_autospec(X()) self.assertRaises(TypeError, mock) def test_create_autospec_instance(self): mock = create_autospec(SomeClass, instance=True) self.assertRaises(TypeError, mock) mock.wibble() mock.wibble.assert_called_once_with() self.assertRaises(TypeError, mock.wibble, 'some', 'args') if __name__ == "__main__": unittest.main()
4,283
152
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testmagicmethods.py
import unittest import sys from unittest.mock import Mock, MagicMock, _magics class TestMockingMagicMethods(unittest.TestCase): def test_deleting_magic_methods(self): mock = Mock() self.assertFalse(hasattr(mock, '__getitem__')) mock.__getitem__ = Mock() self.assertTrue(hasattr(mock, '__getitem__')) del mock.__getitem__ self.assertFalse(hasattr(mock, '__getitem__')) def test_magicmock_del(self): mock = MagicMock() # before using getitem del mock.__getitem__ self.assertRaises(TypeError, lambda: mock['foo']) mock = MagicMock() # this time use it first mock['foo'] del mock.__getitem__ self.assertRaises(TypeError, lambda: mock['foo']) def test_magic_method_wrapping(self): mock = Mock() def f(self, name): return self, 'fish' mock.__getitem__ = f self.assertIsNot(mock.__getitem__, f) self.assertEqual(mock['foo'], (mock, 'fish')) self.assertEqual(mock.__getitem__('foo'), (mock, 'fish')) mock.__getitem__ = mock self.assertIs(mock.__getitem__, mock) def test_magic_methods_isolated_between_mocks(self): mock1 = Mock() mock2 = Mock() mock1.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock1), []) self.assertRaises(TypeError, lambda: list(mock2)) def test_repr(self): mock = Mock() self.assertEqual(repr(mock), "<Mock id='%s'>" % id(mock)) mock.__repr__ = lambda s: 'foo' self.assertEqual(repr(mock), 'foo') def test_str(self): mock = Mock() self.assertEqual(str(mock), object.__str__(mock)) mock.__str__ = lambda s: 'foo' self.assertEqual(str(mock), 'foo') def test_dict_methods(self): mock = Mock() self.assertRaises(TypeError, lambda: mock['foo']) def _del(): del mock['foo'] def _set(): mock['foo'] = 3 self.assertRaises(TypeError, _del) self.assertRaises(TypeError, _set) _dict = {} def getitem(s, name): return _dict[name] def setitem(s, name, value): _dict[name] = value def delitem(s, name): del _dict[name] mock.__setitem__ = setitem mock.__getitem__ = getitem mock.__delitem__ = delitem self.assertRaises(KeyError, lambda: mock['foo']) mock['foo'] = 'bar' self.assertEqual(_dict, {'foo': 'bar'}) self.assertEqual(mock['foo'], 'bar') del mock['foo'] self.assertEqual(_dict, {}) def test_numeric(self): original = mock = Mock() mock.value = 0 self.assertRaises(TypeError, lambda: mock + 3) def add(self, other): mock.value += other return self mock.__add__ = add self.assertEqual(mock + 3, mock) self.assertEqual(mock.value, 3) del mock.__add__ def iadd(mock): mock += 3 self.assertRaises(TypeError, iadd, mock) mock.__iadd__ = add mock += 6 self.assertEqual(mock, original) self.assertEqual(mock.value, 9) self.assertRaises(TypeError, lambda: 3 + mock) mock.__radd__ = add self.assertEqual(7 + mock, mock) self.assertEqual(mock.value, 16) def test_division(self): original = mock = Mock() mock.value = 32 self.assertRaises(TypeError, lambda: mock / 2) def truediv(self, other): mock.value /= other return self mock.__truediv__ = truediv self.assertEqual(mock / 2, mock) self.assertEqual(mock.value, 16) del mock.__truediv__ def itruediv(mock): mock /= 4 self.assertRaises(TypeError, itruediv, mock) mock.__itruediv__ = truediv mock /= 8 self.assertEqual(mock, original) self.assertEqual(mock.value, 2) self.assertRaises(TypeError, lambda: 8 / mock) mock.__rtruediv__ = truediv self.assertEqual(0.5 / mock, mock) self.assertEqual(mock.value, 4) def test_hash(self): mock = Mock() # test delegation self.assertEqual(hash(mock), Mock.__hash__(mock)) def _hash(s): return 3 mock.__hash__ = _hash self.assertEqual(hash(mock), 3) def test_nonzero(self): m = Mock() self.assertTrue(bool(m)) m.__bool__ = lambda s: False self.assertFalse(bool(m)) def test_comparison(self): mock = Mock() def comp(s, o): return True mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp self. assertTrue(mock < 3) self. assertTrue(mock > 3) self. assertTrue(mock <= 3) self. assertTrue(mock >= 3) self.assertRaises(TypeError, lambda: MagicMock() < object()) self.assertRaises(TypeError, lambda: object() < MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() < MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() > object()) self.assertRaises(TypeError, lambda: object() > MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() > MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() <= object()) self.assertRaises(TypeError, lambda: object() <= MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() <= MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() >= object()) self.assertRaises(TypeError, lambda: object() >= MagicMock()) self.assertRaises(TypeError, lambda: MagicMock() >= MagicMock()) def test_equality(self): for mock in Mock(), MagicMock(): self.assertEqual(mock == mock, True) self.assertIsInstance(mock == mock, bool) self.assertEqual(mock != mock, False) self.assertIsInstance(mock != mock, bool) self.assertEqual(mock == object(), False) self.assertEqual(mock != object(), True) def eq(self, other): return other == 3 mock.__eq__ = eq self.assertTrue(mock == 3) self.assertFalse(mock == 4) def ne(self, other): return other == 3 mock.__ne__ = ne self.assertTrue(mock != 3) self.assertFalse(mock != 4) mock = MagicMock() mock.__eq__.return_value = True self.assertIsInstance(mock == 3, bool) self.assertEqual(mock == 3, True) mock.__ne__.return_value = False self.assertIsInstance(mock != 3, bool) self.assertEqual(mock != 3, False) def test_len_contains_iter(self): mock = Mock() self.assertRaises(TypeError, len, mock) self.assertRaises(TypeError, iter, mock) self.assertRaises(TypeError, lambda: 'foo' in mock) mock.__len__ = lambda s: 6 self.assertEqual(len(mock), 6) mock.__contains__ = lambda s, o: o == 3 self.assertIn(3, mock) self.assertNotIn(6, mock) mock.__iter__ = lambda s: iter('foobarbaz') self.assertEqual(list(mock), list('foobarbaz')) def test_magicmock(self): mock = MagicMock() mock.__iter__.return_value = iter([1, 2, 3]) self.assertEqual(list(mock), [1, 2, 3]) getattr(mock, '__bool__').return_value = False self.assertFalse(hasattr(mock, '__nonzero__')) self.assertFalse(bool(mock)) for entry in _magics: self.assertTrue(hasattr(mock, entry)) self.assertFalse(hasattr(mock, '__imaginery__')) def test_magic_mock_equality(self): mock = MagicMock() self.assertIsInstance(mock == object(), bool) self.assertIsInstance(mock != object(), bool) self.assertEqual(mock == object(), False) self.assertEqual(mock != object(), True) self.assertEqual(mock == mock, True) self.assertEqual(mock != mock, False) def test_magicmock_defaults(self): mock = MagicMock() self.assertEqual(int(mock), 1) self.assertEqual(complex(mock), 1j) self.assertEqual(float(mock), 1.0) self.assertNotIn(object(), mock) self.assertEqual(len(mock), 0) self.assertEqual(list(mock), []) self.assertEqual(hash(mock), object.__hash__(mock)) self.assertEqual(str(mock), object.__str__(mock)) self.assertTrue(bool(mock)) # in Python 3 oct and hex use __index__ # so these tests are for __index__ in py3k self.assertEqual(oct(mock), '0o1') self.assertEqual(hex(mock), '0x1') # how to test __sizeof__ ? def test_magic_methods_and_spec(self): class Iterable(object): def __iter__(self): pass mock = Mock(spec=Iterable) self.assertRaises(AttributeError, lambda: mock.__iter__) mock.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock), []) class NonIterable(object): pass mock = Mock(spec=NonIterable) self.assertRaises(AttributeError, lambda: mock.__iter__) def set_int(): mock.__int__ = Mock(return_value=iter([])) self.assertRaises(AttributeError, set_int) mock = MagicMock(spec=Iterable) self.assertEqual(list(mock), []) self.assertRaises(AttributeError, set_int) def test_magic_methods_and_spec_set(self): class Iterable(object): def __iter__(self): pass mock = Mock(spec_set=Iterable) self.assertRaises(AttributeError, lambda: mock.__iter__) mock.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock), []) class NonIterable(object): pass mock = Mock(spec_set=NonIterable) self.assertRaises(AttributeError, lambda: mock.__iter__) def set_int(): mock.__int__ = Mock(return_value=iter([])) self.assertRaises(AttributeError, set_int) mock = MagicMock(spec_set=Iterable) self.assertEqual(list(mock), []) self.assertRaises(AttributeError, set_int) def test_setting_unsupported_magic_method(self): mock = MagicMock() def set_setattr(): mock.__setattr__ = lambda self, name: None self.assertRaisesRegex(AttributeError, "Attempting to set unsupported magic method '__setattr__'.", set_setattr ) def test_attributes_and_return_value(self): mock = MagicMock() attr = mock.foo def _get_type(obj): # the type of every mock (or magicmock) is a custom subclass # so the real type is the second in the mro return type(obj).__mro__[1] self.assertEqual(_get_type(attr), MagicMock) returned = mock() self.assertEqual(_get_type(returned), MagicMock) def test_magic_methods_are_magic_mocks(self): mock = MagicMock() self.assertIsInstance(mock.__getitem__, MagicMock) mock[1][2].__getitem__.return_value = 3 self.assertEqual(mock[1][2][3], 3) def test_magic_method_reset_mock(self): mock = MagicMock() str(mock) self.assertTrue(mock.__str__.called) mock.reset_mock() self.assertFalse(mock.__str__.called) def test_dir(self): # overriding the default implementation for mock in Mock(), MagicMock(): def _dir(self): return ['foo'] mock.__dir__ = _dir self.assertEqual(dir(mock), ['foo']) @unittest.skipIf('PyPy' in sys.version, "This fails differently on pypy") def test_bound_methods(self): m = Mock() # XXXX should this be an expected failure instead? # this seems like it should work, but is hard to do without introducing # other api inconsistencies. Failure message could be better though. m.__iter__ = [3].__iter__ self.assertRaises(TypeError, iter, m) def test_magic_method_type(self): class Foo(MagicMock): pass foo = Foo() self.assertIsInstance(foo.__int__, Foo) def test_descriptor_from_class(self): m = MagicMock() type(m).__str__.return_value = 'foo' self.assertEqual(str(m), 'foo') def test_iterable_as_iter_return_value(self): m = MagicMock() m.__iter__.return_value = [1, 2, 3] self.assertEqual(list(m), [1, 2, 3]) self.assertEqual(list(m), [1, 2, 3]) m.__iter__.return_value = iter([4, 5, 6]) self.assertEqual(list(m), [4, 5, 6]) self.assertEqual(list(m), []) def test_matmul(self): m = MagicMock() self.assertIsInstance(m @ 1, MagicMock) m.__matmul__.return_value = 42 m.__rmatmul__.return_value = 666 m.__imatmul__.return_value = 24 self.assertEqual(m @ 1, 42) self.assertEqual(1 @ m, 666) m @= 24 self.assertEqual(m, 24) def test_divmod_and_rdivmod(self): m = MagicMock() self.assertIsInstance(divmod(5, m), MagicMock) m.__divmod__.return_value = (2, 1) self.assertEqual(divmod(m, 2), (2, 1)) m = MagicMock() foo = divmod(2, m) self.assertIsInstance(foo, MagicMock) foo_direct = m.__divmod__(2) self.assertIsInstance(foo_direct, MagicMock) bar = divmod(m, 2) self.assertIsInstance(bar, MagicMock) bar_direct = m.__rdivmod__(2) self.assertIsInstance(bar_direct, MagicMock) # http://bugs.python.org/issue23310 # Check if you can change behaviour of magic methods in MagicMock init def test_magic_in_initialization(self): m = MagicMock(**{'__str__.return_value': "12"}) self.assertEqual(str(m), "12") def test_changing_magic_set_in_initialization(self): m = MagicMock(**{'__str__.return_value': "12"}) m.__str__.return_value = "13" self.assertEqual(str(m), "13") m = MagicMock(**{'__str__.return_value': "12"}) m.configure_mock(**{'__str__.return_value': "14"}) self.assertEqual(str(m), "14") if __name__ == '__main__': unittest.main()
14,412
469
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testsentinel.py
import unittest from unittest.mock import sentinel, DEFAULT class SentinelTest(unittest.TestCase): def testSentinels(self): self.assertEqual(sentinel.whatever, sentinel.whatever, 'sentinel not stored') self.assertNotEqual(sentinel.whatever, sentinel.whateverelse, 'sentinel should be unique') def testSentinelName(self): self.assertEqual(str(sentinel.whatever), 'sentinel.whatever', 'sentinel name incorrect') def testDEFAULT(self): self.assertIs(DEFAULT, sentinel.DEFAULT) def testBases(self): # If this doesn't raise an AttributeError then help(mock) is broken self.assertRaises(AttributeError, lambda: sentinel.__bases__) if __name__ == '__main__': unittest.main()
824
29
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/testwith.py
import unittest from warnings import catch_warnings from unittest.test.testmock.support import is_instance from unittest.mock import MagicMock, Mock, patch, sentinel, mock_open, call something = sentinel.Something something_else = sentinel.SomethingElse class WithTest(unittest.TestCase): def test_with_statement(self): with patch('%s.something' % __name__, sentinel.Something2): self.assertEqual(something, sentinel.Something2, "unpatched") self.assertEqual(something, sentinel.Something) def test_with_statement_exception(self): try: with patch('%s.something' % __name__, sentinel.Something2): self.assertEqual(something, sentinel.Something2, "unpatched") raise Exception('pow') except Exception: pass else: self.fail("patch swallowed exception") self.assertEqual(something, sentinel.Something) def test_with_statement_as(self): with patch('%s.something' % __name__) as mock_something: self.assertEqual(something, mock_something, "unpatched") self.assertTrue(is_instance(mock_something, MagicMock), "patching wrong type") self.assertEqual(something, sentinel.Something) def test_patch_object_with_statement(self): class Foo(object): something = 'foo' original = Foo.something with patch.object(Foo, 'something'): self.assertNotEqual(Foo.something, original, "unpatched") self.assertEqual(Foo.something, original) def test_with_statement_nested(self): with catch_warnings(record=True): with patch('%s.something' % __name__) as mock_something, patch('%s.something_else' % __name__) as mock_something_else: self.assertEqual(something, mock_something, "unpatched") self.assertEqual(something_else, mock_something_else, "unpatched") self.assertEqual(something, sentinel.Something) self.assertEqual(something_else, sentinel.SomethingElse) def test_with_statement_specified(self): with patch('%s.something' % __name__, sentinel.Patched) as mock_something: self.assertEqual(something, mock_something, "unpatched") self.assertEqual(mock_something, sentinel.Patched, "wrong patch") self.assertEqual(something, sentinel.Something) def testContextManagerMocking(self): mock = Mock() mock.__enter__ = Mock() mock.__exit__ = Mock() mock.__exit__.return_value = False with mock as m: self.assertEqual(m, mock.__enter__.return_value) mock.__enter__.assert_called_with() mock.__exit__.assert_called_with(None, None, None) def test_context_manager_with_magic_mock(self): mock = MagicMock() with self.assertRaises(TypeError): with mock: 'foo' + 3 mock.__enter__.assert_called_with() self.assertTrue(mock.__exit__.called) def test_with_statement_same_attribute(self): with patch('%s.something' % __name__, sentinel.Patched) as mock_something: self.assertEqual(something, mock_something, "unpatched") with patch('%s.something' % __name__) as mock_again: self.assertEqual(something, mock_again, "unpatched") self.assertEqual(something, mock_something, "restored with wrong instance") self.assertEqual(something, sentinel.Something, "not restored") def test_with_statement_imbricated(self): with patch('%s.something' % __name__) as mock_something: self.assertEqual(something, mock_something, "unpatched") with patch('%s.something_else' % __name__) as mock_something_else: self.assertEqual(something_else, mock_something_else, "unpatched") self.assertEqual(something, sentinel.Something) self.assertEqual(something_else, sentinel.SomethingElse) def test_dict_context_manager(self): foo = {} with patch.dict(foo, {'a': 'b'}): self.assertEqual(foo, {'a': 'b'}) self.assertEqual(foo, {}) with self.assertRaises(NameError): with patch.dict(foo, {'a': 'b'}): self.assertEqual(foo, {'a': 'b'}) raise NameError('Konrad') self.assertEqual(foo, {}) class TestMockOpen(unittest.TestCase): def test_mock_open(self): mock = mock_open() with patch('%s.open' % __name__, mock, create=True) as patched: self.assertIs(patched, mock) open('foo') mock.assert_called_once_with('foo') def test_mock_open_context_manager(self): mock = mock_open() handle = mock.return_value with patch('%s.open' % __name__, mock, create=True): with open('foo') as f: f.read() expected_calls = [call('foo'), call().__enter__(), call().read(), call().__exit__(None, None, None)] self.assertEqual(mock.mock_calls, expected_calls) self.assertIs(f, handle) def test_mock_open_context_manager_multiple_times(self): mock = mock_open() with patch('%s.open' % __name__, mock, create=True): with open('foo') as f: f.read() with open('bar') as f: f.read() expected_calls = [ call('foo'), call().__enter__(), call().read(), call().__exit__(None, None, None), call('bar'), call().__enter__(), call().read(), call().__exit__(None, None, None)] self.assertEqual(mock.mock_calls, expected_calls) def test_explicit_mock(self): mock = MagicMock() mock_open(mock) with patch('%s.open' % __name__, mock, create=True) as patched: self.assertIs(patched, mock) open('foo') mock.assert_called_once_with('foo') def test_read_data(self): mock = mock_open(read_data='foo') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.read() self.assertEqual(result, 'foo') def test_readline_data(self): # Check that readline will return all the lines from the fake file mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') line1 = h.readline() line2 = h.readline() line3 = h.readline() self.assertEqual(line1, 'foo\n') self.assertEqual(line2, 'bar\n') self.assertEqual(line3, 'baz\n') # Check that we properly emulate a file that doesn't end in a newline mock = mock_open(read_data='foo') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.readline() self.assertEqual(result, 'foo') def test_readlines_data(self): # Test that emulating a file that ends in a newline character works mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.readlines() self.assertEqual(result, ['foo\n', 'bar\n', 'baz\n']) # Test that files without a final newline will also be correctly # emulated mock = mock_open(read_data='foo\nbar\nbaz') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.readlines() self.assertEqual(result, ['foo\n', 'bar\n', 'baz']) def test_read_bytes(self): mock = mock_open(read_data=b'\xc6') with patch('%s.open' % __name__, mock, create=True): with open('abc', 'rb') as f: result = f.read() self.assertEqual(result, b'\xc6') def test_readline_bytes(self): m = mock_open(read_data=b'abc\ndef\nghi\n') with patch('%s.open' % __name__, m, create=True): with open('abc', 'rb') as f: line1 = f.readline() line2 = f.readline() line3 = f.readline() self.assertEqual(line1, b'abc\n') self.assertEqual(line2, b'def\n') self.assertEqual(line3, b'ghi\n') def test_readlines_bytes(self): m = mock_open(read_data=b'abc\ndef\nghi\n') with patch('%s.open' % __name__, m, create=True): with open('abc', 'rb') as f: result = f.readlines() self.assertEqual(result, [b'abc\n', b'def\n', b'ghi\n']) def test_mock_open_read_with_argument(self): # At one point calling read with an argument was broken # for mocks returned by mock_open some_data = 'foo\nbar\nbaz' mock = mock_open(read_data=some_data) self.assertEqual(mock().read(10), some_data) def test_interleaved_reads(self): # Test that calling read, readline, and readlines pulls data # sequentially from the data we preload with mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') line1 = h.readline() rest = h.readlines() self.assertEqual(line1, 'foo\n') self.assertEqual(rest, ['bar\n', 'baz\n']) mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') line1 = h.readline() rest = h.read() self.assertEqual(line1, 'foo\n') self.assertEqual(rest, 'bar\nbaz\n') def test_overriding_return_values(self): mock = mock_open(read_data='foo') handle = mock() handle.read.return_value = 'bar' handle.readline.return_value = 'bar' handle.readlines.return_value = ['bar'] self.assertEqual(handle.read(), 'bar') self.assertEqual(handle.readline(), 'bar') self.assertEqual(handle.readlines(), ['bar']) # call repeatedly to check that a StopIteration is not propagated self.assertEqual(handle.readline(), 'bar') self.assertEqual(handle.readline(), 'bar') if __name__ == '__main__': unittest.main()
10,415
302
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/unittest/test/testmock/__init__.py
import os import sys import unittest here = os.path.dirname(__file__) loader = unittest.defaultTestLoader def load_tests(*args): suite = unittest.TestSuite() for fn in os.listdir(here): if fn.startswith("test") and fn.endswith(".py"): modname = "unittest.test.testmock." + fn[:-3] __import__(modname) module = sys.modules[modname] suite.addTest(loader.loadTestsFromModule(module)) return suite
465
18
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/encoders.py
# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: [email protected] """Encodings and related functions.""" __all__ = [ 'encode_7or8bit', 'encode_base64', 'encode_noop', 'encode_quopri', ] from base64 import encodebytes as _bencode from quopri import encodestring as _encodestring def _qencode(s): enc = _encodestring(s, quotetabs=True) # Must encode spaces, which quopri.encodestring() doesn't do return enc.replace(b' ', b'=20') def encode_base64(msg): """Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload(decode=True) encdata = str(_bencode(orig), 'ascii') msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'base64' def encode_quopri(msg): """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload(decode=True) encdata = _qencode(orig) msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'quoted-printable' def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload(decode=True) if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fast. If decoding from ASCII succeeds, # we know the data must be 7bit, otherwise treat it as 8bit. try: orig.decode('ascii') except UnicodeError: msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Transfer-Encoding'] = '7bit' def encode_noop(msg): """Do nothing."""
1,786
70
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/_policybase.py
"""Policy framework for the email package. Allows fine grained feature control of how the package parses and emits data. """ import abc from email import header from email import charset as _charset from email.utils import _has_surrogates __all__ = [ 'Policy', 'Compat32', 'compat32', ] class _PolicyBase: """Policy Object basic framework. This class is useless unless subclassed. A subclass should define class attributes with defaults for any values that are to be managed by the Policy object. The constructor will then allow non-default values to be set for these attributes at instance creation time. The instance will be callable, taking these same attributes keyword arguments, and returning a new instance identical to the called instance except for those values changed by the keyword arguments. Instances may be added, yielding new instances with any non-default values from the right hand operand overriding those in the left hand operand. That is, A + B == A(<non-default values of B>) The repr of an instance can be used to reconstruct the object if and only if the repr of the values can be used to reconstruct those values. """ def __init__(self, **kw): """Create new Policy, possibly overriding some defaults. See class docstring for a list of overridable attributes. """ for name, value in kw.items(): if hasattr(self, name): super(_PolicyBase,self).__setattr__(name, value) else: raise TypeError( "{!r} is an invalid keyword argument for {}".format( name, self.__class__.__name__)) def __repr__(self): args = [ "{}={!r}".format(name, value) for name, value in self.__dict__.items() ] return "{}({})".format(self.__class__.__name__, ', '.join(args)) def clone(self, **kw): """Return a new instance with specified attributes changed. The new instance has the same attribute values as the current object, except for the changes passed in as keyword arguments. """ newpolicy = self.__class__.__new__(self.__class__) for attr, value in self.__dict__.items(): object.__setattr__(newpolicy, attr, value) for attr, value in kw.items(): if not hasattr(self, attr): raise TypeError( "{!r} is an invalid keyword argument for {}".format( attr, self.__class__.__name__)) object.__setattr__(newpolicy, attr, value) return newpolicy def __setattr__(self, name, value): if hasattr(self, name): msg = "{!r} object attribute {!r} is read-only" else: msg = "{!r} object has no attribute {!r}" raise AttributeError(msg.format(self.__class__.__name__, name)) def __add__(self, other): """Non-default values from right operand override those from left. The object returned is a new instance of the subclass. """ return self.clone(**other.__dict__) def _append_doc(doc, added_doc): doc = doc.rsplit('\n', 1)[0] added_doc = added_doc.split('\n', 1)[1] return doc + '\n' + added_doc def _extend_docstrings(cls): if cls.__doc__ and cls.__doc__.startswith('+'): cls.__doc__ = _append_doc(cls.__bases__[0].__doc__, cls.__doc__) for name, attr in cls.__dict__.items(): if attr.__doc__ and attr.__doc__.startswith('+'): for c in (c for base in cls.__bases__ for c in base.mro()): doc = getattr(getattr(c, name), '__doc__') if doc: attr.__doc__ = _append_doc(doc, attr.__doc__) break return cls class Policy(_PolicyBase, metaclass=abc.ABCMeta): r"""Controls for how messages are interpreted and formatted. Most of the classes and many of the methods in the email package accept Policy objects as parameters. A Policy object contains a set of values and functions that control how input is interpreted and how output is rendered. For example, the parameter 'raise_on_defect' controls whether or not an RFC violation results in an error being raised or not, while 'max_line_length' controls the maximum length of output lines when a Message is serialized. Any valid attribute may be overridden when a Policy is created by passing it as a keyword argument to the constructor. Policy objects are immutable, but a new Policy object can be created with only certain values changed by calling the Policy instance with keyword arguments. Policy objects can also be added, producing a new Policy object in which the non-default attributes set in the right hand operand overwrite those specified in the left operand. Settable attributes: raise_on_defect -- If true, then defects should be raised as errors. Default: False. linesep -- string containing the value to use as separation between output lines. Default '\n'. cte_type -- Type of allowed content transfer encodings 7bit -- ASCII only 8bit -- Content-Transfer-Encoding: 8bit is allowed Default: 8bit. Also controls the disposition of (RFC invalid) binary data in headers; see the documentation of the binary_fold method. max_line_length -- maximum length of lines, excluding 'linesep', during serialization. None or 0 means no line wrapping is done. Default is 78. mangle_from_ -- a flag that, when True escapes From_ lines in the body of the message by putting a `>' in front of them. This is used when the message is being serialized by a generator. Default: True. message_factory -- the class to use to create new message objects. If the value is None, the default is Message. """ raise_on_defect = False linesep = '\n' cte_type = '8bit' max_line_length = 78 mangle_from_ = False message_factory = None def handle_defect(self, obj, defect): """Based on policy, either raise defect or call register_defect. handle_defect(obj, defect) defect should be a Defect subclass, but in any case must be an Exception subclass. obj is the object on which the defect should be registered if it is not raised. If the raise_on_defect is True, the defect is raised as an error, otherwise the object and the defect are passed to register_defect. This method is intended to be called by parsers that discover defects. The email package parsers always call it with Defect instances. """ if self.raise_on_defect: raise defect self.register_defect(obj, defect) def register_defect(self, obj, defect): """Record 'defect' on 'obj'. Called by handle_defect if raise_on_defect is False. This method is part of the Policy API so that Policy subclasses can implement custom defect handling. The default implementation calls the append method of the defects attribute of obj. The objects used by the email package by default that get passed to this method will always have a defects attribute with an append method. """ obj.defects.append(defect) def header_max_count(self, name): """Return the maximum allowed number of headers named 'name'. Called when a header is added to a Message object. If the returned value is not 0 or None, and there are already a number of headers with the name 'name' equal to the value returned, a ValueError is raised. Because the default behavior of Message's __setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names. """ return None @abc.abstractmethod def header_source_parse(self, sourcelines): """Given a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain surrogateescaped binary data. """ raise NotImplementedError @abc.abstractmethod def header_store_parse(self, name, value): """Given the header name and the value provided by the application program, return the (name, value) that should be stored in the model. """ raise NotImplementedError @abc.abstractmethod def header_fetch_parse(self, name, value): """Given the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. """ raise NotImplementedError @abc.abstractmethod def fold(self, name, value): """Given the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. """ raise NotImplementedError @abc.abstractmethod def fold_binary(self, name, value): """Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. """ raise NotImplementedError @_extend_docstrings class Compat32(Policy): """+ This particular policy is the backward compatibility Policy. It replicates the behavior of the email package version 5.1. """ mangle_from_ = True def _sanitize_header(self, name, value): # If the header value contains surrogates, return a Header using # the unknown-8bit charset to encode the bytes as encoded words. if not isinstance(value, str): # Assume it is already a header object return value if _has_surrogates(value): return header.Header(value, charset=_charset.UNKNOWN8BIT, header_name=name) else: return value def header_source_parse(self, sourcelines): """+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters. """ name, value = sourcelines[0].split(':', 1) value = value.lstrip(' \t') + ''.join(sourcelines[1:]) return (name, value.rstrip('\r\n')) def header_store_parse(self, name, value): """+ The name and value are returned unmodified. """ return (name, value) def header_fetch_parse(self, name, value): """+ If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified. """ return self._sanitize_header(name, value) def fold(self, name, value): """+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset. """ return self._fold(name, value, sanitize=True) def fold_binary(self, name, value): """+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and/or binary data. """ folded = self._fold(name, value, sanitize=self.cte_type=='7bit') return folded.encode('ascii', 'surrogateescape') def _fold(self, name, value, sanitize): parts = [] parts.append('%s: ' % name) if isinstance(value, str): if _has_surrogates(value): if sanitize: h = header.Header(value, charset=_charset.UNKNOWN8BIT, header_name=name) else: # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. parts.append(value) h = None else: h = header.Header(value, header_name=name) else: # Assume it is a Header-like object. h = value if h is not None: # The Header class interprets a value of None for maxlinelen as the # default value of 78, as recommended by RFC 2822. maxlinelen = 0 if self.max_line_length is not None: maxlinelen = self.max_line_length parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen)) parts.append(self.linesep) return ''.join(parts) compat32 = Compat32()
15,073
375
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/architecture.rst
:mod:`email` Package Architecture ================================= Overview -------- The email package consists of three major components: Model An object structure that represents an email message, and provides an API for creating, querying, and modifying a message. Parser Takes a sequence of characters or bytes and produces a model of the email message represented by those characters or bytes. Generator Takes a model and turns it into a sequence of characters or bytes. The sequence can either be intended for human consumption (a printable unicode string) or bytes suitable for transmission over the wire. In the latter case all data is properly encoded using the content transfer encodings specified by the relevant RFCs. Conceptually the package is organized around the model. The model provides both "external" APIs intended for use by application programs using the library, and "internal" APIs intended for use by the Parser and Generator components. This division is intentionally a bit fuzzy; the API described by this documentation is all a public, stable API. This allows for an application with special needs to implement its own parser and/or generator. In addition to the three major functional components, there is a third key component to the architecture: Policy An object that specifies various behavioral settings and carries implementations of various behavior-controlling methods. The Policy framework provides a simple and convenient way to control the behavior of the library, making it possible for the library to be used in a very flexible fashion while leveraging the common code required to parse, represent, and generate message-like objects. For example, in addition to the default :rfc:`5322` email message policy, we also have a policy that manages HTTP headers in a fashion compliant with :rfc:`2616`. Individual policy controls, such as the maximum line length produced by the generator, can also be controlled individually to meet specialized application requirements. The Model --------- The message model is implemented by the :class:`~email.message.Message` class. The model divides a message into the two fundamental parts discussed by the RFC: the header section and the body. The `Message` object acts as a pseudo-dictionary of named headers. Its dictionary interface provides convenient access to individual headers by name. However, all headers are kept internally in an ordered list, so that the information about the order of the headers in the original message is preserved. The `Message` object also has a `payload` that holds the body. A `payload` can be one of two things: data, or a list of `Message` objects. The latter is used to represent a multipart MIME message. Lists can be nested arbitrarily deeply in order to represent the message, with all terminal leaves having non-list data payloads. Message Lifecycle ----------------- The general lifecycle of a message is: Creation A `Message` object can be created by a Parser, or it can be instantiated as an empty message by an application. Manipulation The application may examine one or more headers, and/or the payload, and it may modify one or more headers and/or the payload. This may be done on the top level `Message` object, or on any sub-object. Finalization The Model is converted into a unicode or binary stream, or the model is discarded. Header Policy Control During Lifecycle -------------------------------------- One of the major controls exerted by the Policy is the management of headers during the `Message` lifecycle. Most applications don't need to be aware of this. A header enters the model in one of two ways: via a Parser, or by being set to a specific value by an application program after the Model already exists. Similarly, a header exits the model in one of two ways: by being serialized by a Generator, or by being retrieved from a Model by an application program. The Policy object provides hooks for all four of these pathways. The model storage for headers is a list of (name, value) tuples. The Parser identifies headers during parsing, and passes them to the :meth:`~email.policy.Policy.header_source_parse` method of the Policy. The result of that method is the (name, value) tuple to be stored in the model. When an application program supplies a header value (for example, through the `Message` object `__setitem__` interface), the name and the value are passed to the :meth:`~email.policy.Policy.header_store_parse` method of the Policy, which returns the (name, value) tuple to be stored in the model. When an application program retrieves a header (through any of the dict or list interfaces of `Message`), the name and value are passed to the :meth:`~email.policy.Policy.header_fetch_parse` method of the Policy to obtain the value returned to the application. When a Generator requests a header during serialization, the name and value are passed to the :meth:`~email.policy.Policy.fold` method of the Policy, which returns a string containing line breaks in the appropriate places. The :meth:`~email.policy.Policy.cte_type` Policy control determines whether or not Content Transfer Encoding is performed on the data in the header. There is also a :meth:`~email.policy.Policy.binary_fold` method for use by generators that produce binary output, which returns the folded header as binary data, possibly folded at different places than the corresponding string would be. Handling Binary Data -------------------- In an ideal world all message data would conform to the RFCs, meaning that the parser could decode the message into the idealized unicode message that the sender originally wrote. In the real world, the email package must also be able to deal with badly formatted messages, including messages containing non-ASCII characters that either have no indicated character set or are not valid characters in the indicated character set. Since email messages are *primarily* text data, and operations on message data are primarily text operations (except for binary payloads of course), the model stores all text data as unicode strings. Un-decodable binary inside text data is handled by using the `surrogateescape` error handler of the ASCII codec. As with the binary filenames the error handler was introduced to handle, this allows the email package to "carry" the binary data received during parsing along until the output stage, at which time it is regenerated in its original form. This carried binary data is almost entirely an implementation detail. The one place where it is visible in the API is in the "internal" API. A Parser must do the `surrogateescape` encoding of binary input data, and pass that data to the appropriate Policy method. The "internal" interface used by the Generator to access header values preserves the `surrogateescaped` bytes. All other interfaces convert the binary data either back into bytes or into a safe form (losing information in some cases). Backward Compatibility ---------------------- The :class:`~email.policy.Policy.Compat32` Policy provides backward compatibility with version 5.1 of the email package. It does this via the following implementation of the four+1 Policy methods described above: header_source_parse Splits the first line on the colon to obtain the name, discards any spaces after the colon, and joins the remainder of the line with all of the remaining lines, preserving the linesep characters to obtain the value. Trailing carriage return and/or linefeed characters are stripped from the resulting value string. header_store_parse Returns the name and value exactly as received from the application. header_fetch_parse If the value contains any `surrogateescaped` binary data, return the value as a :class:`~email.header.Header` object, using the character set `unknown-8bit`. Otherwise just returns the value. fold Uses :class:`~email.header.Header`'s folding to fold headers in the same way the email5.1 generator did. binary_fold Same as fold, but encodes to 'ascii'. New Algorithm ------------- header_source_parse Same as legacy behavior. header_store_parse Same as legacy behavior. header_fetch_parse If the value is already a header object, returns it. Otherwise, parses the value using the new parser, and returns the resulting object as the value. `surrogateescaped` bytes get turned into unicode unknown character code points. fold Uses the new header folding algorithm, respecting the policy settings. surrogateescaped bytes are encoded using the ``unknown-8bit`` charset for ``cte_type=7bit`` or ``8bit``. Returns a string. At some point there will also be a ``cte_type=unicode``, and for that policy fold will serialize the idealized unicode message with RFC-like folding, converting any surrogateescaped bytes into the unicode unknown character glyph. binary_fold Uses the new header folding algorithm, respecting the policy settings. surrogateescaped bytes are encoded using the `unknown-8bit` charset for ``cte_type=7bit``, and get turned back into bytes for ``cte_type=8bit``. Returns bytes. At some point there will also be a ``cte_type=unicode``, and for that policy binary_fold will serialize the message according to :rfc:``5335``.
9,561
217
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/headerregistry.py
"""Representing and manipulating email headers via custom objects. This module provides an implementation of the HeaderRegistry API. The implementation is designed to flexibly follow RFC5322 rules. Eventually HeaderRegistry will be a public API, but it isn't yet, and will probably change some before that happens. """ from types import MappingProxyType from email import utils from email import errors from email import _header_value_parser as parser class Address: def __init__(self, display_name='', username='', domain='', addr_spec=None): """Create an object representing a full email address. An address can have a 'display_name', a 'username', and a 'domain'. In addition to specifying the username and domain separately, they may be specified together by using the addr_spec keyword *instead of* the username and domain keywords. If an addr_spec string is specified it must be properly quoted according to RFC 5322 rules; an error will be raised if it is not. An Address object has display_name, username, domain, and addr_spec attributes, all of which are read-only. The addr_spec and the string value of the object are both quoted according to RFC5322 rules, but without any Content Transfer Encoding. """ inputs = ''.join(filter(None, (display_name, username, domain, addr_spec))) if '\r' in inputs or '\n' in inputs: raise ValueError("invalid arguments; address parts cannot contain CR or LF") # This clause with its potential 'raise' may only happen when an # application program creates an Address object using an addr_spec # keyword. The email library code itself must always supply username # and domain. if addr_spec is not None: if username or domain: raise TypeError("addrspec specified when username and/or " "domain also specified") a_s, rest = parser.get_addr_spec(addr_spec) if rest: raise ValueError("Invalid addr_spec; only '{}' " "could be parsed from '{}'".format( a_s, addr_spec)) if a_s.all_defects: raise a_s.all_defects[0] username = a_s.local_part domain = a_s.domain self._display_name = display_name self._username = username self._domain = domain @property def display_name(self): return self._display_name @property def username(self): return self._username @property def domain(self): return self._domain @property def addr_spec(self): """The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. """ nameset = set(self.username) if len(nameset) > len(nameset-parser.DOT_ATOM_ENDS): lp = parser.quote_string(self.username) else: lp = self.username if self.domain: return lp + '@' + self.domain if not lp: return '<>' return lp def __repr__(self): return "{}(display_name={!r}, username={!r}, domain={!r})".format( self.__class__.__name__, self.display_name, self.username, self.domain) def __str__(self): nameset = set(self.display_name) if len(nameset) > len(nameset-parser.SPECIALS): disp = parser.quote_string(self.display_name) else: disp = self.display_name if disp: addr_spec = '' if self.addr_spec=='<>' else self.addr_spec return "{} <{}>".format(disp, addr_spec) return self.addr_spec def __eq__(self, other): if type(other) != type(self): return False return (self.display_name == other.display_name and self.username == other.username and self.domain == other.domain) class Group: def __init__(self, display_name=None, addresses=None): """Create an object representing an address group. An address group consists of a display_name followed by colon and a list of addresses (see Address) terminated by a semi-colon. The Group is created by specifying a display_name and a possibly empty list of Address objects. A Group can also be used to represent a single address that is not in a group, which is convenient when manipulating lists that are a combination of Groups and individual Addresses. In this case the display_name should be set to None. In particular, the string representation of a Group whose display_name is None is the same as the Address object, if there is one and only one Address object in the addresses list. """ self._display_name = display_name self._addresses = tuple(addresses) if addresses else tuple() @property def display_name(self): return self._display_name @property def addresses(self): return self._addresses def __repr__(self): return "{}(display_name={!r}, addresses={!r}".format( self.__class__.__name__, self.display_name, self.addresses) def __str__(self): if self.display_name is None and len(self.addresses)==1: return str(self.addresses[0]) disp = self.display_name if disp is not None: nameset = set(disp) if len(nameset) > len(nameset-parser.SPECIALS): disp = parser.quote_string(disp) adrstr = ", ".join(str(x) for x in self.addresses) adrstr = ' ' + adrstr if adrstr else adrstr return "{}:{};".format(disp, adrstr) def __eq__(self, other): if type(other) != type(self): return False return (self.display_name == other.display_name and self.addresses == other.addresses) # Header Classes # class BaseHeader(str): """Base class for message headers. Implements generic behavior and provides tools for subclasses. A subclass must define a classmethod named 'parse' that takes an unfolded value string and a dictionary as its arguments. The dictionary will contain one key, 'defects', initialized to an empty list. After the call the dictionary must contain two additional keys: parse_tree, set to the parse tree obtained from parsing the header, and 'decoded', set to the string value of the idealized representation of the data from the value. (That is, encoded words are decoded, and values that have canonical representations are so represented.) The defects key is intended to collect parsing defects, which the message parser will subsequently dispose of as appropriate. The parser should not, insofar as practical, raise any errors. Defects should be added to the list instead. The standard header parsers register defects for RFC compliance issues, for obsolete RFC syntax, and for unrecoverable parsing errors. The parse method may add additional keys to the dictionary. In this case the subclass must define an 'init' method, which will be passed the dictionary as its keyword arguments. The method should use (usually by setting them as the value of similarly named attributes) and remove all the extra keys added by its parse method, and then use super to call its parent class with the remaining arguments and keywords. The subclass should also make sure that a 'max_count' attribute is defined that is either None or 1. XXX: need to better define this API. """ def __new__(cls, name, value): kwds = {'defects': []} cls.parse(value, kwds) if utils._has_surrogates(kwds['decoded']): kwds['decoded'] = utils._sanitize(kwds['decoded']) self = str.__new__(cls, kwds['decoded']) del kwds['decoded'] self.init(name, **kwds) return self def init(self, name, *, parse_tree, defects): self._name = name self._parse_tree = parse_tree self._defects = defects @property def name(self): return self._name @property def defects(self): return tuple(self._defects) def __reduce__(self): return ( _reconstruct_header, ( self.__class__.__name__, self.__class__.__bases__, str(self), ), self.__dict__) @classmethod def _reconstruct(cls, value): return str.__new__(cls, value) def fold(self, *, policy): """Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped bytes, the bytes are CTE encoded using the charset 'unknown-8bit". Any non-ASCII characters in the parse tree are CTE encoded using charset utf-8. XXX: make this a policy setting. The returned value is an ASCII-only string possibly containing linesep characters, and ending with a linesep character. The string includes the header name and the ': ' separator. """ # At some point we need to put fws here iif it was in the source. header = parser.Header([ parser.HeaderLabel([ parser.ValueTerminal(self.name, 'header-name'), parser.ValueTerminal(':', 'header-sep')]), ]) if self._parse_tree: header.append( parser.CFWSList([parser.WhiteSpaceTerminal(' ', 'fws')])) header.append(self._parse_tree) return header.fold(policy=policy) def _reconstruct_header(cls_name, bases, value): return type(cls_name, bases, {})._reconstruct(value) class UnstructuredHeader: max_count = None value_parser = staticmethod(parser.get_unstructured) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = cls.value_parser(value) kwds['decoded'] = str(kwds['parse_tree']) class UniqueUnstructuredHeader(UnstructuredHeader): max_count = 1 class DateHeader: """Header whose value consists of a single timestamp. Provides an additional attribute, datetime, which is either an aware datetime using a timezone, or a naive datetime if the timezone in the input string is -0000. Also accepts a datetime as input. The 'value' attribute is the normalized form of the timestamp, which means it is the output of format_datetime on the datetime. """ max_count = None # This is used only for folding, not for creating 'decoded'. value_parser = staticmethod(parser.get_unstructured) @classmethod def parse(cls, value, kwds): if not value: kwds['defects'].append(errors.HeaderMissingRequiredValue()) kwds['datetime'] = None kwds['decoded'] = '' kwds['parse_tree'] = parser.TokenList() return if isinstance(value, str): value = utils.parsedate_to_datetime(value) kwds['datetime'] = value kwds['decoded'] = utils.format_datetime(kwds['datetime']) kwds['parse_tree'] = cls.value_parser(kwds['decoded']) def init(self, *args, **kw): self._datetime = kw.pop('datetime') super().init(*args, **kw) @property def datetime(self): return self._datetime class UniqueDateHeader(DateHeader): max_count = 1 class AddressHeader: max_count = None @staticmethod def value_parser(value): address_list, value = parser.get_address_list(value) assert not value, 'this should not happen' return address_list @classmethod def parse(cls, value, kwds): if isinstance(value, str): # We are translating here from the RFC language (address/mailbox) # to our API language (group/address). kwds['parse_tree'] = address_list = cls.value_parser(value) groups = [] for addr in address_list.addresses: groups.append(Group(addr.display_name, [Address(mb.display_name or '', mb.local_part or '', mb.domain or '') for mb in addr.all_mailboxes])) defects = list(address_list.all_defects) else: # Assume it is Address/Group stuff if not hasattr(value, '__iter__'): value = [value] groups = [Group(None, [item]) if not hasattr(item, 'addresses') else item for item in value] defects = [] kwds['groups'] = groups kwds['defects'] = defects kwds['decoded'] = ', '.join([str(item) for item in groups]) if 'parse_tree' not in kwds: kwds['parse_tree'] = cls.value_parser(kwds['decoded']) def init(self, *args, **kw): self._groups = tuple(kw.pop('groups')) self._addresses = None super().init(*args, **kw) @property def groups(self): return self._groups @property def addresses(self): if self._addresses is None: self._addresses = tuple([address for group in self._groups for address in group.addresses]) return self._addresses class UniqueAddressHeader(AddressHeader): max_count = 1 class SingleAddressHeader(AddressHeader): @property def address(self): if len(self.addresses)!=1: raise ValueError(("value of single address header {} is not " "a single address").format(self.name)) return self.addresses[0] class UniqueSingleAddressHeader(SingleAddressHeader): max_count = 1 class MIMEVersionHeader: max_count = 1 value_parser = staticmethod(parser.parse_mime_version) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) kwds['major'] = None if parse_tree.minor is None else parse_tree.major kwds['minor'] = parse_tree.minor if parse_tree.minor is not None: kwds['version'] = '{}.{}'.format(kwds['major'], kwds['minor']) else: kwds['version'] = None def init(self, *args, **kw): self._version = kw.pop('version') self._major = kw.pop('major') self._minor = kw.pop('minor') super().init(*args, **kw) @property def major(self): return self._major @property def minor(self): return self._minor @property def version(self): return self._version class ParameterizedMIMEHeader: # Mixin that handles the params dict. Must be subclassed and # a property value_parser for the specific header provided. max_count = 1 @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) if parse_tree.params is None: kwds['params'] = {} else: # The MIME RFCs specify that parameter ordering is arbitrary. kwds['params'] = {utils._sanitize(name).lower(): utils._sanitize(value) for name, value in parse_tree.params} def init(self, *args, **kw): self._params = kw.pop('params') super().init(*args, **kw) @property def params(self): return MappingProxyType(self._params) class ContentTypeHeader(ParameterizedMIMEHeader): value_parser = staticmethod(parser.parse_content_type_header) def init(self, *args, **kw): super().init(*args, **kw) self._maintype = utils._sanitize(self._parse_tree.maintype) self._subtype = utils._sanitize(self._parse_tree.subtype) @property def maintype(self): return self._maintype @property def subtype(self): return self._subtype @property def content_type(self): return self.maintype + '/' + self.subtype class ContentDispositionHeader(ParameterizedMIMEHeader): value_parser = staticmethod(parser.parse_content_disposition_header) def init(self, *args, **kw): super().init(*args, **kw) cd = self._parse_tree.content_disposition self._content_disposition = cd if cd is None else utils._sanitize(cd) @property def content_disposition(self): return self._content_disposition class ContentTransferEncodingHeader: max_count = 1 value_parser = staticmethod(parser.parse_content_transfer_encoding_header) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) def init(self, *args, **kw): super().init(*args, **kw) self._cte = utils._sanitize(self._parse_tree.cte) @property def cte(self): return self._cte # The header factory # _default_header_map = { 'subject': UniqueUnstructuredHeader, 'date': UniqueDateHeader, 'resent-date': DateHeader, 'orig-date': UniqueDateHeader, 'sender': UniqueSingleAddressHeader, 'resent-sender': SingleAddressHeader, 'to': UniqueAddressHeader, 'resent-to': AddressHeader, 'cc': UniqueAddressHeader, 'resent-cc': AddressHeader, 'bcc': UniqueAddressHeader, 'resent-bcc': AddressHeader, 'from': UniqueAddressHeader, 'resent-from': AddressHeader, 'reply-to': UniqueAddressHeader, 'mime-version': MIMEVersionHeader, 'content-type': ContentTypeHeader, 'content-disposition': ContentDispositionHeader, 'content-transfer-encoding': ContentTransferEncodingHeader, } class HeaderRegistry: """A header_factory and header registry.""" def __init__(self, base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True): """Create a header_factory that works with the Policy API. base_class is the class that will be the last class in the created header class's __bases__ list. default_class is the class that will be used if "name" (see __call__) does not appear in the registry. use_default_map controls whether or not the default mapping of names to specialized classes is copied in to the registry when the factory is created. The default is True. """ self.registry = {} self.base_class = base_class self.default_class = default_class if use_default_map: self.registry.update(_default_header_map) def map_to_type(self, name, cls): """Register cls as the specialized class for handling "name" headers. """ self.registry[name.lower()] = cls def __getitem__(self, name): cls = self.registry.get(name.lower(), self.default_class) return type('_'+cls.__name__, (cls, self.base_class), {}) def __call__(self, name, value): """Create a header instance for header 'name' from 'value'. Creates a header instance by creating a specialized class for parsing and representing the specified header by combining the factory base_class with a specialized class from the registry or the default_class, and passing the name and value to the constructed class's constructor. """ return self[name](name, value)
20,447
595
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/generator.py
# Copyright (C) 2001-2010 Python Software Foundation # Author: Barry Warsaw # Contact: [email protected] """Classes to generate plain text from a message object tree.""" __all__ = ['Generator', 'DecodedGenerator', 'BytesGenerator'] import re import sys import time import random from copy import deepcopy from io import StringIO, BytesIO from email.utils import _has_surrogates UNDERSCORE = '_' NL = '\n' # XXX: no longer used by the code below. NLCRE = re.compile(r'\r\n|\r|\n') fcre = re.compile(r'^From ', re.MULTILINE) class Generator: """Generates output from a Message object tree. This basic generator writes the message to the given file object as plain text. """ # # Public interface # def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, *, policy=None): """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default if policy is not set), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. The policy keyword specifies a policy object that controls a number of aspects of the generator's operation. If no policy is specified, the policy associated with the Message object passed to the flatten method is used. """ if mangle_from_ is None: mangle_from_ = True if policy is None else policy.mangle_from_ self._fp = outfp self._mangle_from_ = mangle_from_ self.maxheaderlen = maxheaderlen self.policy = policy def write(self, s): # Just delegate to the file object self._fp.write(s) def flatten(self, msg, unixfrom=False, linesep=None): r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy specified when the Generator instance was created or, if none was specified, from the policy associated with the msg. """ # We use the _XXX constants for operating on data that comes directly # from the msg, and _encoded_XXX constants for operating on data that # has already been converted (to bytes in the BytesGenerator) and # inserted into a temporary buffer. policy = msg.policy if self.policy is None else self.policy if linesep is not None: policy = policy.clone(linesep=linesep) if self.maxheaderlen is not None: policy = policy.clone(max_line_length=self.maxheaderlen) self._NL = policy.linesep self._encoded_NL = self._encode(self._NL) self._EMPTY = '' self._encoded_EMPTY = self._encode(self._EMPTY) # Because we use clone (below) when we recursively process message # subparts, and because clone uses the computed policy (not None), # submessages will automatically get set to the computed policy when # they are processed by this code. old_gen_policy = self.policy old_msg_policy = msg.policy try: self.policy = policy msg.policy = policy if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) self.write(ufrom + self._NL) self._write(msg) finally: self.policy = old_gen_policy msg.policy = old_msg_policy def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, None, # Use policy setting, which we've adjusted policy=self.policy) # # Protected interface - undocumented ;/ # # Note that we use 'self.write' when what we are writing is coming from # the source, and self._fp.write when what we are writing is coming from a # buffer (because the Bytes subclass has already had a chance to transform # the data in its write method in that case). This is an entirely # pragmatic split determined by experiment; we could be more general by # always using write and having the Bytes subclass write method detect when # it has already transformed the input; but, since this whole thing is a # hack anyway this seems good enough. def _new_buffer(self): # BytesGenerator overrides this to return BytesIO. return StringIO() def _encode(self, s): # BytesGenerator overrides this to encode strings to bytes. return s def _write_lines(self, lines): # We have to transform the line endings. if not lines: return lines = NLCRE.split(lines) for line in lines[:-1]: self.write(line) self.write(self._NL) if lines[-1]: self.write(lines[-1]) # XXX logic tells me this else should be needed, but the tests fail # with it and pass without it. (NLCRE.split ends with a blank element # if and only if there was a trailing newline.) #else: # self.write(self._NL) def _write(self, msg): # We can't write the headers yet because of the following scenario: # say a multipart message includes the boundary string somewhere in # its body. We'd have to calculate the new boundary /before/ we write # the headers so that we can write the correct Content-Type: # parameter. # # The way we do this, so as to make the _handle_*() methods simpler, # is to cache any subpart writes into a buffer. The we write the # headers and the buffer contents. That way, subpart handlers can # Do The Right Thing, and can still modify the Content-Type: header if # necessary. oldfp = self._fp try: self._munge_cte = None self._fp = sfp = self._new_buffer() self._dispatch(msg) finally: self._fp = oldfp munge_cte = self._munge_cte del self._munge_cte # If we munged the cte, copy the message again and re-fix the CTE. if munge_cte: msg = deepcopy(msg) msg.replace_header('content-transfer-encoding', munge_cte[0]) msg.replace_header('content-type', munge_cte[1]) # Write the headers. First we see if the message object wants to # handle that itself. If not, we'll do it generically. meth = getattr(msg, '_write_headers', None) if meth is None: self._write_headers(msg) else: meth(self) self._fp.write(sfp.getvalue()) def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_<maintype>_<subtype>(). If there's no handler for the # full MIME type, then dispatch to self._handle_<maintype>(). If # that's missing too, then dispatch to self._writeBody(). main = msg.get_content_maintype() sub = msg.get_content_subtype() specific = UNDERSCORE.join((main, sub)).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = main.replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg) # # Default handlers # def _write_headers(self, msg): for h, v in msg.raw_items(): self.write(self.policy.fold(h, v)) # A blank line always separates headers from body self.write(self._NL) # # Handlers for writing types and subtypes # def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return if not isinstance(payload, str): raise TypeError('string payload expected: %s' % type(payload)) if _has_surrogates(msg._payload): charset = msg.get_param('charset') if charset is not None: # XXX: This copy stuff is an ugly hack to avoid modifying the # existing message. msg = deepcopy(msg) del msg['content-transfer-encoding'] msg.set_payload(payload, charset) payload = msg.get_payload() self._munge_cte = (msg['content-transfer-encoding'], msg['content-type']) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._write_lines(payload) # Default body handler _writeBody = _handle_text def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: subparts = [] elif isinstance(subparts, str): # e.g. a non-strict parse of a message with no starting boundary. self.write(subparts) return elif not isinstance(subparts, list): # Scalar payload subparts = [subparts] for part in subparts: s = self._new_buffer() g = self.clone(s) g.flatten(part, unixfrom=False, linesep=self._NL) msgtexts.append(s.getvalue()) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary() if not boundary: # Create a boundary that doesn't appear in any of the # message texts. alltext = self._encoded_NL.join(msgtexts) boundary = self._make_boundary(alltext) msg.set_boundary(boundary) # If there's a preamble, write it out, with a trailing CRLF if msg.preamble is not None: if self._mangle_from_: preamble = fcre.sub('>From ', msg.preamble) else: preamble = msg.preamble self._write_lines(preamble) self.write(self._NL) # dash-boundary transport-padding CRLF self.write('--' + boundary + self._NL) # body-part if msgtexts: self._fp.write(msgtexts.pop(0)) # *encapsulation # --> delimiter transport-padding # --> CRLF body-part for body_part in msgtexts: # delimiter transport-padding CRLF self.write(self._NL + '--' + boundary + self._NL) # body-part self._fp.write(body_part) # close-delimiter transport-padding self.write(self._NL + '--' + boundary + '--' + self._NL) if msg.epilogue is not None: if self._mangle_from_: epilogue = fcre.sub('>From ', msg.epilogue) else: epilogue = msg.epilogue self._write_lines(epilogue) def _handle_multipart_signed(self, msg): # The contents of signed parts has to stay unmodified in order to keep # the signature intact per RFC1847 2.1, so we disable header wrapping. # RDM: This isn't enough to completely preserve the part, but it helps. p = self.policy self.policy = p.clone(max_line_length=0) try: self._handle_multipart(msg) finally: self.policy = p def _handle_message_delivery_status(self, msg): # We can't just write the headers directly to self's file object # because this will leave an extra newline between the last header # block and the boundary. Sigh. blocks = [] for part in msg.get_payload(): s = self._new_buffer() g = self.clone(s) g.flatten(part, unixfrom=False, linesep=self._NL) text = s.getvalue() lines = text.split(self._encoded_NL) # Strip off the unnecessary trailing empty line if lines and lines[-1] == self._encoded_EMPTY: blocks.append(self._encoded_NL.join(lines[:-1])) else: blocks.append(text) # Now join all the blocks with an empty line. This has the lovely # effect of separating each block with an empty line, but not adding # an extra one after the last one. self._fp.write(self._encoded_NL.join(blocks)) def _handle_message(self, msg): s = self._new_buffer() g = self.clone(s) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart. Extract that object, stringify it, and # write it out. # Except, it turns out, when it's a string instead, which happens when # and only when HeaderParser is used on a message of mime type # message/rfc822. Such messages are generated by, for example, # Groupwise when forwarding unadorned messages. (Issue 7970.) So # in that case we just emit the string body. payload = msg._payload if isinstance(payload, list): g.flatten(msg.get_payload(0), unixfrom=False, linesep=self._NL) payload = s.getvalue() else: payload = self._encode(payload) self._fp.write(payload) # This used to be a module level function; we use a classmethod for this # and _compile_re so we can continue to provide the module level function # for backward compatibility by doing # _make_boundary = Generator._make_boundary # at the end of the module. It *is* internal, so we could drop that... @classmethod def _make_boundary(cls, text=None): # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. token = random.randrange(sys.maxsize) boundary = ('=' * 15) + (_fmt % token) + '==' if text is None: return boundary b = boundary counter = 0 while True: cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b @classmethod def _compile_re(cls, s, flags): return re.compile(s, flags) class BytesGenerator(Generator): """Generates a bytes version of a Message object tree. Functionally identical to the base Generator except that the output is bytes and not string. When surrogates were used in the input to encode bytes, these are decoded back to bytes for output. If the policy has cte_type set to 7bit, then the message is transformed such that the non-ASCII bytes are properly content transfer encoded, using the charset unknown-8bit. The outfp object must accept bytes in its write method. """ def write(self, s): self._fp.write(s.encode('ascii', 'surrogateescape')) def _new_buffer(self): return BytesIO() def _encode(self, s): return s.encode('ascii') def _write_headers(self, msg): # This is almost the same as the string version, except for handling # strings with 8bit bytes. for h, v in msg.raw_items(): self._fp.write(self.policy.fold_binary(h, v)) # A blank line always separates headers from body self.write(self._NL) def _handle_text(self, msg): # If the string has surrogates the original source was bytes, so # just write it back out. if msg._payload is None: return if _has_surrogates(msg._payload) and not self.policy.cte_type=='7bit': if self._mangle_from_: msg._payload = fcre.sub(">From ", msg._payload) self._write_lines(msg._payload) else: super(BytesGenerator,self)._handle_text(msg) # Default body handler _writeBody = _handle_text @classmethod def _compile_re(cls, s, flags): return re.compile(s.encode('ascii'), flags) _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]' class DecodedGenerator(Generator): """Generates a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. """ def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *, policy=None): """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] """ Generator.__init__(self, outfp, mangle_from_, maxheaderlen, policy=policy) if fmt is None: self._fmt = _FMT else: self._fmt = fmt def _dispatch(self, msg): for part in msg.walk(): maintype = part.get_content_maintype() if maintype == 'text': print(part.get_payload(decode=False), file=self) elif maintype == 'multipart': # Just skip this pass else: print(self._fmt % { 'type' : part.get_content_type(), 'maintype' : part.get_content_maintype(), 'subtype' : part.get_content_subtype(), 'filename' : part.get_filename('[no filename]'), 'description': part.get('Content-Description', '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), }, file=self) # Helper used by Generator._make_boundary _width = len(repr(sys.maxsize-1)) _fmt = '%%0%dd' % _width # Backward compatibility _make_boundary = Generator._make_boundary
19,975
509
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/feedparser.py
# Copyright (C) 2004-2006 Python Software Foundation # Authors: Baxter, Wouters and Warsaw # Contact: [email protected] """FeedParser - An email feed parser. The feed parser implements an interface for incrementally parsing an email message, line by line. This has advantages for certain applications, such as those reading email messages off a socket. FeedParser.feed() is the primary interface for pushing new data into the parser. It returns when there's nothing more it can do with the available data. When you have no more data to push into the parser, call .close(). This completes the parsing and returns the root message object. The other advantage of this parser is that it will never raise a parsing exception. Instead, when it finds something unexpected, it adds a 'defect' to the current message. Defects are just instances that live on the message object's .defects attribute. """ __all__ = ['FeedParser', 'BytesFeedParser'] import re from email import errors from email._policybase import compat32 from collections import deque from io import StringIO NLCRE = re.compile(r'\r\n|\r|\n') NLCRE_bol = re.compile(r'(\r\n|\r|\n)') NLCRE_eol = re.compile(r'(\r\n|\r|\n)\Z') NLCRE_crack = re.compile(r'(\r\n|\r|\n)') # RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character # except controls, SP, and ":". headerRE = re.compile(r'^(From |[\041-\071\073-\176]*:|[\t ])') EMPTYSTRING = '' NL = '\n' NeedMoreData = object() class BufferedSubFile(object): """A file-ish object that can have new data loaded into it. You can also push and pop line-matching predicates onto a stack. When the current predicate matches the current line, a false EOF response (i.e. empty string) is returned instead. This lets the parser adhere to a simple abstraction -- it parses until EOF closes the current message. """ def __init__(self): # Text stream of the last partial line pushed into this object. # See issue 22233 for why this is a text stream and not a list. self._partial = StringIO(newline='') # A deque of full, pushed lines self._lines = deque() # The stack of false-EOF checking predicates. self._eofstack = [] # A flag indicating whether the file has been closed or not. self._closed = False def push_eof_matcher(self, pred): self._eofstack.append(pred) def pop_eof_matcher(self): return self._eofstack.pop() def close(self): # Don't forget any trailing partial line. self._partial.seek(0) self.pushlines(self._partial.readlines()) self._partial.seek(0) self._partial.truncate() self._closed = True def readline(self): if not self._lines: if self._closed: return '' return NeedMoreData # Pop the line off the stack and see if it matches the current # false-EOF predicate. line = self._lines.popleft() # RFC 2046, section 5.1.2 requires us to recognize outer level # boundaries at any level of inner nesting. Do this, but be sure it's # in the order of most to least nested. for ateof in reversed(self._eofstack): if ateof(line): # We're at the false EOF. But push the last line back first. self._lines.appendleft(line) return '' return line def unreadline(self, line): # Let the consumer push a line back into the buffer. assert line is not NeedMoreData self._lines.appendleft(line) def push(self, data): """Push some new data into this object.""" self._partial.write(data) if '\n' not in data and '\r' not in data: # No new complete lines, wait for more. return # Crack into lines, preserving the linesep characters. self._partial.seek(0) parts = self._partial.readlines() self._partial.seek(0) self._partial.truncate() # If the last element of the list does not end in a newline, then treat # it as a partial line. We only check for '\n' here because a line # ending with '\r' might be a line that was split in the middle of a # '\r\n' sequence (see bugs 1555570 and 1721862). if not parts[-1].endswith('\n'): self._partial.write(parts.pop()) self.pushlines(parts) def pushlines(self, lines): self._lines.extend(lines) def __iter__(self): return self def __next__(self): line = self.readline() if line == '': raise StopIteration return line class FeedParser: """A feed-style parser of email.""" def __init__(self, _factory=None, *, policy=compat32): """_factory is called with no arguments to create a new message obj The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility. """ self.policy = policy self._old_style_factory = False if _factory is None: if policy.message_factory is None: from email.message import Message self._factory = Message else: self._factory = policy.message_factory else: self._factory = _factory try: _factory(policy=self.policy) except TypeError: # Assume this is an old-style factory self._old_style_factory = True self._input = BufferedSubFile() self._msgstack = [] self._parse = self._parsegen().__next__ self._cur = None self._last = None self._headersonly = False # Non-public interface for supporting Parser's headersonly flag def _set_headersonly(self): self._headersonly = True def feed(self, data): """Push more data into the parser.""" self._input.push(data) self._call_parse() def _call_parse(self): try: self._parse() except StopIteration: pass def close(self): """Parse all remaining data and return the root message object.""" self._input.close() self._call_parse() root = self._pop_message() assert not self._msgstack # Look for final set of defects if root.get_content_maintype() == 'multipart' \ and not root.is_multipart(): defect = errors.MultipartInvariantViolationDefect() self.policy.handle_defect(root, defect) return root def _new_message(self): if self._old_style_factory: msg = self._factory() else: msg = self._factory(policy=self.policy) if self._cur and self._cur.get_content_type() == 'multipart/digest': msg.set_default_type('message/rfc822') if self._msgstack: self._msgstack[-1].attach(msg) self._msgstack.append(msg) self._cur = msg self._last = msg def _pop_message(self): retval = self._msgstack.pop() if self._msgstack: self._cur = self._msgstack[-1] else: self._cur = None return retval def _parsegen(self): # Create a new message and start by parsing headers. self._new_message() headers = [] # Collect the headers, searching for a line that doesn't match the RFC # 2822 header or continuation pattern (including an empty line). for line in self._input: if line is NeedMoreData: yield NeedMoreData continue if not headerRE.match(line): # If we saw the RFC defined header/body separator # (i.e. newline), just throw it away. Otherwise the line is # part of the body so push it back. if not NLCRE.match(line): defect = errors.MissingHeaderBodySeparatorDefect() self.policy.handle_defect(self._cur, defect) self._input.unreadline(line) break headers.append(line) # Done with the headers, so parse them and figure out what we're # supposed to see in the body of the message. self._parse_headers(headers) # Headers-only parsing is a backwards compatibility hack, which was # necessary in the older parser, which could raise errors. All # remaining lines in the input are thrown into the message body. if self._headersonly: lines = [] while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue if line == '': break lines.append(line) self._cur.set_payload(EMPTYSTRING.join(lines)) return if self._cur.get_content_type() == 'message/delivery-status': # message/delivery-status contains blocks of headers separated by # a blank line. We'll represent each header block as a separate # nested message object, but the processing is a bit different # than standard message/* types because there is no body for the # nested messages. A blank line separates the subparts. while True: self._input.push_eof_matcher(NLCRE.match) for retval in self._parsegen(): if retval is NeedMoreData: yield NeedMoreData continue break msg = self._pop_message() # We need to pop the EOF matcher in order to tell if we're at # the end of the current file, not the end of the last block # of message headers. self._input.pop_eof_matcher() # The input stream must be sitting at the newline or at the # EOF. We want to see if we're at the end of this subpart, so # first consume the blank line, then test the next line to see # if we're at this subpart's EOF. while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue break while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue break if line == '': break # Not at EOF so this is a line we're going to need. self._input.unreadline(line) return if self._cur.get_content_maintype() == 'message': # The message claims to be a message/* type, then what follows is # another RFC 2822 message. for retval in self._parsegen(): if retval is NeedMoreData: yield NeedMoreData continue break self._pop_message() return if self._cur.get_content_maintype() == 'multipart': boundary = self._cur.get_boundary() if boundary is None: # The message /claims/ to be a multipart but it has not # defined a boundary. That's a problem which we'll handle by # reading everything until the EOF and marking the message as # defective. defect = errors.NoBoundaryInMultipartDefect() self.policy.handle_defect(self._cur, defect) lines = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue lines.append(line) self._cur.set_payload(EMPTYSTRING.join(lines)) return # Make sure a valid content type was specified per RFC 2045:6.4. if (self._cur.get('content-transfer-encoding', '8bit').lower() not in ('7bit', '8bit', 'binary')): defect = errors.InvalidMultipartContentTransferEncodingDefect() self.policy.handle_defect(self._cur, defect) # Create a line match predicate which matches the inter-part # boundary as well as the end-of-multipart boundary. Don't push # this onto the input stream until we've scanned past the # preamble. separator = '--' + boundary boundaryre = re.compile( '(?P<sep>' + re.escape(separator) + r')(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$') capturing_preamble = True preamble = [] linesep = False close_boundary_seen = False while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue if line == '': break mo = boundaryre.match(line) if mo: # If we're looking at the end boundary, we're done with # this multipart. If there was a newline at the end of # the closing boundary, then we need to initialize the # epilogue with the empty string (see below). if mo.group('end'): close_boundary_seen = True linesep = mo.group('linesep') break # We saw an inter-part boundary. Were we in the preamble? if capturing_preamble: if preamble: # According to RFC 2046, the last newline belongs # to the boundary. lastline = preamble[-1] eolmo = NLCRE_eol.search(lastline) if eolmo: preamble[-1] = lastline[:-len(eolmo.group(0))] self._cur.preamble = EMPTYSTRING.join(preamble) capturing_preamble = False self._input.unreadline(line) continue # We saw a boundary separating two parts. Consume any # multiple boundary lines that may be following. Our # interpretation of RFC 2046 BNF grammar does not produce # body parts within such double boundaries. while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue mo = boundaryre.match(line) if not mo: self._input.unreadline(line) break # Recurse to parse this subpart; the input stream points # at the subpart's first line. self._input.push_eof_matcher(boundaryre.match) for retval in self._parsegen(): if retval is NeedMoreData: yield NeedMoreData continue break # Because of RFC 2046, the newline preceding the boundary # separator actually belongs to the boundary, not the # previous subpart's payload (or epilogue if the previous # part is a multipart). if self._last.get_content_maintype() == 'multipart': epilogue = self._last.epilogue if epilogue == '': self._last.epilogue = None elif epilogue is not None: mo = NLCRE_eol.search(epilogue) if mo: end = len(mo.group(0)) self._last.epilogue = epilogue[:-end] else: payload = self._last._payload if isinstance(payload, str): mo = NLCRE_eol.search(payload) if mo: payload = payload[:-len(mo.group(0))] self._last._payload = payload self._input.pop_eof_matcher() self._pop_message() # Set the multipart up for newline cleansing, which will # happen if we're in a nested multipart. self._last = self._cur else: # I think we must be in the preamble assert capturing_preamble preamble.append(line) # We've seen either the EOF or the end boundary. If we're still # capturing the preamble, we never saw the start boundary. Note # that as a defect and store the captured text as the payload. if capturing_preamble: defect = errors.StartBoundaryNotFoundDefect() self.policy.handle_defect(self._cur, defect) self._cur.set_payload(EMPTYSTRING.join(preamble)) epilogue = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue self._cur.epilogue = EMPTYSTRING.join(epilogue) return # If we're not processing the preamble, then we might have seen # EOF without seeing that end boundary...that is also a defect. if not close_boundary_seen: defect = errors.CloseBoundaryNotFoundDefect() self.policy.handle_defect(self._cur, defect) return # Everything from here to the EOF is epilogue. If the end boundary # ended in a newline, we'll need to make sure the epilogue isn't # None if linesep: epilogue = [''] else: epilogue = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue epilogue.append(line) # Any CRLF at the front of the epilogue is not technically part of # the epilogue. Also, watch out for an empty string epilogue, # which means a single newline. if epilogue: firstline = epilogue[0] bolmo = NLCRE_bol.match(firstline) if bolmo: epilogue[0] = firstline[len(bolmo.group(0)):] self._cur.epilogue = EMPTYSTRING.join(epilogue) return # Otherwise, it's some non-multipart type, so the entire rest of the # file contents becomes the payload. lines = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue lines.append(line) self._cur.set_payload(EMPTYSTRING.join(lines)) def _parse_headers(self, lines): # Passed a list of lines that make up the headers for the current msg lastheader = '' lastvalue = [] for lineno, line in enumerate(lines): # Check for continuation if line[0] in ' \t': if not lastheader: # The first line of the headers was a continuation. This # is illegal, so let's note the defect, store the illegal # line, and ignore it for purposes of headers. defect = errors.FirstHeaderLineIsContinuationDefect(line) self.policy.handle_defect(self._cur, defect) continue lastvalue.append(line) continue if lastheader: self._cur.set_raw(*self.policy.header_source_parse(lastvalue)) lastheader, lastvalue = '', [] # Check for envelope header, i.e. unix-from if line.startswith('From '): if lineno == 0: # Strip off the trailing newline mo = NLCRE_eol.search(line) if mo: line = line[:-len(mo.group(0))] self._cur.set_unixfrom(line) continue elif lineno == len(lines) - 1: # Something looking like a unix-from at the end - it's # probably the first line of the body, so push back the # line and stop. self._input.unreadline(line) return else: # Weirdly placed unix-from line. Note this as a defect # and ignore it. defect = errors.MisplacedEnvelopeHeaderDefect(line) self._cur.defects.append(defect) continue # Split the line on the colon separating field name from value. # There will always be a colon, because if there wasn't the part of # the parser that calls us would have started parsing the body. i = line.find(':') # If the colon is on the start of the line the header is clearly # malformed, but we might be able to salvage the rest of the # message. Track the error but keep going. if i == 0: defect = errors.InvalidHeaderDefect("Missing header name.") self._cur.defects.append(defect) continue assert i>0, "_parse_headers fed line with no : and no leading WS" lastheader = line[:i] lastvalue = [line] # Done with all the lines, so handle the last header. if lastheader: self._cur.set_raw(*self.policy.header_source_parse(lastvalue)) class BytesFeedParser(FeedParser): """Like FeedParser, but feed accepts bytes.""" def feed(self, data): super().feed(data.decode('ascii', 'surrogateescape'))
22,775
537
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/email/quoprimime.py
# Copyright (C) 2001-2006 Python Software Foundation # Author: Ben Gertzfield # Contact: [email protected] """Quoted-printable content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to safely encode text that is in a character set similar to the 7-bit US ASCII character set, but that includes some 8-bit characters that are normally not allowed in email bodies or headers. Quoted-printable is very space-inefficient for encoding binary files; use the email.base64mime module for that instead. This module provides an interface to encode and decode both headers and bodies with quoted-printable encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:/From:/Cc: etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. """ __all__ = [ 'body_decode', 'body_encode', 'body_length', 'decode', 'decodestring', 'header_decode', 'header_encode', 'header_length', 'quote', 'unquote', ] import re from string import ascii_letters, digits, hexdigits CRLF = '\r\n' NL = '\n' EMPTYSTRING = '' # Build a mapping of octets to the expansion of that octet. Since we're only # going to have 256 of these things, this isn't terribly inefficient # space-wise. Remember that headers and bodies have different sets of safe # characters. Initialize both maps with the full expansion, and then override # the safe bytes with the more compact form. _QUOPRI_MAP = ['=%02X' % c for c in range(256)] _QUOPRI_HEADER_MAP = _QUOPRI_MAP[:] _QUOPRI_BODY_MAP = _QUOPRI_MAP[:] # Safe header bytes which need no encoding. for c in b'-!*+/' + ascii_letters.encode('ascii') + digits.encode('ascii'): _QUOPRI_HEADER_MAP[c] = chr(c) # Headers have one other special encoding; spaces become underscores. _QUOPRI_HEADER_MAP[ord(' ')] = '_' # Safe body bytes which need no encoding. for c in (b' !"#$%&\'()*+,-./0123456789:;<>' b'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`' b'abcdefghijklmnopqrstuvwxyz{|}~\t'): _QUOPRI_BODY_MAP[c] = chr(c) # Helpers def header_check(octet): """Return True if the octet should be escaped with header quopri.""" return chr(octet) != _QUOPRI_HEADER_MAP[octet] def body_check(octet): """Return True if the octet should be escaped with body quopri.""" return chr(octet) != _QUOPRI_BODY_MAP[octet] def header_length(bytearray): """Return a header quoted-printable encoding length. Note that this does not include any RFC 2047 chrome added by `header_encode()`. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with quoted-printable for headers. """ return sum(len(_QUOPRI_HEADER_MAP[octet]) for octet in bytearray) def body_length(bytearray): """Return a body quoted-printable encoding length. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with quoted-printable for bodies. """ return sum(len(_QUOPRI_BODY_MAP[octet]) for octet in bytearray) def _max_append(L, s, maxlen, extra=''): if not isinstance(s, str): s = chr(s) if not L: L.append(s.lstrip()) elif len(L[-1]) + len(s) <= maxlen: L[-1] += extra + s else: L.append(s.lstrip()) def unquote(s): """Turn a string in the form =AB to the ASCII character with value 0xab""" return chr(int(s[1:3], 16)) def quote(c): return _QUOPRI_MAP[ord(c)] def header_encode(header_bytes, charset='iso-8859-1'): """Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use in the RFC 2046 header. It defaults to iso-8859-1. """ # Return empty headers as an empty string. if not header_bytes: return '' # Iterate over every byte, encoding if necessary. encoded = header_bytes.decode('latin1').translate(_QUOPRI_HEADER_MAP) # Now add the RFC chrome to each encoded chunk and glue the chunks # together. return '=?%s?q?%s?=' % (charset, encoded) _QUOPRI_BODY_ENCODE_MAP = _QUOPRI_BODY_MAP[:] for c in b'\r\n': _QUOPRI_BODY_ENCODE_MAP[c] = chr(c) def body_encode(body, maxlinelen=76, eol=NL): """Encode with quoted-printable, wrapping at maxlinelen characters. Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly in an email. Each line will be wrapped at, at most, maxlinelen characters before the eol string (maxlinelen defaults to 76 characters, the maximum value permitted by RFC 2045). Long lines will have the 'soft line break' quoted-printable character "=" appended to them, so the decoded text will be identical to the original text. The minimum maxlinelen is 4 to have room for a quoted character ("=XX") followed by a soft line break. Smaller values will generate a ValueError. """ if maxlinelen < 4: raise ValueError("maxlinelen must be at least 4") if not body: return body # quote special characters body = body.translate(_QUOPRI_BODY_ENCODE_MAP) soft_break = '=' + eol # leave space for the '=' at the end of a line maxlinelen1 = maxlinelen - 1 encoded_body = [] append = encoded_body.append for line in body.splitlines(): # break up the line into pieces no longer than maxlinelen - 1 start = 0 laststart = len(line) - 1 - maxlinelen while start <= laststart: stop = start + maxlinelen1 # make sure we don't break up an escape sequence if line[stop - 2] == '=': append(line[start:stop - 1]) start = stop - 2 elif line[stop - 1] == '=': append(line[start:stop]) start = stop - 1 else: append(line[start:stop] + '=') start = stop # handle rest of line, special case if line ends in whitespace if line and line[-1] in ' \t': room = start - laststart if room >= 3: # It's a whitespace character at end-of-line, and we have room # for the three-character quoted encoding. q = quote(line[-1]) elif room == 2: # There's room for the whitespace character and a soft break. q = line[-1] + soft_break else: # There's room only for a soft break. The quoted whitespace # will be the only content on the subsequent line. q = soft_break + quote(line[-1]) append(line[start:-1] + q) else: append(line[start:]) # add back final newline if present if body[-1] in CRLF: append('') return eol.join(encoded_body) # BAW: I'm not sure if the intent was for the signature of this function to be # the same as base64MIME.decode() or not... def decode(encoded, eol=NL): """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ if not encoded: return encoded # BAW: see comment in encode() above. Again, we're building up the # decoded string with string concatenation, which could be done much more # efficiently. decoded = '' for line in encoded.splitlines(): line = line.rstrip() if not line: decoded += eol continue i = 0 n = len(line) while i < n: c = line[i] if c != '=': decoded += c i += 1 # Otherwise, c == "=". Are we at the end of the line? If so, add # a soft line break. elif i+1 == n: i += 1 continue # Decode if in form =AB elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits: decoded += unquote(line[i:i+3]) i += 3 # Otherwise, not in form =AB, pass literally else: decoded += c i += 1 if i == n: decoded += eol # Special case if original string did not end with eol if encoded[-1] not in '\r\n' and decoded.endswith(eol): decoded = decoded[:-1] return decoded # For convenience and backwards compatibility w/ standard base64 module body_decode = decode decodestring = decode def _unquote_match(match): """Turn a match in the form =AB to the ASCII character with value 0xab""" s = match.group(0) return unquote(s) # Header decoding is done a bit differently def header_decode(s): """Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use the high level email.header class for that functionality. """ s = s.replace('_', ' ') return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, flags=re.ASCII)
9,858
300
jart/cosmopolitan
false