def num_even_digits(n): """ >>>num_even_digits(123456) 3 >>>num_even_digits(2468) 4 >>>num_even_digits(1357) 0 >>>num_even_digits(2) 1 >>>num_even_digits(20) 2 """ n=str(n) x=0 for i in n: i=int(i) if i%2==0: x+=1 else: pass return x doctest.testmod()
def _test(chat=None): if chat: print("Unit tests for gmpy 1.15 (threading)") print(" running on Python", sys.version) print() if _g.gmp_version(): print("Testing gmpy %s (GMP %s) with default caching (%s, %s)" % ( (_g.version(), _g.gmp_version(), _g.get_cache()[0], _g.get_cache()[1]))) else: print("Testing gmpy %s (MPIR %s) with default caching (%s, %s)" % ( (_g.version(), _g.mpir_version(), _g.get_cache()[0], _g.get_cache()[1]))) thismod = sys.modules.get(__name__) doctest.testmod(thismod, report=0) if chat: print("Repeating tests, with caching disabled") _g.set_cache(0,128) sav = sys.stdout class _Dummy: def write(self,*whatever): pass try: sys.stdout = _Dummy() doctest.testmod(thismod, report=0) finally: sys.stdout = sav if chat: print() print("Overall results for thr:") return doctest.master.summarize(chat)
def test_europe_extract(*args): """Test the extraction of European individuals on Chromosome 1 from a sample file Note: use nose to run tests. """ # print 'args ', args # logging.basicConfig(level = logging.DEBUG) import doctest doctest.testmod() basedir = '/home/gioby/Data/HGDP/' # testgenotypefile = [basedir + 'Test/chr22_100.geno', ] testgenotypefile = basedir + 'Test/chr1_30.geno' # [samplesfilter, genotypes_files, outputfile] = get_parameters() TODO: don't call get_parameters twice continent = 'Europe' samplesfilepath = basedir + '/Annotations/samples_subset.csv' samples_filter = filter_samples_by_continent(samplesfilepath, continent) samples = getFilteredGenotypes(samples_filter, testgenotypefile) outputfile = basedir + 'Results/test.europe' # logging.debug(pformat(samples_filter)) printGenotypes(samples, outputfile) sys.exit()
def main(): parser = argparse.ArgumentParser() # parameter for the AFL. parser.add_argument( 'AFL', help='Application File Locator value (coded in hexadecimal).' ) # doctest flag. parser.add_argument( '-t', '--test', help='run the doctests and exit.', action='store_true' ) args = parser.parse_args() test = args.test afl = args.AFL if test: doctest.testmod() return valid_in = validate(afl) if not valid_in: util.die("A valid AFL value should be a multiple of 4 Bytes.") print human(afl) return
def test(): # sendFusiRequest([ "GGGAGGCTGCTTTACCCGCTGTGGGGGCGC", "GGGAGGCTGCTTTACCCGCTGTGGGGGCGC"]) # sys.exit(1) # global binDir import doctest doctest.testmod()
def test(): import doctest doctest.testmod(verbose=True) unittests() sys.exit(0)
def _test(): """Run the Bio.SeqIO module's doctests. This will try and locate the unit tests directory, and run the doctests from there in order that the relative paths used in the examples work. """ import doctest import os if os.path.isdir(os.path.join("..", "..", "Tests", "Ace")): print "Runing doctests..." cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("..", "..", "Tests")) assert os.path.isfile("Ace/consed_sample.ace") doctest.testmod() os.chdir(cur_dir) del cur_dir print "Done" elif os.path.isdir(os.path.join("Tests", "Ace")): print "Runing doctests..." cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir print "Done"
def _test(): """Start a doctest run on this module""" import doctest import bb from bb import data bb.msg.set_debug_level(0) doctest.testmod(data)
def _test(): import doctest start_suppress = np.get_printoptions()["suppress"] np.set_printoptions(suppress=True) doctest.testmod() np.set_printoptions(suppress=start_suppress)
def _test(): """Run the module's doctests (PRIVATE).""" print("Running XXmotif doctests...") import doctest doctest.testmod() print("Done")
def test(): """ Main testrunnner >>> import util >>> >>> text = ''' ... A = B = True ... 1: A* = B ... 2: B* = A and B ... C* = not C ... E = False ... F = (1, 2, 3) ... ''' >>> >>> lexer = Lexer() >>> tokens = lexer.tokenize_text( text ) >>> tokens[0] [LexToken(ID,'A',1,0), LexToken(EQUAL,'=',1,2), LexToken(ID,'B',1,4), LexToken(EQUAL,'=',1,6), LexToken(STATE,'True',1,8)] >>> tokens[1] [LexToken(LABEL,1,1,0), LexToken(ID,'A',1,3), LexToken(ASSIGN,'*',1,4), LexToken(EQUAL,'=',1,6), LexToken(ID,'B',1,8)] >>> tokens[2] [LexToken(LABEL,2,1,0), LexToken(ID,'B',1,3), LexToken(ASSIGN,'*',1,4), LexToken(EQUAL,'=',1,6), LexToken(ID,'A',1,8), LexToken(AND,'and',1,10), LexToken(ID,'B',1,14)] >>> tokens[3] [LexToken(ID,'C',1,0), LexToken(ASSIGN,'*',1,1), LexToken(EQUAL,'=',1,3), LexToken(NOT,'not',1,5), LexToken(ID,'C',1,9)] >>> >>> get_nodes( tokens ) set(['A', 'C', 'B', 'E', 'F']) """ # runs the local suite import doctest doctest.testmod( optionflags=doctest.ELLIPSIS + doctest.NORMALIZE_WHITESPACE )
def _main(): """ Parse options and run checks on Python source. """ options, args = process_options() if options.doctest: import doctest doctest.testmod(verbose=options.verbose) selftest() start_time = time.time() for path in args: if os.path.isdir(path): input_dir(path) else: input_file(path) elapsed = time.time() - start_time if options.statistics: print_statistics() if options.benchmark: print_benchmark(elapsed) if options.count: count = get_count() if count: sys.stderr.write(str(count) + '\n') sys.exit(1)
def main(argc, argv): if (argc > 1): logging.basicConfig(format='%(message)s') log.setLevel(logging.DEBUG) if (argv[1] == '--test'): import doctest doctest.testmod(optionflags = doctest.NORMALIZE_WHITESPACE + doctest.ELLIPSIS) else: try: infolog = open(argv[1], 'r') dbgsymdir = ((argc >= 3) and argv[2]) or None ## config, branch, githash = detect_version_details(infolog.read()) stacktrace = translate_stacktrace(infolog.read(), dbgsymdir) for address in stacktrace: print(address) except FatalError: ## redundant ## print("FatalError:\n%s" % traceback.format_exc()) return except IOError: print("IOError: file \"%s\" not readable" % argv[1]) return else: run_xmlrpc_server()
def main_coverage(TESTS): modulenames = MODULE_NAMES coverage.erase() coverage.start() coverage.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') modules = [] for modulename in modulenames: print modulenames mod = my_import(modulename) modules.append(mod) if 'unittest' in TESTS: print "***** Unittest *****" test_args = {'verbosity': 1} suite = unittest.TestLoader().loadTestsFromNames(TEST_NAMES) unittest.TextTestRunner(**test_args).run(suite) if 'doctest' in TESTS: t0 = time.time() print "\n***** Doctest *****" for mod in modules: doctest.testmod(mod, verbose=VERBOSE) td = time.time() - t0 print " Tests took %.3f seconds" % (td, ) print "\n***** Coverage Python *****" coverage.stop() coverage.report(modules, ignore_errors=1, show_missing=1) coverage.erase()
def main(): import doctest doctest.testmod() # ... # ... x_blue = np.random.normal(loc=0, size=num_samples) y_blue = np.random.normal(loc=0, scale=0.5, size=num_samples) x_red = np.random.normal(loc=2, size=num_samples) y_red = np.random.normal(loc=2, scale=0.5, size=num_samples) data = list(zip(zip(x_blue, y_blue), [labels[0]] * num_samples)) data += zip(zip(x_red, y_red), [labels[1]] * num_samples) np.random.shuffle(data) # ... train_set = data[:train_size] test_set = data[train_size:] # Matplotlib craziness to be able to update a plot plt.ion() fig = plt.figure() subplot = fig.add_subplot(1,1,1, xlim=(-5,5), ylim=(-5,5)) subplot.grid() subplot.plot(x_blue, y_blue, linestyle='None', marker='o', color='blue') subplot.plot(x_red, y_red, linestyle='None', marker='o', color='red') p = Perceptron(2) p.train(train_set, test_set, subplot=subplot, fig=fig)
def test(): r""" Run all the doctests available. """ import doctest import pylsmlib doctest.testmod(pylsmlib)
def run(self): ''' Finds all the tests files in tests/, and run doctest on them. ''' pymods = [] pyxmods = [] for root, dirs, files in os.walk('arboris'): for file in files: package = '.'.join(root.split(sep)) if file.endswith('.py') and file != '__init__.py': pymods.append('.'.join([package, splitext(file)[0]])) elif file.endswith('.so'): pyxmods.append('.'.join([package, splitext(file)[0]])) for mod in pymods: exec('import {0} as module'.format(mod)) doctest.testmod(module) for mod in pyxmods: exec('import {0} as mod'.format(mod)) fix_module_doctests(mod) doctest.testmod(mod) for rst in glob(pjoin('tests', '*.rst')): doctest.testfile(rst)
def test(ctx, param, value): """Run doctests""" if not value or ctx.resilient_parsing: return import doctest doctest.testmod(verbose=True) ctx.exit()
def run_doctests(): '''Runs all doctests in the flickrapi module.''' # First run the flickrapi module (failure_count, test_count) = doctest.testmod(flickrapi) # run the submodules too. filenames = glob.glob('[a-z]*.py') modules = [fn[:-3] for fn in filenames] # Go to the top-level source directory to ensure relative path names are # correct. os.chdir('..') for modulename in modules: # Load the module module = load_module('%s.%s' % (flickrapi.__name__, modulename)) # Run the tests (failed, tested) = doctest.testmod(module) failure_count += failed test_count += tested if failure_count: print 'Doctests: %i of %i failed' % (failure_count, test_count) global failure failure = True else: print 'Doctests: all of %i OK' % test_count
def test(): from pprint import pprint pprint(get_atlas_summary(['Pou5f1', 'Dppa3'], 'Mus musculus')) pprint(get_atlas_summary(['PDLIM5', 'FGFR2' ], 'H**o sapiens')) import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
def main(): engine = get_engine() engine.connect() try: doctest.testmod(verbose=True) finally: engine.disconnect()
def testmod(): import doctest global testEntry, testCatalog, testToHtml, testArchiveToHtml urn = 'urn:x-internet-archive:bookserver:catalog' testCatalog = Catalog(title='Internet Archive OPDS', urn=urn) testLink = Link(url = 'http://archive.org/download/itemid.pdf', type = 'application/pdf', rel='http://opds-spec.org/acquisition/buying') catalogLink = Link(url = '/providers/IA', type = Link.opds) testEntry = Entry({'urn' : 'x-internet-archive:item:itemid', 'title' : u'test item', 'updated' : '2009-01-01T00:00:00Z', 'date': '1977-06-17T00:00:55Z', 'summary': '<p>Fantastic book.</p>', }, links=[testLink]) start = 0 numFound = 2 numRows = 1 urlBase = '/alpha/a/' testNavigation = Navigation.initWithBaseUrl(start, numRows, numFound, urlBase) testCatalog.addNavigation(testNavigation) osDescription = 'http://bookserver.archive.org/catalog/opensearch.xml' testSearch = OpenSearch(osDescription) testCatalog.addOpenSearch(testSearch) testCatalog.addEntry(testEntry) testToHtml = CatalogToHtml(testCatalog) testArchiveToHtml = ArchiveCatalogToHtml(testCatalog) doctest.testmod()
def main(): globs = {} try: #doctest.testmod() doctest.testmod(raise_on_error=True, globs=globs) except doctest.UnexpectedException as failure: exc_info = failure.exc_info # ctx = {} # for example in failure.test.examples: # try: # exec example.source in ctx, globals() # except Exception, e: # pm_to.__startframe__ = exc_info[2] # TODO: fuzzy? find functions on the same module that # were modified "soon" raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) except doctest.DocTestFailure as failure: example = failure.example print(example.source, '?=', example.want, 'got', failure.got, file=sys.stderr) try: # globs = {} # for ex in failure.test.examples: # if ex is example: break # exec ex.source in globs, globals() assert eval(example.source, globs, globals()) == eval(example.want, globs, globals()) except AssertionError: pm_to.__frames__ = [tb for tb in inspect.getinnerframes(sys.exc_info()[2])] calls = [i for i in ast.walk(ast.parse(failure.example.source)) if isinstance(i, ast.Call)] if len(calls) > 0: _, fname = calls[-1], calls[-1].func.id print('on call ', fname, 'locals are', pm_to(fname), file=sys.stderr)
def test(verbose=0): """ Test runner """ import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
def test(): """ >>> from pylab import show >>> p=show() """ import doctest doctest.testmod()
def main(): import sys if '--test' in sys.argv: import doctest doctest.testmod() sys.exit(0) if len(sys.argv) != 2: sys.stdout.write('Usage: {} <year>\n'.format(sys.argv[0])) sys.exit(1) line = '' year = int(sys.argv[1]) for dt in iter_year(year): prev_dt = dt - ONE_DAY if dt.month != prev_dt.month or dt == prev_dt: if line: sys.stdout.write('{0}\n'.format(line)) line = '' sys.stdout.write('# {0}-{1}\n'.format(dt.month, dt.year)) line = ' ' * (dt.isoweekday() - 1) line += holiday_char if is_holiday(dt) else workday_char if dt.isoweekday() >= 7: sys.stdout.write('{0}\n'.format(line)) line = '' sys.stdout.write('{0}\n'.format(line))
def _test(): """ Run tests in docstrings. """ import doctest doctest.testmod(optionflags=+doctest.ELLIPSIS)
def _test(chat=None): if chat: print "Unit tests for gmpy2 (mpfr functionality)" print " on Python %s" % sys.version print "Testing gmpy2 {0}".format(_g.version()) print " Mutliple-precision library: {0}".format(_g.mp_version()) print " Floating-point library: {0}".format(_g.mpfr_version()) print " Complex library: {0}".format(_g.mpc_version()) print " Caching Values: (Number) {0}".format(_g.get_cache()[0]) print " Caching Values: (Size, limbs) {0}".format(_g.get_cache()[1]) thismod = sys.modules.get(__name__) doctest.testmod(thismod, report=0) if chat: print "Repeating tests, with caching disabled" _g.set_cache(0,128) sav = sys.stdout class _Dummy: def write(self,*whatever): pass try: sys.stdout = _Dummy() doctest.testmod(thismod, report=0, optionflags=doctest.IGNORE_EXCEPTION_DETAIL) finally: sys.stdout = sav if chat: print print "Overall results for mpfr:" return doctest.master.summarize(chat)
def run_check(argList): """ Parse options and run checks on Python source. """ options, args = process_options(argList) if options.doctest: import doctest doctest.testmod(verbose=options.verbose) selftest() start_time = time.time() for path in args: if os.path.isdir(path): input_dir(path) else: input_file(path) elapsed = time.time() - start_time if options.statistics: print_statistics() if options.benchmark: print_benchmark(elapsed) if options.count: print(get_count()) values = [r for r in RESULTS if r] RESULTS[:] = [] return values
def _test(chat=None): if chat: print("Unit tests for gmpy2 (mpq functionality)") print(" on Python %s" % sys.version) print("Testing gmpy2 {0}".format(_g.version())) print(" Mutliple-precision library: {0}".format(_g.mp_version())) print(" Floating-point library: {0}".format(_g.mpfr_version())) print(" Complex library: {0}".format(_g.mpc_version())) print(" Caching Values: (Number) {0}".format(_g.get_cache()[0])) print(" Caching Values: (Size, limbs) {0}".format(_g.get_cache()[1])) thismod = sys.modules.get(__name__) doctest.testmod(thismod, report=0) if chat: print("Repeating tests, with caching disabled") _g.set_cache(0,128) sav = sys.stdout class _Dummy: encoding = None def write(self,*whatever): pass try: sys.stdout = _Dummy() doctest.testmod(thismod, report=0) finally: sys.stdout = sav if chat: print() print("Overall results for mpq:") return doctest.master.summarize(chat)
def programm_testen(): print("\n-------------------------------------------------------") print("Fehlgeschlagene Test:") doctest.testmod() print("-------------------------------------------------------\n")
orangeColor = color(1, 0.65, 0) # CMYK yellowColor = color(c=0, m=0, y=1, k=0) magentaColor = color(c=0, m=1, y=0, k=0) cyanColor = color(c=1, m=0, y=0, k=0) # All on, for registration / cropmarks usage. registrationColor = color(cmyk=1) # NOTE: Needed to be renamed, else Color class has a naming conflict: # # W0143: Comparing against a callable, did you omit the parenthesis? # (comparison-with-callable) def rgbColor(r, g=None, b=None, rgb=None, name=None): return color(r=r, g=g, b=b, name=name) def spotColor(spot): return color(spot=spot) def cmykColor(c, m=None, y=None, k=None): return color(c=c, m=m, y=y, k=k) def ralColor(ral): return color(ral=ral) if __name__ == "__main__": import doctest import sys sys.exit(doctest.testmod()[0])
def test_rst_formatter_doctests(self): import tablib.formats._rst results = doctest.testmod(tablib.formats._rst) self.assertEqual(results.failed, 0)
a = 0.23 rns = (1.0 - a) * rs # step 18: net outgoing long wave solar radiation sigma = 4.903e-9 rnl = sigma * 0.5 * (math.pow(tmax_C + 273.16, 4) + math.pow(tmin_C + 273.16, 4)) * (0.34 - 0.14 * math.sqrt(ea)) * (1.35 * rs / rso - 0.35) # step 19: net radiation rn = rns - rnl # step 20: overall evapotranspiration ev_rad = dt * rn ev_wind = pt * tt * (es - ea) evt = ev_rad + ev_wind return evt def evapotranspiration_US(tmax_F, tmin_F, sr_avg, ws_mph, z_ft, lat, ts=None): if tmax_F is None or tmin_F is None or sr_avg is None or ws_mph is None: return None tmax_C = FtoC(tmax_F) tmin_C = FtoC(tmin_F) ws_mps = ws_mph * METER_PER_MILE / 3600.0 z_m = z_ft * METER_PER_FOOT evt = evapotranspiration_Metric(tmax_C, tmin_C, sr_avg, ws_mps, z_m, lat, ts) return evt / MM_PER_INCH if evt is not None else None if __name__ == "__main__": import doctest if not doctest.testmod().failed: print("PASSED")
@new_contract def even(x: int) -> None: """Check even numbers.""" if x % 2 != 0: raise ValueError('The number {0} is not even.'.format(x)) @contract(n='int,>=0', returns='list[>=0](int,>=0,even)') def even_fib(n: int) -> list: """Return a list of n even numbers of the Fibonacci sequence. >>> even_fib(4) [0, 2, 8, 34] """ if n == 0: return [] f = [0, 1] res = [0] while len(res) < n: f[0], f[1] = f[1], sum(f) if f[1] % 2 == 0: res.append(f[1]) return res if __name__ == '__main__': doctest.testmod() print("Five even Fibonacci numbers:", even_fib(5))
# coding:utf-8 """ User Name: [email protected] Date Time: 2019-12-16 14:13:46 File Name: _private.py @v1.0 """ if __name__ == "__main__": import doctest doctest.testmod(verbose=False) # import pydoc # pydoc.doc(SomeClass)
for _ in range(acc): q = 1 # To kick-off the counting yield dict(zip(factors.keys(), counter)) # up front to give zeroth value for i, e in enumerate(factors.values()): if q == 1: q, counter[i] = divmod(counter[i] + 1, e + 1) else: break def divisors(factors): """ A generator that returns the divisors from the prime factors of the dividend. Args: factors: Dictionary of prime factors (keys) and their exponents (values). Returns: An integer divisor. Usage: >>> list(divisors({2: 2, 5: 2})) [1, 2, 4, 5, 10, 20, 25, 50, 100] """ for d in divisorsFactors(factors): yield calcDivisor(d) if __name__ == "__main__": import doctest print(doctest.testmod())
def run_tests(): doctest.testmod(verbose=True)
>>> with flow.no_grad(): ... y = x * x >>> y.requires_grad False >>> @flow.no_grad() ... def no_grad_func(x): ... return x * x >>> y = no_grad_func(x) >>> y.requires_grad False """ def __call__(self, func): def wrapper(*args, **kwargs): with AutoGradMode(False): return func(*args, **kwargs) return wrapper def __enter__(self): self.grad_mode = AutoGradMode(False) return self def __exit__(self, exc_type, exc_val, exc_tb): pass if __name__ == "__main__": import doctest doctest.testmod(raise_on_error=True)
def doctest(): import doctest import json doctest.testmod()
def test(): import doctest doctest.testmod()
else: print "SOMETHING IS WRONG WITH BUCKETS" beats = beats + da_dict[dance[i]].beats i += 1 print translation return translation def make_choreo(): """Calls functions to create new dance and translate it. """ dance, da_dict, the_prog = algorithm.do_it_all() print "DANCE IS ", dance translation = simple_trans(dance, da_dict) return dance, translation, the_prog if __name__ == "__main__": from server import app connect_to_db(app) print "Connected to DB." doctest.testmod(verbose=True) make_title() make_choreo()
self.fd = fd self.dbg = dbg def __getattribute__(self, name): if name in ('fd', 'dbg', 'write', 'flush', 'close'): return object.__getattribute__(self, name) else: self.dbg.write('==(%d.%s)\n' % (self.fd.fileno(), name)) return object.__getattribute__(self.fd, name) def write(self, data, *args, **kwargs): self.dbg.write('<=(%d.write)= %s\n' % (self.fd.fileno(), HideBinary(data).rstrip())) return self.fd.write(data, *args, **kwargs) def flush(self, *args, **kwargs): self.dbg.write('==(%d.flush)\n' % self.fd.fileno()) return self.fd.flush(*args, **kwargs) def close(self, *args, **kwargs): self.dbg.write('==(%d.close)\n' % self.fd.fileno()) return self.fd.close(*args, **kwargs) # If 'python util.py' is executed, start the doctest unittest if __name__ == "__main__": import doctest import sys if doctest.testmod().failed: sys.exit(1)
>>> for count in countdown(10): ... print(count) 10 9 8 7 6 5 4 3 2 1 BLASTOFF! ''' # Write your code here: # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved.
>>> one = Node(1) >>> two = Node(2) >>> three = Node(3) >>> one.add_child(two) >>> one.add_child(three) >>> num_nodes(one) 3 >>> four = Node(4) >>> five = Node(5) >>> two.add_child(four) >>> two.add_child(five) >>> num_nodes(one) 5 >>> six = Node(6) >>> three.add_child(six) >>> num_nodes(one) 6 """ ##################################################################### # END OF ASSIGNMENT: You can ignore everything below. if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!" print
def transform(self, transformation): """Transform the box. Parameters ---------- transformation : :class:`Transformation` The transformation used to transform the Box. Examples -------- >>> box = Box(Frame.worldXY(), 1.0, 2.0, 3.0) >>> frame = Frame([1, 1, 1], [0.68, 0.68, 0.27], [-0.67, 0.73, -0.15]) >>> T = Transformation.from_frame(frame) >>> box.transform(T) """ self.frame.transform(transformation) # ============================================================================== # Main # ============================================================================== if __name__ == '__main__': import doctest from compas.geometry import Transformation # noqa : F401 doctest.testmod(globs=globals())
self.my_turtle.setheading(270) self.my_turtle.forward(down) def draw_line(self, direction, distance): """ Draws a line of given distance pointing in the provided direction :param int direction: the heading to face, in degrees (must be between 0 - 360) :param int distance: the distance to travel :return: >>> t = TurtleDrawer() >>> t.draw_line(72, 90) >>> t.draw_line(666, 42) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ValueError: Direction given was 666, must be between 0 - 360 >>> t.draw_line(-75, 43) Traceback (most recent call last): ValueError: Direction given was -75, must be between 0 - 360 >>> t.draw_line(45, -100) """ if direction in range(0, 360): self.my_turtle.setheading(direction) self.my_turtle.forward(distance) else: raise ValueError(f"Direction given was {direction}, must be between 0 - 360") if __name__ == "__main__": import doctest doctest.testmod(extraglobs={'t': TurtleDrawer()}, verbose=True)
def _test(): import doctest start_suppress = np.get_printoptions()['suppress'] np.set_printoptions(suppress=True) doctest.testmod() np.set_printoptions(suppress=start_suppress)
out += [iRchl] if Rcyt: out += [iRcyt] if Rstarch: out += [iRstarch] if Rpyr: out += [iRpyr] if Rbio: out += [iRbio] if Rphloem: out += [iRphloem] if Vstarch: out += [iVstarch] if ass13: out += [iAss13] if disc: out += [idisc] if Rnew_starch: out += [iRnew_starch] if Rnew_cyt: out += [iRnew_cyt] if Vstarch & np.any(starch_mol2g is not None): out += [iVstarchg] return out if __name__ == '__main__': import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
def _test(): import doctest, os, sys sys.path.insert(0, os.pardir) import pytz return doctest.testmod(pytz)
def test_decay_module_with_doctest(): """Doctest embedded in a nose/pytest unit test.""" # Test all functions with doctest in module decay failure_count, test_count = doctest.testmod(m=decay) assert failure_count == 0
def test_doctests(): results = doctest.testmod(tasks) assert results.failed == 0
distributable_py_file, distributablep_filename, f"LocalInParts({taskindex},{self.taskcount},mkl_num_threads={self.mkl_num_threads},weights={self.weights},environ={environ})".replace(" ","") ] #logging.info(command_string_list) proc = subprocess.Popen(command_string_list, cwd=os.getcwd()) proc_list.append(proc) for taskindex, proc in enumerate(proc_list): rc = proc.wait() if not 0 == rc : raise Exception("Running python in python results in non-zero return code in task#{0}".format(taskindex)) else: from pysnptools.util.mapreduce1.runner import LocalInParts for taskindex in range(self.taskcount): environ = self.taskindex_to_environ(taskindex) if self.taskindex_to_environ is not None else None LocalInParts(taskindex,self.taskcount, mkl_num_threads=self.mkl_num_threads, weights=self.weights, environ=environ).run(distributable) environ = self.taskindex_to_environ(self.taskcount) if self.taskindex_to_environ is not None else None result = _run_one_task(distributable, self.taskcount, self.taskcount, distributable.tempdirectory, weights=self.weights, environ=environ) _JustCheckExists().output(distributable) return result if __name__ == "__main__": logging.basicConfig(level=logging.INFO) from pysnptools.util.mapreduce1 import map_reduce #Needed to work around thread local variable issue import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
''' Created on 2011-3-13 @author: me ''' def average(values): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main()
print("\n=== Pull Request #%s ===" % pr_num) print("PR title\t%s\nCommit title\t%s\nSource\t\t%s\nTarget\t\t%s\nURL\t\t%s" % ( pr_title, commit_title, pr_repo_desc, target_ref, url)) continue_maybe("Proceed with merging pull request #%s?" % pr_num) merged_refs = [target_ref] # proceed with the merge merge_hash, merge_commit_log = merge_pr(pr_num, target_ref, commit_title, body, pr_reviewers, pr_repo_desc) # once the pr is merged, refresh the local repo run_cmd("git fetch %s" % PR_REMOTE_NAME) pick_prompt = "Would you like to pick %s into another branch?" % merge_hash while raw_input("\n%s (y/n): " % pick_prompt).lower() == "y": pick_ref = ask_for_branch(latest_branch) branch_version = pick_ref.split('-')[1] # add releases fix_releases = ask_release_for_github_issues(branch_version, labels) if len(fix_releases) > 0: all_issue_labels = add_release_to_github_issues(github_issue_ids, all_issue_labels, fix_releases[0]) merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, pick_ref)] if __name__ == "__main__": import doctest (failure_count, test_count) = doctest.testmod() if (failure_count): exit(-1) main()
import sys, os sys.path.insert(0, os.pardir) import decay import doctest def test_decay_module_with_doctest(): """Doctest embedded in a nose/pytest unit test.""" # Test all functions with doctest in module decay failure_count, test_count = doctest.testmod(m=decay) assert failure_count == 0 if __name__ == '__main__': # Run all functions with doctests in this module failure_count, test_count = doctest.testmod(m=decay)
# -*- encoding: utf-8 -*- __doc__ = u""" This test should pass:: >>> print u'ä' ä """ import doctest print '-' * 70 failures, tests = doctest.testmod() print 'No doctest output:' print '%s tests, %s failures' % (tests, failures) print '-' * 70 try: # next line raises UnicodeEncodeError on Python 2.5 failures, tests = doctest.testmod(verbose=True) print 'With doctest output:' print '%s tests, %s failures' % (tests, failures) except UnicodeEncodeError, ue: print 'Doctest output would contain non-ASCII character, testmod aborts with' print 'exception class:', ue.__class__ print 'encoding:', ue.encoding print 'reason:', ue.reason print 'start:', ue.start print 'end:', ue.end print 'object:' print ue.object
:UC: self must be non empty """ try: return self.__content.pop() except IndexError: raise StackEmptyError('empty stack, nothing to pop') def top(self): """ :return: element on top of self without removing it :UC: self must be non empty """ try: return self.__content[-1] except IndexError: raise StackEmptyError('empty stack, nothing on the top') def is_empty(self): """ :return: * ``True`` if s is empty * ``False`` otherwise :rtype: bool :UC: none """ return self.__content == [] if __name__ == '__main__': import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS, verbose=True)
def update_event(self, inp=-1): self.set_output_val(0, doctest.testmod(self.input(0), self.input(1), self.input(2), self.input(3), self.input(4), self.input(5), self.input(6), self.input(7), self.input(8)))
'items': self.setitems, 'values': self.setvalues, } def __setattr__(self, name, value): """Protect keys, items, and values.""" if not '_att_dict' in self.__dict__: object.__setattr__(self, name, value) else: try: fun = self._att_dict[name] except KeyError: OrderedDict.__setattr__(self, name, value) else: fun(value) if __name__ == '__main__': if INTP_VER < (2, 3): raise RuntimeError("Tests require Python v.2.3 or later") # turn off warnings for tests warnings.filterwarnings('ignore') # run the code tests in doctest format import doctest m = sys.modules.get('__main__') globs = m.__dict__.copy() globs.update({ 'INTP_VER': INTP_VER, }) doctest.testmod(m, globs=globs)