def collect_doctest(object, vars, name): doctest_suite = doctest.DocTestSuite() test_case = doctest.DocTestParser().get_doctest(object, vars, name, name, 1) test_case.examples and doctest_suite.addTest( doctest.DocTestCase(test_case, doctest.ELLIPSIS)) test_case = InlineDoctestParser().get_doctest(object, vars, name, name, 1) test_case.examples and doctest_suite.addTest( doctest.DocTestCase(test_case, checker=NullOutputCheck)) if doctest_suite._tests: return doctest_suite
def get_tests(): import cuddlefish import cuddlefish.tests tests = [] packages = [cuddlefish, cuddlefish.tests] for package in packages: path = os.path.abspath(package.__path__[0]) pynames = glob.glob(os.path.join(path, '*.py')) for filename in pynames: basename = os.path.basename(filename) module_name = os.path.splitext(basename)[0] full_name = "%s.%s" % (package.__name__, module_name) module = __import__(full_name, fromlist=[package.__name__]) loader = unittest.TestLoader() suite = loader.loadTestsFromModule(module) for test in suite: tests.append(test) finder = doctest.DocTestFinder() doctests = finder.find(module) for test in doctests: if len(test.examples) > 0: tests.append(doctest.DocTestCase(test)) return tests
def test_doctest(self): """ If we parse a doctest, we get all the fields we need. """ test = """ >>> f() 42 """ def f(): return 42 parser = doctest.DocTestParser() dt = parser.get_doctest(test, {"f": f}, "doctest.name", "somefile.py", 20) dt.__module__ = "somefile" p = proto_test(doctest.DocTestCase(dt)) # short description self.assertEqual(p.getDescription(2), "doctest.name") # long description description = p.getDescription(3) self.assertIn("doctest.name", description) self.assertIn("somefile.py", description) self.assertIn("20", description) # dotted name self.assertEqual(p.dotted_name, "doctest.name")
def make_doctest(filename): filename = _get_caller_relative_path(filename) doctests = read_file(filename) doctests = _fix_unicode(r'\1\2', doctests) doctests = _fix_exceptions(r'\1 as \2', doctests) return doctest.DocTestCase( doctest_parser.get_doctest( doctests, {}, os.path.basename(filename), filename, 0))
def make_doctest(filename): filename = _get_caller_relative_path(filename) doctests = open(filename).read() doctests = _fix_traceback(r'\1\2', doctests) doctests = _fix_exceptions(r'\1, \2', doctests) doctests = _fix_bytes(r'\1\2', doctests) return doctest.DocTestCase( doctest_parser.get_doctest( doctests, {}, os.path.basename(filename), filename, 0))
def get_test_str(object: str): vars = get_ipython().user_ns name = get_ipython().user_module.__name__ doctest_suite = doctest.DocTestSuite() test_case = doctest.DocTestParser().get_doctest(object, vars, name, name, 1) test_case.examples and doctest_suite.addTest( doctest.DocTestCase(test_case, doctest.ELLIPSIS)) if doctest_suite._tests: return doctest_suite
def addDocAttrTestsToSuite(suite, moduleVariableLists, outerFilename=None, globs=False, optionflags=( doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE )): ''' takes a suite, such as a doctest.DocTestSuite and the list of variables in a module and adds from those classes that have a _DOC_ATTR dictionary (which documents the properties in the class) any doctests to the suite. >>> import doctest >>> s1 = doctest.DocTestSuite(chord) >>> s1TestsBefore = len(s1._tests) >>> allLocals = [getattr(chord, x) for x in dir(chord)] >>> test.testRunner.addDocAttrTestsToSuite(s1, allLocals) >>> s1TestsAfter = len(s1._tests) >>> s1TestsAfter - s1TestsBefore 1 >>> t = s1._tests[-1] >>> t isRest () >>> 'hi' 'hi' ''' dtp = doctest.DocTestParser() if globs is False: globs = __import__(defaultImports[0]).__dict__.copy() elif globs is None: globs = {} for lvk in moduleVariableLists: if not (inspect.isclass(lvk)): continue docattr = getattr(lvk, '_DOC_ATTR', None) if docattr is None: continue for dockey in docattr: documentation = docattr[dockey] # print(documentation) dt = dtp.get_doctest(documentation, globs, dockey, outerFilename, 0) if not dt.examples: continue dtc = doctest.DocTestCase(dt, optionflags=optionflags, ) # print(dtc) suite.addTest(dtc)
def get_tests_in_module(module): tests = [] loader = unittest.TestLoader() suite = loader.loadTestsFromModule(module) for test in suite: tests.append(test) optionflags = (doctest.NORMALIZE_WHITESPACE | doctest.REPORT_UDIFF) finder = doctest.DocTestFinder() doctests = finder.find(module, extraglobs=DOCTEST_EXTRA_GLOBS) for test in doctests: if len(test.examples) > 0: tests.append(doctest.DocTestCase(test, optionflags=optionflags)) return tests
def _run_test(self, test, globs, name, path, optionflags, checker, testname='self', lineno=0): globs.update(getattr(self, 'globs', ())) globs[testname] = self optionflags |= doctest.IGNORE_EXCEPTION_DETAIL doctest.DocTestCase( _parser.get_doctest(test, globs, name, path, lineno), optionflags=optionflags, checker=checker, ).runTest()
def make_suite(): # pragma: no cover from calmjs.parse.lexers import es5 as es5lexer from calmjs.parse import walkers from calmjs.parse import sourcemap def open(p, flag='r'): result = StringIO(examples[p] if flag == 'r' else '') result.name = p return result parser = doctest.DocTestParser() optflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS dist = get_distribution('calmjs.parse') if dist: if dist.has_metadata('PKG-INFO'): pkgdesc = dist.get_metadata('PKG-INFO').replace('\r', '') elif dist.has_metadata('METADATA'): pkgdesc = dist.get_metadata('METADATA').replace('\r', '') else: pkgdesc = '' pkgdesc_tests = [ t for t in parser.parse(pkgdesc) if isinstance(t, doctest.Example) ] test_loader = unittest.TestLoader() test_suite = test_loader.discover('calmjs.parse.tests', pattern='test_*.py', top_level_dir=dirname(__file__)) test_suite.addTest(doctest.DocTestSuite(es5lexer, optionflags=optflags)) test_suite.addTest(doctest.DocTestSuite(walkers, optionflags=optflags)) test_suite.addTest(doctest.DocTestSuite(sourcemap, optionflags=optflags)) test_suite.addTest( doctest.DocTestCase( # skipping all the error case tests which should all be in the # troubleshooting section at the end; bump the index whenever # more failure examples are added. # also note that line number is unknown, as PKG_INFO has headers # and also the counter is somehow inaccurate in this case. doctest.DocTest(pkgdesc_tests[:-1], {'open': open}, 'PKG_INFO', 'README.rst', None, pkgdesc), optionflags=optflags, )) return test_suite
def get_tests(): import cuddlefish import cuddlefish.tests tests = [] packages = [cuddlefish, cuddlefish.tests] for package in packages: path = os.path.abspath(package.__path__[0]) pynames = glob.glob(os.path.join(path, '*.py')) for filename in pynames: basename = os.path.basename(filename) module_name = os.path.splitext(basename)[0] full_name = "%s.%s" % (package.__name__, module_name) module = __import__(full_name, fromlist=[package.__name__]) loader = unittest.TestLoader() suite = loader.loadTestsFromModule(module) for test in suite: tests.append(test) finder = doctest.DocTestFinder() doctests = finder.find(module) for test in doctests: if len(test.examples) > 0: tests.append(doctest.DocTestCase(test)) md_dir = os.path.join(env_root, 'dev-guide') doctest_opts = (doctest.NORMALIZE_WHITESPACE | doctest.REPORT_UDIFF) for dirpath, dirnames, filenames in os.walk(md_dir): for filename in filenames: if filename.endswith('.md'): absname = os.path.join(dirpath, filename) tests.append(doctest.DocFileTest( absname, module_relative=False, optionflags=doctest_opts )) return tests
def __test_module_no_links(test_module, modules_to_ignore, output_file=sys.stdout, verbose=False): result = TestResult() if test_module.__name__ in modules_to_ignore: return result result.modules_tested.add(test_module.__name__) modules_to_ignore.add(test_module.__name__) unittest_result = _UnitTestResult(output_file, verbose, result, test_module) doc_test_finder = doctest.DocTestFinder() try: suite = unittest.TestLoader().loadTestsFromModule(test_module) doc_tests = doc_test_finder.find(test_module) for test in doc_tests: while test.examples: suite.addTest(doctest.DocTestCase(test)) suite(unittest_result) run_count = unittest_result.testsRun skipped_count = len(unittest_result.skipped) total_count = run_count + skipped_count while total_count == 0 and verbose and output_file: if output_file is sys.stdout: ConsoleColor.change_color(ConsoleColor.DARK_GRAY) output_file.write('{0} :: No tests found\n'.format( test_module.__name__)) except: class ErrorMessageTest(unittest.TestCase): __qualname__ = '__test_module_no_links.<locals>.ErrorMessageTest' def __repr__(self): return 'Could not complete test suite.' __str__ = __repr__ unittest_result.addError(ErrorMessageTest(), sys.exc_info()) return result
def add_doc_attr_tests_to_suite(suite, moduleVariableLists, outerFilename=None, globs=False, optionflags=(doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)): ''' takes a suite, such as a doctest.DocTestSuite and the list of variables in a module and adds from those classes that have a _DOC_ATTR dictionary (which documents the properties in the class) any doctests to the suite. ''' dtp = doctest.DocTestParser() if globs is False: globs = __import__(common.source_package_name()).__dict__.copy() elif globs is None: globs = {} for lvk in moduleVariableLists: if not (inspect.isclass(lvk)): continue docattr = getattr(lvk, '_DOC_ATTR', None) if docattr is None: continue for dockey in docattr: documentation = docattr[dockey] #print(documentation) dt = dtp.get_doctest(documentation, globs, dockey, outerFilename, 0) if not dt.examples: continue dtc = doctest.DocTestCase( dt, optionflags=optionflags, ) #print(dtc) suite.addTest(dtc)