desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'2to3 two files in one directory with a new output dir.'
def test_filename_changing_on_output_two_files(self):
self.setup_test_source_trees() err = io.StringIO() py2_files = [self.trivial_py2_file, self.init_py2_file] expected_files = set((os.path.basename(name) for name in py2_files)) ret = self.run_2to3_capture((['-n', '-w', '--write-unchanged-files', '--no-diffs', '--output-dir', self.py3_dest_dir] + py2_...
'2to3 a single file with a new output dir.'
def test_filename_changing_on_output_single_file(self):
self.setup_test_source_trees() err = io.StringIO() ret = self.run_2to3_capture(['-n', '-w', '--no-diffs', '--output-dir', self.py3_dest_dir, self.trivial_py2_file], io.StringIO(''), io.StringIO(), err) self.assertEqual(ret, 0) stderr = err.getvalue() self.assertIn(('Output in %r will ...
'Reduces a fixer\'s pattern tree to a linear path and adds it to the matcher(a common Aho-Corasick automaton). The fixer is appended on the matching states and called when they are reached'
def add_fixer(self, fixer):
self.fixers.append(fixer) tree = reduce_tree(fixer.pattern_tree) linear = tree.get_linear_subpattern() match_nodes = self.add(linear, start=self.root) for match_node in match_nodes: match_node.fixers.append(fixer)
'Recursively adds a linear pattern to the AC automaton'
def add(self, pattern, start):
if (not pattern): return [start] if isinstance(pattern[0], tuple): match_nodes = [] for alternative in pattern[0]: end_nodes = self.add(alternative, start=start) for end in end_nodes: match_nodes.extend(self.add(pattern[1:], end)) return ma...
'The main interface with the bottom matcher. The tree is traversed from the bottom using the constructed automaton. Nodes are only checked once as the tree is retraversed. When the automaton fails, we give it one more shot(in case the above tree matches as a whole with the rejected leaf), then we break for the next lea...
def run(self, leaves):
current_ac_node = self.root results = defaultdict(list) for leaf in leaves: current_ast_node = leaf while current_ast_node: current_ast_node.was_checked = True for child in current_ast_node.children: if (isinstance(child, pytree.Leaf) and (child.value ...
'Prints a graphviz diagram of the BM automaton(for debugging)'
def print_ac(self):
print 'digraph g{' def print_node(node): for subnode_key in node.transition_table.keys(): subnode = node.transition_table[subnode_key] print ('%d -> %d [label=%s] //%s' % (node.id, subnode.id, type_repr(subnode_key), str(subnode.fixers))) if (subnode_ke...
'Initializer. Creates an attribute for each grammar symbol (nonterminal), whose value is the symbol\'s type (an int >= 256).'
def __init__(self, grammar):
for (name, symbol) in grammar.symbol2number.items(): setattr(self, name, symbol)
'Transform for the basic import case. Replaces the old import name with a comma separated list of its replacements.'
def transform_import(self, node, results):
import_mod = results.get('module') pref = import_mod.prefix names = [] for name in MAPPING[import_mod.value][:(-1)]: names.extend([Name(name[0], prefix=pref), Comma()]) names.append(Name(MAPPING[import_mod.value][(-1)][0], prefix=pref)) import_mod.replace(names)
'Transform for imports of specific module elements. Replaces the module to be imported from with the appropriate new module.'
def transform_member(self, node, results):
mod_member = results.get('mod_member') pref = mod_member.prefix member = results.get('member') if member: if isinstance(member, list): member = member[0] new_name = None for change in MAPPING[mod_member.value]: if (member.value in change[1]): ...
'Transform for calls to module members in code.'
def transform_dot(self, node, results):
module_dot = results.get('bare_with_attr') member = results.get('member') new_name = None if isinstance(member, list): member = member[0] for change in MAPPING[module_dot.value]: if (member.value in change[1]): new_name = change[0] break if new_name: ...
'Initializer. Args: fixer_names: a list of fixers to import options: an dict with configuration. explicit: a list of fixers to run even if they are explicit.'
def __init__(self, fixer_names, options=None, explicit=None):
self.fixers = fixer_names self.explicit = (explicit or []) self.options = self._default_options.copy() if (options is not None): self.options.update(options) if self.options['print_function']: self.grammar = pygram.python_grammar_no_print_statement else: self.grammar = py...
'Inspects the options to load the requested patterns and handlers. Returns: (pre_order, post_order), where pre_order is the list of fixers that want a pre-order AST traversal, and post_order is the list that want post-order traversal.'
def get_fixers(self):
pre_order_fixers = [] post_order_fixers = [] for fix_mod_path in self.fixers: mod = __import__(fix_mod_path, {}, {}, ['*']) fix_name = fix_mod_path.rsplit('.', 1)[(-1)] if fix_name.startswith(self.FILE_PREFIX): fix_name = fix_name[len(self.FILE_PREFIX):] parts = f...
'Called when an error occurs.'
def log_error(self, msg, *args, **kwds):
raise
'Hook to log a message.'
def log_message(self, msg, *args):
if args: msg = (msg % args) self.logger.info(msg)
'Called with the old version, new version, and filename of a refactored file.'
def print_output(self, old_text, new_text, filename, equal):
pass
'Refactor a list of files and directories.'
def refactor(self, items, write=False, doctests_only=False):
for dir_or_file in items: if os.path.isdir(dir_or_file): self.refactor_dir(dir_or_file, write, doctests_only) else: self.refactor_file(dir_or_file, write, doctests_only)
'Descends down a directory and refactor every Python file found. Python files are assumed to have a .py extension. Files and subdirectories starting with \'.\' are skipped.'
def refactor_dir(self, dir_name, write=False, doctests_only=False):
py_ext = (os.extsep + 'py') for (dirpath, dirnames, filenames) in os.walk(dir_name): self.log_debug('Descending into %s', dirpath) dirnames.sort() filenames.sort() for name in filenames: if ((not name.startswith('.')) and (os.path.splitext(name)[1] == py_ext)): ...
'Do our best to decode a Python source file correctly.'
def _read_python_source(self, filename):
try: f = open(filename, 'rb') except OSError as err: self.log_error("Can't open %s: %s", filename, err) return (None, None) try: encoding = tokenize.detect_encoding(f.readline)[0] finally: f.close() with _open_with_encoding(filename, 'r', encoding=enc...
'Refactors a file.'
def refactor_file(self, filename, write=False, doctests_only=False):
(input, encoding) = self._read_python_source(filename) if (input is None): return input += '\n' if doctests_only: self.log_debug('Refactoring doctests in %s', filename) output = self.refactor_docstring(input, filename) if (self.write_unchanged_files or (output !=...
'Refactor a given input string. Args: data: a string holding the code to be refactored. name: a human-readable name for use in error/log messages. Returns: An AST corresponding to the refactored input stream; None if there were errors during the parse.'
def refactor_string(self, data, name):
features = _detect_future_features(data) if ('print_function' in features): self.driver.grammar = pygram.python_grammar_no_print_statement try: tree = self.driver.parse_string(data) except Exception as err: self.log_error("Can't parse %s: %s: %s", name, err.__class__....
'Refactors a parse tree (modifying the tree in place). For compatible patterns the bottom matcher module is used. Otherwise the tree is traversed node-to-node for matches. Args: tree: a pytree.Node instance representing the root of the tree to be refactored. name: a human-readable name for this tree. Returns: True if t...
def refactor_tree(self, tree, name):
for fixer in chain(self.pre_order, self.post_order): fixer.start_tree(tree, name) self.traverse_by(self.bmi_pre_order_heads, tree.pre_order()) self.traverse_by(self.bmi_post_order_heads, tree.post_order()) match_set = self.BM.run(tree.leaves()) while any(match_set.values()): for fixe...
'Traverse an AST, applying a set of fixers to each node. This is a helper method for refactor_tree(). Args: fixers: a list of fixer instances. traversal: a generator that yields AST nodes. Returns: None'
def traverse_by(self, fixers, traversal):
if (not fixers): return for node in traversal: for fixer in fixers[node.type]: results = fixer.match(node) if results: new = fixer.transform(node, results) if (new is not None): node.replace(new) node...
'Called when a file has been refactored and there may be changes.'
def processed_file(self, new_text, filename, old_text=None, write=False, encoding=None):
self.files.append(filename) if (old_text is None): old_text = self._read_python_source(filename)[0] if (old_text is None): return equal = (old_text == new_text) self.print_output(old_text, new_text, filename, equal) if equal: self.log_debug('No changes to ...
'Writes a string to a file. It first shows a unified diff between the old text and the new text, and then rewrites the file; the latter is only done if the write option is set.'
def write_file(self, new_text, filename, old_text, encoding=None):
try: f = _open_with_encoding(filename, 'w', encoding=encoding) except OSError as err: self.log_error("Can't create %s: %s", filename, err) return try: f.write(_to_system_newlines(new_text)) except OSError as err: self.log_error("Can't write %s: %...
'Refactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be continued with "..." prompts, as long as the "..." is indented the same as the ">>>". (Unfortunately we can\'t use the doctest module\'s parser, since, l...
def refactor_docstring(self, input, filename):
result = [] block = None block_lineno = None indent = None lineno = 0 for line in input.splitlines(keepends=True): lineno += 1 if line.lstrip().startswith(self.PS1): if (block is not None): result.extend(self.refactor_doctest(block, block_lineno, inden...
'Refactors one doctest. A doctest is given as a block of lines, the first of which starts with ">>>" (possibly indented), while the remaining lines start with "..." (identically indented).'
def refactor_doctest(self, block, lineno, indent, filename):
try: tree = self.parse_block(block, lineno, indent) except Exception as err: if self.logger.isEnabledFor(logging.DEBUG): for line in block: self.log_debug('Source: %s', line.rstrip('\n')) self.log_error("Can't parse docstring in %s line %s...
'Parses a block into a tree. This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree.'
def parse_block(self, block, lineno, indent):
tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) tree.future_features = frozenset() return tree
'Wraps a tokenize stream to systematically modify start/end.'
def wrap_toks(self, block, lineno, indent):
tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__) for (type, value, (line0, col0), (line1, col1), line_text) in tokens: line0 += (lineno - 1) line1 += (lineno - 1) (yield (type, value, (line0, col0), (line1, col1), line_text))
'Generates lines as expected by tokenize from a list of lines. This strips the first len(indent + self.PS1) characters off each line.'
def gen_lines(self, block, indent):
prefix1 = (indent + self.PS1) prefix2 = (indent + self.PS2) prefix = prefix1 for line in block: if line.startswith(prefix): (yield line[len(prefix):]) elif (line == (prefix.rstrip() + '\n')): (yield '\n') else: raise AssertionError(('line=%r, ...
'Initializer. Subclass may override. Args: options: an dict containing the options passed to RefactoringTool that could be used to customize the fixer through the command line. log: a list to append warnings and other messages to.'
def __init__(self, options, log):
self.options = options self.log = log self.compile_pattern()
'Compiles self.PATTERN into self.pattern. Subclass may override if it doesn\'t want to use self.{pattern,PATTERN} in .match().'
def compile_pattern(self):
if (self.PATTERN is not None): PC = PatternCompiler() (self.pattern, self.pattern_tree) = PC.compile_pattern(self.PATTERN, with_tree=True)
'Set the filename. The main refactoring tool should call this.'
def set_filename(self, filename):
self.filename = filename
'Returns match for a given parse tree node. Should return a true or false object (not necessarily a bool). It may return a non-empty dict of matching sub-nodes as returned by a matching pattern. Subclass may override.'
def match(self, node):
results = {'node': node} return (self.pattern.match(node, results) and results)
'Returns the transformation for a given parse tree node. Args: node: the root of the parse tree that matched the fixer. results: a dict mapping symbolic names to part of the match. Returns: None, or a node that is a modified copy of the argument node. The node argument may also be modified in-place to effect the same ...
def transform(self, node, results):
raise NotImplementedError()
'Return a string suitable for use as an identifier The new name is guaranteed not to conflict with other identifiers.'
def new_name(self, template='xxx_todo_changeme'):
name = template while (name in self.used_names): name = (template + str(next(self.numbers))) self.used_names.add(name) return name
'Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically. First argument is the top-level node for the code in question. Optional second argument is why it can\'t be converted.'
def cannot_convert(self, node, reason=None):
lineno = node.get_lineno() for_output = node.clone() for_output.prefix = '' msg = 'Line %d: could not convert: %s' self.log_message((msg % (lineno, for_output))) if reason: self.log_message(reason)
'Used for warning the user about possible uncertainty in the translation. First argument is the top-level node for the code in question. Optional second argument is why it can\'t be converted.'
def warning(self, node, reason):
lineno = node.get_lineno() self.log_message(('Line %d: %s' % (lineno, reason)))
'Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from.'
def start_tree(self, tree, filename):
self.used_names = tree.used_names self.set_filename(filename) self.numbers = itertools.count(1) self.first_log = True
'Some fixers need to maintain tree-wide state. This method is called once, at the conclusion of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from.'
def finish_tree(self, tree, filename):
pass
'Convert/check value type.'
def _convert_string_type(self, value):
if (type(value) is str): return value raise AssertionError('Header names/values must be of type str (got {0})'.format(repr(value)))
'Return the total number of headers, including duplicates.'
def __len__(self):
return len(self._headers)
'Set the value of a header.'
def __setitem__(self, name, val):
del self[name] self._headers.append((self._convert_string_type(name), self._convert_string_type(val)))
'Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing.'
def __delitem__(self, name):
name = self._convert_string_type(name.lower()) self._headers[:] = [kv for kv in self._headers if (kv[0].lower() != name)]
'Get the first header value for \'name\' Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, the first exactly which occurrance gets returned is undefined. Use getall() to get all the values matching a header field name.'
def __getitem__(self, name):
return self.get(name)
'Return true if the message contains the header.'
def __contains__(self, name):
return (self.get(name) is not None)
'Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an emp...
def get_all(self, name):
name = self._convert_string_type(name.lower()) return [kv[1] for kv in self._headers if (kv[0].lower() == name)]
'Get the first header value for \'name\', or return \'default\''
def get(self, name, default=None):
name = self._convert_string_type(name.lower()) for (k, v) in self._headers: if (k.lower() == name): return v return default
'Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def keys(self):
return [k for (k, v) in self._headers]
'Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def values(self):
return [v for (k, v) in self._headers]
'Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def items(self):
return self._headers[:]
'str() returns the formatted headers, complete with end line, suitable for direct HTTP transmission.'
def __str__(self):
return '\r\n'.join(([('%s: %s' % kv) for kv in self._headers] + ['', '']))
'Return first matching header value for \'name\', or \'value\' If there is no header named \'name\', add a new header with name \'name\' and value \'value\'.'
def setdefault(self, name, value):
result = self.get(name) if (result is None): self._headers.append((self._convert_string_type(name), self._convert_string_type(value))) return value else: return result
'Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header(\...
def add_header(self, _name, _value, **_params):
parts = [] if (_value is not None): _value = self._convert_string_type(_value) parts.append(_value) for (k, v) in _params.items(): k = self._convert_string_type(k) if (v is None): parts.append(k.replace('_', '-')) else: v = self._convert_string...
'Invoke the application'
def run(self, application):
try: self.setup_environ() self.result = application(self.environ, self.start_response) self.finish_response() except: try: self.handle_error() except: self.close() raise
'Set up the environment for one request'
def setup_environ(self):
env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread']...
'Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call \'self.close()\' once the response is finished.'
def finish_response(self):
try: if ((not self.result_is_file()) or (not self.sendfile())): for data in self.result: self.write(data) self.finish_content() finally: self.close()
'Return the URL scheme being used'
def get_scheme(self):
return guess_scheme(self.environ)
'Compute Content-Length or switch to chunked encoding if possible'
def set_content_length(self):
try: blocks = len(self.result) except (TypeError, AttributeError, NotImplementedError): pass else: if (blocks == 1): self.headers['Content-Length'] = str(self.bytes_sent) return
'Make any necessary header changes or defaults Subclasses can extend this to add other defaults.'
def cleanup_headers(self):
if ('Content-Length' not in self.headers): self.set_content_length()
'\'start_response()\' callable as specified by PEP 3333'
def start_response(self, status, headers, exc_info=None):
if exc_info: try: if self.headers_sent: raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) finally: exc_info = None elif (self.headers is not None): raise AssertionError('Headers already set!') self.status = status self.header...
'Convert/check value type.'
def _convert_string_type(self, value, title):
if (type(value) is str): return value raise AssertionError('{0} must be of type str (got {1})'.format(title, repr(value)))
'Transmit version/status/date/server, via self._write()'
def send_preamble(self):
if self.origin_server: if self.client_is_modern(): self._write(('HTTP/%s %s\r\n' % (self.http_version, self.status)).encode('iso-8859-1')) if ('Date' not in self.headers): self._write(('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')) ...
'\'write()\' callable as specified by PEP 3333'
def write(self, data):
assert (type(data) is bytes), 'write() argument must be a bytes instance' if (not self.status): raise AssertionError('write() before start_response()') elif (not self.headers_sent): self.bytes_sent = len(data) self.send_headers() else: self.bytes_s...
'Platform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application\'s return iterable (\'self.result\') is an instance of \'self.wsgi_file_wrapper\'. This method should return a true value if it was able to actually transmit the ...
def sendfile(self):
return False
'Ensure headers and content have both been sent'
def finish_content(self):
if (not self.headers_sent): self.headers.setdefault('Content-Length', '0') self.send_headers() else: pass
'Close the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection.'
def close(self):
try: if hasattr(self.result, 'close'): self.result.close() finally: self.result = self.headers = self.status = self.environ = None self.bytes_sent = 0 self.headers_sent = False
'Transmit headers to the client, via self._write()'
def send_headers(self):
self.cleanup_headers() self.headers_sent = True if ((not self.origin_server) or self.client_is_modern()): self.send_preamble() self._write(bytes(self.headers))
'True if \'self.result\' is an instance of \'self.wsgi_file_wrapper\''
def result_is_file(self):
wrapper = self.wsgi_file_wrapper return ((wrapper is not None) and isinstance(self.result, wrapper))
'True if client can accept status and headers'
def client_is_modern(self):
return (self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9')
'Log the \'exc_info\' tuple in the server log Subclasses may override to retarget the output or change its format.'
def log_exception(self, exc_info):
try: from traceback import print_exception stderr = self.get_stderr() print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr) stderr.flush() finally: exc_info = None
'Log current error, and send error output to client if possible'
def handle_error(self):
self.log_exception(sys.exc_info()) if (not self.headers_sent): self.result = self.error_output(self.environ, self.start_response) self.finish_response()
'WSGI mini-app to create error output By default, this just uses the \'error_status\', \'error_headers\', and \'error_body\' attributes to generate an output page. It can be overridden in a subclass to dynamically generate diagnostics, choose an appropriate message for the user\'s preferred language, etc. Note, howeve...
def error_output(self, environ, start_response):
start_response(self.error_status, self.error_headers[:], sys.exc_info()) return [self.error_body]
'Override in subclass to buffer data for send to client It\'s okay if this method actually transmits the data; BaseHandler just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction.'
def _write(self, data):
raise NotImplementedError
'Override in subclass to force sending of recent \'_write()\' calls It\'s okay if this method is a no-op (i.e., if \'_write()\' actually sends the data.'
def _flush(self):
raise NotImplementedError
'Override in subclass to return suitable \'wsgi.input\''
def get_stdin(self):
raise NotImplementedError
'Override in subclass to return suitable \'wsgi.errors\''
def get_stderr(self):
raise NotImplementedError
'Override in subclass to insert CGI variables in \'self.environ\''
def add_cgi_vars(self):
raise NotImplementedError
'Override this method to support alternative .mo formats.'
def _parse(self, fp):
unpack = struct.unpack filename = getattr(fp, 'name', '') self._catalog = catalog = {} self.plural = (lambda n: int((n != 1))) buf = fp.read() buflen = len(buf) magic = unpack('<I', buf[:4])[0] if (magic == self.LE_MAGIC): (version, msgcount, masteridx, transidx) = unpack('<4I', ...
'This tests the improved concurrency with pysqlite 2.3.4. You needed to roll back con2 before you could commit con1.'
def CheckLocking(self):
if (sqlite.sqlite_version_info < (3, 2, 2)): return self.cur1.execute('create table test(i)') self.cur1.execute('insert into test(i) values (5)') try: self.cur2.execute('insert into test(i) values (5)') self.fail('should have raised an Op...
'Checks if cursors on the connection are set into a "reset" state when a rollback is done on the connection.'
def CheckRollbackCursorConsistency(self):
con = sqlite.connect(':memory:') cur = con.cursor() cur.execute('create table test(x)') cur.execute('insert into test(x) values (5)') cur.execute('select 1 union select 2 union select 3') con.rollback() try: cur.fetchall() self.fail('Int...
'Checks if the row object is iterable'
def CheckSqliteRowIter(self):
self.con.row_factory = sqlite.Row row = self.con.execute('select 1 as a, 2 as b').fetchone() for col in row: pass
'Checks if the row object can be converted to a tuple'
def CheckSqliteRowAsTuple(self):
self.con.row_factory = sqlite.Row row = self.con.execute('select 1 as a, 2 as b').fetchone() t = tuple(row) self.assertEqual(t, (row['a'], row['b']))
'Checks if the row object can be correctly converted to a dictionary'
def CheckSqliteRowAsDict(self):
self.con.row_factory = sqlite.Row row = self.con.execute('select 1 as a, 2 as b').fetchone() d = dict(row) self.assertEqual(d['a'], row['a']) self.assertEqual(d['b'], row['b'])
'Checks if the row object compares and hashes correctly'
def CheckSqliteRowHashCmp(self):
self.con.row_factory = sqlite.Row row_1 = self.con.execute('select 1 as a, 2 as b').fetchone() row_2 = self.con.execute('select 1 as a, 2 as b').fetchone() row_3 = self.con.execute('select 1 as a, 3 as b').fetchone() self.assertEqual(row_1, row_1...
'Checks if the row object can act like a sequence'
def CheckSqliteRowAsSequence(self):
self.con.row_factory = sqlite.Row row = self.con.execute('select 1 as a, 2 as b').fetchone() as_tuple = tuple(row) self.assertEqual(list(reversed(row)), list(reversed(as_tuple))) self.assertIsInstance(row, Sequence)
'A commit should also work when no changes were made to the database.'
def CheckCommitAfterNoChanges(self):
self.cx.commit() self.cx.commit()
'A rollback should also work when no changes were made to the database.'
def CheckRollbackAfterNoChanges(self):
self.cx.rollback() self.cx.rollback()
'pysqlite does not know the rowcount of SELECT statements, because we don\'t fetch all rows after executing the select statement. The rowcount has thus to be -1.'
def CheckRowcountSelect(self):
self.cu.execute('select 5 union select 6') self.assertEqual(self.cu.rowcount, (-1))
'Checks if fetchmany works with keyword arguments'
def CheckFetchmanyKwArg(self):
self.cu.execute('select name from test') res = self.cu.fetchmany(size=100) self.assertEqual(len(res), 1)
'Checks whether converter names are cut off at \'(\' characters'
def CheckNumber2(self):
self.cur.execute('insert into test(n2) values (5)') value = self.cur.execute('select n2 from test').fetchone()[0] self.assertEqual(type(value), float)
'Assures that the declared type is not used when PARSE_DECLTYPES is not set.'
def CheckDeclTypeNotUsed(self):
self.cur.execute('insert into test(x) values (?)', ('xxx',)) self.cur.execute('select x from test') val = self.cur.fetchone()[0] self.assertEqual(val, 'xxx')
'cursor.description should at least provide the column name(s), even if no row returned.'
def CheckCursorDescriptionNoRow(self):
self.cur.execute('select * from test where 0 = 1') self.assertEqual(self.cur.description[0][0], 'x')
'pysqlite would crash with older SQLite versions unless a workaround is implemented.'
def CheckWorkaroundForBuggySqliteTransferBindings(self):
self.con.execute('create table foo(bar)') self.con.execute('drop table foo') self.con.execute('create table foo(bar)')
'pysqlite used to segfault with SQLite versions 3.5.x. These return NULL for "no-operation" statements'
def CheckEmptyStatement(self):
self.con.execute('')
'pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling a statement. This test exhibits the problem.'
def CheckTypeMapUsage(self):
SELECT = 'select * from foo' con = sqlite.connect(':memory:', detect_types=sqlite.PARSE_DECLTYPES) con.execute('create table foo(bar timestamp)') con.execute('insert into foo(bar) values (?)', (datetime.datetime.now(),)) con.execute(SELECT) con.execute('drop tabl...
'See issue 3312.'
def CheckRegisterAdapter(self):
self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
'See issue 3312.'
def CheckSetIsolationLevel(self):
con = sqlite.connect(':memory:') setattr(con, 'isolation_level', '\xe9')
'Verifies that cursor methods check whether base class __init__ was called.'
def CheckCursorConstructorCallCheck(self):
class Cursor(sqlite.Cursor, ): def __init__(self, con): pass con = sqlite.connect(':memory:') cur = Cursor(con) try: cur.execute('select 4+5').fetchall() self.fail('should have raised ProgrammingError') except sqlite.ProgrammingError: pass ...
'The Python 3.0 port of the module didn\'t cope with values of subclasses of str.'
def CheckStrSubclass(self):
class MyStr(str, ): pass self.con.execute('select ?', (MyStr('abc'),))
'Verifies that connection methods check whether base class __init__ was called.'
def CheckConnectionConstructorCallCheck(self):
class Connection(sqlite.Connection, ): def __init__(self, name): pass con = Connection(':memory:') try: cur = con.cursor() self.fail('should have raised ProgrammingError') except sqlite.ProgrammingError: pass except: self.fail('should h...