def t(): if sys.version_info[0] == 2: # This test is disabled in Python2. There are too many subtle differences in the syntax ('str' has to be renamed 'unicode', # 'u' prefix is needed in front of string literals, etc), it's too hacky to preserve compatibility. # # In any case this test isn't to verify that the library works in Python2, it's too check that the README is up to date # with the code. So it doesn't matter. # return readme_file_path = path.join(path.dirname(__file__), '..', 'README.md') with open(readme_file_path, 'rb') as file_in: doctest_str = '\n\n'.join( re.findall( r'```python\s+(.+?)```', file_in.read().decode('UTF-8'), flags=re.S, ), ) assert doctest_str parser = DocTestParser() runner = DocTestRunner() runner.run( parser.get_doctest( doctest_str, dict(globals(), json=json, pickle=pickle), 'README.md', 'README.md', 0, ), ) assert runner.failures == 0
def _test_docstr(docstr, verbose=True, optionflags=0, raise_on_error=True): parser = DocTestParser() if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) test = parser.get_doctest(docstr, {}, __name__, __file__, 0) runner.run(test)
def test_readme_examples(): readme_file_path = path.join(path.dirname(__file__), '..', 'README.md') with open(readme_file_path, 'rt', encoding='UTF-8') as file_in: all_blocks = re.findall(r'```(\w+)\s+(.+?)```', file_in.read(), flags=re.S) with TemporaryDirectory() as temp_dir: chdir(temp_dir) for syntax, block in all_blocks: if syntax == 'console': command_match = re.search(r'^\$ (\w+) (.+)\s+', block) if not command_match: raise ValueError(block) print(command_match.group().rstrip()) command, args = command_match.groups() block = block[command_match.end():] if command == 'cat': # save the sample file to an actual file file_name = args with open(path.join(temp_dir, file_name), 'wt', encoding='UTF-8') as file_out: file_out.write(block) else: # check that the command output is as expcted actual_output = check_output( '%s %s' % (command, args), shell=True, cwd=temp_dir, encoding='UTF-8', env={ **environ, # `canif --help` reads this, and it can vary in the CI environment, so make it fixed 'COLUMNS': '71', }, ) print(actual_output) assert actual_output == block elif syntax == 'python': parser = DocTestParser() test = parser.get_doctest(block, {'canif': canif}, 'README.md', 'README.md', 0) runner = DocTestRunner() runner.run(test) assert not runner.failures
def _import_docstring(documenter): code_content = _import_docstring_code_content(documenter) if code_content: # noinspection PyBroadException try: code, content = code_content parser = DocTestParser() runner = DocTestRunner(verbose=0, optionflags=NORMALIZE_WHITESPACE | ELLIPSIS) glob = {} if documenter.modname: exec('from %s import *\n' % documenter.modname, glob) tests = parser.get_doctest(code, glob, '', '', 0) runner.run(tests, clear_globs=False) documenter.object = tests.globs[documenter.name] documenter.code = content documenter.is_doctest = True return True except Exception: pass
def _import_docstring(documenter): code_content = _import_docstring_code_content(documenter) if code_content: # noinspection PyBroadException try: code, content = code_content parser = DocTestParser() runner = DocTestRunner(verbose=0, optionflags=NORMALIZE_WHITESPACE | ELLIPSIS) glob = {} if documenter.modname: exec('from %s import *\n' % documenter.modname, glob) tests = parser.get_doctest(code, glob, '', '', 0) runner.run(tests, clear_globs=False) documenter.object = tests.globs[documenter.name] documenter.code = content documenter.is_doctest = True return True except Exception: pass
def _copy_doctests( src_path: pathlib.Path, dst_f: TextIO, dp: doctest.DocTestParser = doctest.DocTestParser(), ): with src_path.open() as src_f: src_p = str(src_path.resolve()) dt = dp.get_doctest(src_f.read(), {"__name__": "__main__"}, src_p, src_p, 0) cur_lineno = 0 if not dt.examples: logging.debug("no doctests found in %s", src_path) for example in dt.examples: assert cur_lineno <= example.lineno while cur_lineno < example.lineno: dst_f.write("# skipped line {}\n".format(cur_lineno)) cur_lineno += 1 dst_f.write(example.source) cur_lineno += sum(1 for c in example.source if c == "\n")
def _import_docstring(documenter): if getattr(documenter.directive, 'content', None): # noinspection PyBroadException try: import textwrap content = documenter.directive.content def get_code(source, c=''): s = "\n%s" % c return textwrap.dedent(s.join(map(str, source))) is_doctest = contains_doctest(get_code(content)) offset = documenter.directive.content_offset if is_doctest: parent, parent_offset = get_grandfather_content(content) parent = parent[:offset + len(content) - parent_offset] code = get_code(parent) else: code = get_code(content, '>>> ') parser = DocTestParser() runner = DocTestRunner(verbose=0, optionflags=NORMALIZE_WHITESPACE | ELLIPSIS) glob = {} exec('import %s as mdl\n' % documenter.modname, glob) glob = glob['mdl'].__dict__ tests = parser.get_doctest(code, glob, '', '', 0) runner.run(tests, clear_globs=False) documenter.object = tests.globs[documenter.name] documenter.code = content documenter.is_doctest = True return True except: return False
def get_doc_test_cases_from_string( self, string, name = '<string>', filename = '<string>', globs = None, ): if globs is None: globs = {} # Make sure __name__ == '__main__' checks fail: globs = dict(globs) globs['__name__'] = None parser = DocTestParser() test = parser.get_doctest( string, globs = globs, name = name, filename = filename, lineno = 0, ) test_case = self.make_doc_test_case(test) return [test_case]