def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(ngsutils.support.stats)) return tests
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite()) return tests
def get_suite(): """Get unittest suite for this module""" import doctest, sys return doctest.DocTestSuite(sys.modules[__name__])
def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite()) return tests
def test_suite(): return unittest.TestSuite((doctest.DocTestSuite(setUp=setUp, tearDown=tearDown), ))
def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(TemplateLoader.__module__)) suite.addTest(unittest.makeSuite(TemplateLoaderTestCase, 'test')) return suite
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(ObjectFactoryMixin)) return tests
def test_suite(): optionflags = (doctest.ELLIPSIS | doctest.REPORT_NDIFF | doctest.NORMALIZE_WHITESPACE) return unittest.TestSuite([ doctest.DocTestSuite(optionflags=optionflags, checker=checker), ])
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(rdSubstructLibrary)) return tests
def test_suite(): optionflags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_ONLY_FIRST_FAILURE) return doctest.DocTestSuite(setUp=setUp, tearDown=tearDown, optionflags=optionflags)
def doctests(): # type: () -> unittest.TestSuite import doctest return doctest.DocTestSuite()
def load_tests(*args): from test import test_pdb suites = [unittest.makeSuite(PdbTestCase), doctest.DocTestSuite(test_pdb)] return unittest.TestSuite(suites)
The config file's encoding, defaults to :data:`default_encoding`. Examples -------- >>> get_val("junk") is None True >>> set_val("junk", "random") >>> get_val("junk") u'random' >>> set_val("junk", None) >>> get_val("junk") is None True """ if os.path.exists(path()): if encoding == None: encoding = default_encoding config = ConfigParser.ConfigParser() f = codecs.open(path(), 'r', encoding) config.readfp(f, path()) f.close() try: return config.get(section, name) except ConfigParser.NoOptionError: return default else: return default if libbe.TESTING == True: suite = doctest.DocTestSuite()
def run_docstring_tests(module): runner = TextTestRunner() s = runner.run(doctest.DocTestSuite(module)) assert 0 == len(s.failures)
for path, module in walk_modules(): add_module(module, path) add_module('setup', 'setup.py') if not modules: sys.exit('No modules found matching %s' % ' '.join(allowed_modules)) suite = unittest.TestSuite() tests_count = 0 modules_count = 0 for m, path in sorted(modules): with open(path, 'r') as f: contents = f.read() if re.search(r'^\s*>>> ', contents, re.M): try: s = doctest.DocTestSuite(m, extraglobs=globs) test_count = len(s._tests) # pylint: disable=W0212 print('%s (from %s): %s tests' % (m, path, test_count)) suite.addTest(s) modules_count += 1 tests_count += test_count except Exception: traceback.print_exc() sys.stderr.write('Failed to process %s\n\n' % path) print('Total: %s tests in %s modules' % (tests_count, modules_count)) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite) finally: os.chdir(cwd)
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(encrypt)) tests.addTests(doctest.DocTestSuite(game)) return tests
def test_suite(): suite = unittest.TestSuite() suite.addTest( doctest.DocTestSuite('Products.eXtremeManagement.browser.gantt', optionflags=OPTIONFLAGS)) return suite
import doctest import unittest import os import vcf2hl7v2 from os.path import join, dirname import shutil import logging import filecmp suite = doctest.DocTestSuite(vcf2hl7v2) class TestTemporary(unittest.TestCase): @classmethod def setUpClass(self): self.TEST_RESULT_DIR = os.path.join( os.path.dirname(__file__), 'output') if os.path.exists(self.TEST_RESULT_DIR): shutil.rmtree(self.TEST_RESULT_DIR) os.mkdir(self.TEST_RESULT_DIR) @classmethod def tearDownClass(self): shutil.rmtree(self.TEST_RESULT_DIR) def test_NB6TK328(self): o_vcf_2_hl7v2 = vcf2hl7v2.Converter( vcf_filename=os.path.join( os.path.dirname(__file__), 'NB6TK328_filtered.vcf' ),
if os.path.exists(self.rustc_stamp_path): os.unlink(self.rustc_stamp_path) self.assertTrue(self.build.program_out_of_date(self.rustc_stamp_path)) def test_dates_are_different(self): """Return True when the dates are different""" with open(self.rustc_stamp_path, "w") as rustc_stamp: rustc_stamp.write("2017-06-14") self.assertTrue(self.build.program_out_of_date(self.rustc_stamp_path)) def test_same_dates(self): """Return False both dates match""" with open(self.rustc_stamp_path, "w") as rustc_stamp: rustc_stamp.write("2017-06-15") self.assertFalse(self.build.program_out_of_date(self.rustc_stamp_path)) if __name__ == '__main__': SUITE = unittest.TestSuite() TEST_LOADER = unittest.TestLoader() SUITE.addTest(doctest.DocTestSuite(bootstrap)) SUITE.addTests([ TEST_LOADER.loadTestsFromTestCase(Stage0DataTestCase), TEST_LOADER.loadTestsFromTestCase(VerifyTestCase), TEST_LOADER.loadTestsFromTestCase(ProgramOutOfDate) ]) RUNNER = unittest.TextTestRunner(stream=sys.stdout, verbosity=2) result = RUNNER.run(SUITE) sys.exit(0 if result.wasSuccessful() else 1)
def load_tests(loader, tests, ignore): tests.addTests( doctest.DocTestSuite('plainbox.impl.xparsers', optionflags=doctest.REPORT_NDIFF)) return tests
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(representation)) return tests
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(preprocessing)) return tests
def test_suite(): return unittest.TestSuite( [doctest.DocTestSuite(module=module) for module in modules])
def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(mofile, optionflags=doctest.ELLIPSIS)) suite.addTest(unittest.makeSuite(ReadMoTestCase)) suite.addTest(unittest.makeSuite(WriteMoTestCase)) return suite
def suitefn(): suite = unittest.TestSuite() suite.addTests(doctest.DocTestSuite(diskarray)) suite.addTests(doctest.DocTestSuite(vararray)) return suite
def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(solists.move_to_front_list)) return tests
def make_test_suite(): """Load unittests placed in here and below, then return a TestSuite object of those.""" path = os.path.abspath(__file__).rsplit(os.sep + 'tests', 1)[0] # path to actual code that we want to test sys.path.append('../') sys.path.append('../../') top_testdir = os.path.join(path, 'tests') # 'tests', 'unittests' testdirs = getSubDirectories(top_testdir) # testdirs.append('./') print "scan directories: ", testdirs # Initialize the testsuite to add to suite = TestSuite() optionflags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE for testdir in testdirs: # All unittest modules have to start with 'test_' and have to be, of # course, python files module_names = [ f[:-3] for f in os.listdir(testdir) if f.startswith('test_') and f.endswith('.py') ] if not module_names: logging.info('No tests found in %s' % testdir) continue # "Magically" import the tests package and its test-modules that we've # found sub_path = os.path.relpath(testdir, top_testdir).split(os.sep) test_package_path = '.'.join(sub_path) test_package = __import__(test_package_path, fromlist=module_names) # Put the test modules in a list that can be passed to the testsuite modules = (getattr(test_package, n) for n in module_names) modules = [(m, missingDependencies(m)) for m in modules] untests = [(m, md) for m, md in modules if md] modules = [m for m, md in modules if not md] # Print out modules that are missing dependencies for module, miss_dep in untests: # Mr Dep is not around, though logging.warning('Module %s is missing dependencies: %s' % (module.__name__, ', '.join(miss_dep))) # Print out a list of tests that are found for m in modules: logging.info('Tests found: %s' % m.__name__) # Build up the testsuite suite.addTests([TestLoader().loadTestsFromModule(m) for m in modules]) # Add doctests from the unittest modules to the suite for mod in modules: try: suite.addTest( doctest.DocTestSuite(mod, optionflags=optionflags)) except ValueError: # No tests found. pass return suite
def runTest(self, name): from Bio import MissingExternalDependencyError result = self._makeResult() output = StringIO() # Restore the language and thus default encoding (in case a prior # test changed this, e.g. to help with detecting command line tools) global SYSTEM_LANG os.environ['LANG'] = SYSTEM_LANG # Always run tests from the Tests/ folder where run_tests.py # should be located (as we assume this with relative paths etc) os.chdir(self.testdir) try: stdout = sys.stdout sys.stdout = output if name.startswith("test_"): sys.stderr.write("%s ... " % name) # It's either a unittest or a print-and-compare test loader = unittest.TestLoader() suite = loader.loadTestsFromName(name) if hasattr(loader, "errors") and loader.errors: # New in Python 3.5, don't always get an exception anymore # Instead this is a list of error messages as strings for msg in loader.errors: if "Bio.MissingExternalDependencyError: " in msg or \ "Bio.MissingPythonDependencyError: " in msg: # Remove the traceback etc msg = msg[msg.find("Bio.Missing"):] msg = msg[msg.find("Error: "):] sys.stderr.write("skipping. %s\n" % msg) return True # Looks like a real failure sys.stderr.write("loading tests failed:\n") for msg in loader.errors: sys.stderr.write("%s\n" % msg) return False if suite.countTestCases() == 0: # This is a print-and-compare test instead of a # unittest-type test. test = ComparisonTestCase(name, output) suite = unittest.TestSuite([test]) else: # It's a doc test sys.stderr.write("%s docstring test ... " % name) module = __import__(name, fromlist=name.split(".")) suite = doctest.DocTestSuite(module, optionflags=doctest.ELLIPSIS) del module suite.run(result) if self.testdir != os.path.abspath("."): sys.stderr.write("FAIL\n") result.stream.write(result.separator1 + "\n") result.stream.write("ERROR: %s\n" % name) result.stream.write(result.separator2 + "\n") result.stream.write("Current directory changed\n") result.stream.write("Was: %s\n" % self.testdir) result.stream.write("Now: %s\n" % os.path.abspath(".")) os.chdir(self.testdir) if not result.wasSuccessful(): result.printErrors() return False elif result.wasSuccessful(): sys.stderr.write("ok\n") return True else: sys.stderr.write("FAIL\n") result.printErrors() return False except MissingExternalDependencyError as msg: # Seems this isn't always triggered on Python 3.5, # exception messages can be in loader.errors instead. sys.stderr.write("skipping. %s\n" % msg) return True except Exception as msg: # This happened during the import sys.stderr.write("ERROR\n") result.stream.write(result.separator1 + "\n") result.stream.write("ERROR: %s\n" % name) result.stream.write(result.separator2 + "\n") result.stream.write(traceback.format_exc()) return False except KeyboardInterrupt as err: # Want to allow this, and abort the test # (see below for special case) raise err except: # This happens in Jython with java.lang.ClassFormatError: # Invalid method Code length ... sys.stderr.write("ERROR\n") result.stream.write(result.separator1 + "\n") result.stream.write("ERROR: %s\n" % name) result.stream.write(result.separator2 + "\n") result.stream.write(traceback.format_exc()) return False finally: sys.stdout = stdout # Running under PyPy we were leaking file handles... gc.collect()
def doctests(): import doctest return doctest.DocTestSuite()
def mainTest(*testClasses, **kwargs): ''' Takes as its arguments modules (or a string 'noDocTest' or 'verbose') and runs all of these modules through a unittest suite Unless 'noDocTest' is passed as a module, a docTest is also performed on `__main__`, hence the name "mainTest". If 'moduleRelative' (a string) is passed as a module, then global variables are preserved. Run example (put at end of your modules): :: import unittest class Test(unittest.TestCase): def testHello(self): hello = "Hello" self.assertEqual("Hello", hello) import music21 if __name__ == '__main__': music21.mainTest(Test) This module tries to fix up some differences between python2 and python3 so that the same doctests can work. ''' runAllTests = True # default -- is fail fast. failFast = bool(kwargs.get('failFast', True)) if failFast: optionflags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_ONLY_FIRST_FAILURE) else: optionflags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) globs = None if ('noDocTest' in testClasses or 'noDocTest' in sys.argv or 'nodoctest' in sys.argv or bool(kwargs.get('noDocTest', False))): skipDoctest = True else: skipDoctest = False # start with doc tests, then add unit tests if skipDoctest: # create a test suite for storage s1 = unittest.TestSuite() else: # create test suite derived from doc tests # here we use '__main__' instead of a module if ('moduleRelative' in testClasses or 'moduleRelative' in sys.argv or bool(kwargs.get('moduleRelative', False))): pass else: for di in defaultImports: globs = __import__(di).__dict__.copy() if ('importPlusRelative' in testClasses or 'importPlusRelative' in sys.argv or bool(kwargs.get('importPlusRelative', False))): globs.update(globals()) try: s1 = doctest.DocTestSuite( '__main__', globs=globs, optionflags=optionflags, ) except ValueError as ve: # no docstrings print("Problem in docstrings [usually a missing r value before " + "the quotes:] {0}".format(str(ve))) s1 = unittest.TestSuite() verbosity = 1 if ('verbose' in testClasses or 'verbose' in sys.argv or bool(kwargs.get('verbose', False))): verbosity = 2 # this seems to hide most display displayNames = False if ('list' in sys.argv or 'display' in sys.argv or bool(kwargs.get('display', False)) or bool(kwargs.get('list', False))): displayNames = True runAllTests = False runThisTest = None if len(sys.argv) == 2: arg = sys.argv[1].lower() if arg not in ('list', 'display', 'verbose', 'nodoctest'): # run a test directly named in this module runThisTest = sys.argv[1] if bool(kwargs.get('runTest', False)): runThisTest = kwargs.get('runTest', False) # -f, --failfast if ('onlyDocTest' in sys.argv or 'onlyDocTest' in testClasses or bool(kwargs.get('onlyDocTest', False))): testClasses = [] # remove cases for t in testClasses: if not isinstance(t, str): if displayNames is True: for tName in unittest.defaultTestLoader.getTestCaseNames(t): print('Unit Test Method: %s' % tName) if runThisTest is not None: tObj = t() # call class # search all names for case-insensitive match for name in dir(tObj): if (name.lower() == runThisTest.lower() or name.lower() == ('test' + runThisTest.lower()) or name.lower() == ('xtest' + runThisTest.lower())): runThisTest = name break if hasattr(tObj, runThisTest): print('Running Named Test Method: %s' % runThisTest) tObj.setUp() getattr(tObj, runThisTest)() runAllTests = False break else: print( 'Could not find named test method: %s, running all tests' % runThisTest) # normally operation collects all tests s2 = unittest.defaultTestLoader.loadTestsFromTestCase(t) s1.addTests(s2) ### Add _DOC_ATTR tests... if not skipDoctest: stacks = inspect.stack() if len(stacks) > 1: outerFrameTuple = stacks[1] else: outerFrameTuple = stacks[0] outerFrame = outerFrameTuple[0] outerFilename = outerFrameTuple[1] localVariables = list(outerFrame.f_locals.values()) addDocAttrTestsToSuite(s1, localVariables, outerFilename, globs, optionflags) if runAllTests is True: fixDoctests(s1) runner = unittest.TextTestRunner() runner.verbosity = verbosity unused_testResult = runner.run(s1)