def doctest_object(name, obj): """doctest obj and enclosed methods and classes.""" if type(obj) in ( types.FunctionType, types.TypeType, types.ClassType, types.MethodType, types.UnboundMethodType, ): # Reload environment before each test. globs = env(a, c=c, f=f, import_models=import_models) execfile(testfile, globs) doctest.run_docstring_examples( obj, globs=globs, name="%s: %s" % (os.path.basename(testfile), name), verbose=verbose ) if type(obj) in (types.TypeType, types.ClassType): for attr_name in dir(obj): # Execute . operator so decorators are executed. o = eval("%s.%s" % (name, attr_name), globs) doctest_object(attr_name, o)
def doctests(): try: import psyco psyco.full() except ImportError: pass import sys from timeit import default_timer as clock filter = [] for i, arg in enumerate(sys.argv): if '__init__.py' in arg: filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")] break import doctest globs = globals().copy() for obj in globs: #sorted(globs.keys()): if filter: if not sum([pat in obj for pat in filter]): continue sys.stdout.write(str(obj) + " ") sys.stdout.flush() t1 = clock() doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv)) t2 = clock() print(round(t2-t1, 3))
def test(): """run the examples in the docstrings using the doctest module""" import doctest print('Testing pyproj.Proj ...') doctest.run_docstring_examples(pyproj, None, name='pyproj.Proj', verbose=False) print('Testing pyproj.Proj ... done')
def _test(): """You can use python __init__.py [-v] module[.class] to run only selected tests""" import doctest,sys import protocols, messages, entities, transports, containers,tests if len(sys.argv) > 1 and sys.argv[-1] != '-v': name = sys.argv[-1] gb = globals() gb.update(locals()) verbose = '-v' in sys.argv if '.' in name: m,c = name.split('.') mod = gb[m] obj = getattr(mod,c) gb = mod.__dict__ doctest.run_docstring_examples(obj,gb,verbose,name,optionflags=doctest.ELLIPSIS) else: obj = gb[name] doctest.testmod(obj,optionflags=doctest.ELLIPSIS) else: #doctest.testmod(optionflags=doctest.ELLIPSIS) doctest.testmod(optionflags=doctest.ELLIPSIS) doctest.testmod(protocols,optionflags=doctest.ELLIPSIS) doctest.testmod(messages,optionflags=doctest.ELLIPSIS) doctest.testmod(entities,optionflags=doctest.ELLIPSIS) doctest.testmod(transports,optionflags=doctest.ELLIPSIS) doctest.testmod(containers,optionflags=doctest.ELLIPSIS) doctest.testmod(tests,optionflags=doctest.ELLIPSIS)
def test(target=None, show=False, onlydoctests=False, coverage=False, htmlreport=False): """Run docstring examples and additional tests. Examples -------- >>> from pygimli.utils import boxprint >>> test(target=boxprint) Parameters ---------- target : function, optional Function or method to test. By default everything is tested. show : boolean, optional Show matplotlib windows during test run. They will be closed automatically. onlydoctests : boolean, optional Run test files in ../tests as well. coverage : boolean, optional Create a coverage report. Requires the pytest-cov plugin. htmlreport : str, optional Filename for HTML report such as www.pygimli.org/build_tests.html. Requires pytest-html plugin. """ if target: import doctest doctest.run_docstring_examples(target, globals()) return try: import pytest except ImportError: raise ImportError("pytest is required to run test suite. " + \ "Try 'sudo pip install pytest'.") from matplotlib import pyplot as plt from pygimli.utils import opt_import pc = opt_import("pytest_cov", "create a code coverage report") ph = opt_import("pytest_html", "create a html report") old_backend = plt.get_backend() if not show: plt.switch_backend("Agg") cwd = os.path.realpath(__path__[0]) cfg = os.path.join(cwd, "../tests/setup.cfg") cmd = "" if os.path.exists(cfg): cmd += "-c %s " % cfg if pc and coverage: cmd += "--cov pygimli --cov-report term " + \ "--cov-config %s " % cfg.replace("setup.cfg", ".coveragerc") if ph and htmlreport: cmd += "--html %s " % htmlreport cmd += "%s " % cwd if not onlydoctests and os.path.exists(cfg): cmd += os.path.join(cwd, "../tests") exitcode = pytest.main(cmd) plt.switch_backend(old_backend) plt.close('all') sys.exit(exitcode)
def run_doctests(names): """Run verbose doctests for all functions in space-separated names.""" g = globals() errors = [] for name in names.split(): if name not in g: print("No function named " + name) else: run_docstring_examples(g[name], g, True, name)
def do_test(self, args): """ Run all the `docstring`s. """ if args: for param in args.split(): if not param in self.commands: print(NO_SUCH_CMD.format(param)) else: run_docstring_examples(eval("self.do_"+param), globals().copy()) else: testmod()
def _test_all(): '''To use these tests, from the w3af root directory, do: >>> import core.ui.gtkUi.encdec >>> core.ui.gtkUi.encdec._test_all() ''' import doctest glob = globals() for func in (x[1] for x in _butNameFunc_enc+_butNameFunc_dec): doctest.run_docstring_examples(func, glob)
def test(): """run the examples in the docstrings using the doctest module""" import doctest #print 'Testing colormath ...' #doctest.run_docstring_examples(colormath, None, name='colormath', verbose=False) #print 'Testing colormath ... done' print 'Testing numpy ...' doctest.run_docstring_examples(numpy, None, name='numpy', verbose=False) print 'Testing numpy ... done'
def test_comparison(self): r""" >>> V('1.2.0') == '1.2' Traceback (most recent call last): ... TypeError: cannot compare NormalizedVersion and str >>> V('1.2.0') == V('1.2') True >>> V('1.2.0') == V('1.2.3') False >>> V('1.2.0') < V('1.2.3') True >>> (V('1.0') > V('1.0b2')) True >>> (V('1.0') > V('1.0c2') > V('1.0c1') > V('1.0b2') > V('1.0b1') ... > V('1.0a2') > V('1.0a1')) True >>> (V('1.0.0') > V('1.0.0c2') > V('1.0.0c1') > V('1.0.0b2') > V('1.0.0b1') ... > V('1.0.0a2') > V('1.0.0a1')) True >>> V('1.0') < V('1.0.post456.dev623') True >>> V('1.0.post456.dev623') < V('1.0.post456') < V('1.0.post1234') True >>> (V('1.0a1') ... < V('1.0a2.dev456') ... < V('1.0a2') ... < V('1.0a2.1.dev456') # e.g. need to do a quick post release on 1.0a2 ... < V('1.0a2.1') ... < V('1.0b1.dev456') ... < V('1.0b2') ... < V('1.0c1.dev456') ... < V('1.0c1') ... < V('1.0.dev7') ... < V('1.0.dev18') ... < V('1.0.dev456') ... < V('1.0.dev1234') ... < V('1.0') ... < V('1.0.post456.dev623') # development version of a post release ... < V('1.0.post456')) True """ # must be a simpler way to call the docstrings doctest.run_docstring_examples(self.test_comparison, globals(), name='test_comparison')
def run_docstring_examples(obj, verbose=True): from IPython.core.interactiveshell import InteractiveShell import doctest inst = InteractiveShell.instance() globs = inst.user_ns return doctest.run_docstring_examples(obj, globs, verbose=verbose)
def test_get_group(self): board_string = ( "b b w e e\n" "b w e w e\n" "w b b w w\n" "e w w w e\n" "e e e w e") board = BoardModel.from_string(board_string) self.assertEqual(([(0, 0), (0, 1), (1, 0)], ("white", )), board.get_group(0, 0)) self.assertEqual(([(2, 0)], ("black", "empty")), board.get_group(2, 0)) self.assertEqual(([(3, 4), (4, 4)], ("white", )), board.get_group(4, 4)) doctest.run_docstring_examples( BoardModel.get_group, {"BoardModel": BoardModel}, name="get_group")
def adv_word_length_sorted_words(words): """Given list of words, return list of ascending [(len, [sorted-words])]. Given a list of words, return a list of tuples, ordered by word-length. Each tuple should have two items--the length of the words for that word-length, and the list of words of that word length. The list of words for that length should be sorted alphabetically. For example: >>> adv_word_length_sorted_words(["ok", "an", "apple", "a", "day"]) [(1, ['a']), (2, ['an', 'ok']), (3, ['day']), (5, ['apple'])] """ word_frequency_dict = {} word_frequency_list = [] for word in words: word_frequency_dict.setdefault(len(word),[]).append(word) for key, value in word_frequency_dict.items(): value.sort() word_frequency_list.append((key, value)) return word_frequency_list ############################################################################## # You can ignore everything after here def print_dict(d): # This method is just used to print dictionaries in key-alphabetical # order, and is only used for our documentation tests. You can ignore it. if isinstance(d, dict): print "{" + ", ".join("%r: %r" % (k, d[k]) for k in sorted(d)) + "}" else: print d def sort_pairs(l): # Print sorted list of pairs where the pairs are sorted. This is used only # for documentation tests. You can ignore it. return sorted(sorted(pair) for pair in l) if __name__ == "__main__": print import doctest for k, v in globals().items(): if k[0].isalpha(): if k.startswith('adv_') and not ADVANCED: continue a = doctest.run_docstring_examples(v, globals(), name=k) print "** END OF TEST OUTPUT" print
def run_doctests(names): """Run verbose doctests for all functions in space-separated names.""" g = globals() errors = [] for name in names.split(): if name not in g: print("No function named " + name) else: if run_docstring_examples(g[name], g, True) is not None: errors.append(name) if len(errors) == 0: print("Test passed.") else: print("Error(s) found in: " + ', '.join(errors))
def do_testmod(globals_=None, locals_=None, name=None, default_options=None, **doctest_kw): """ Default options can be any of the doctest flags combinations (as integer) or True/False. None defaults to True. If True, uses ELLIPSIS and NORMALIZE_WHITESPACE, otherwise uses no options. """ NO_OPTIONS = 0 STANDARD_OPTIONS = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE if default_options in (None, True): default_options = STANDARD_OPTIONS elif default_options is False: default_options = NO_OPTIONS else: default_options = int(default_options) doctest_kw.setdefault('optionflags', NO_OPTIONS) doctest_kw['optionflags'] |= default_options if name: doctest.run_docstring_examples( eval(name, globals_, locals_), globals_, name=name, **doctest_kw) return [], 0 else: return doctest.testmod(**doctest_kw)
assert isinstance(stop, int), "The stop index must be an int." assert start >= 0, "The start index must be non-negative." assert start < stop, "Stop index must be higher than the stop" i = 0 while True: item = (yield) i += 1 if start <= i <= stop: target.send(item) # once we hit the stop, no point checking from # now on elif i > stop: while True: limbo = (yield) @coroutine def sort(target): while 1: for item in sorted(i for i in (yield)): # possible? target.send(item) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) from copy import copy gg = globals() for f in copy(gg): doctest.run_docstring_examples(f, gg)
def doctestobj(*args, **kwargs): """ Wrapper for doctest.run_docstring_examples that works in maya gui. """ return doctest.run_docstring_examples(*args, **kwargs)
def doc_check(func): """Use to check specific functions, or get more information on why they failed the doctest.""" doctest.run_docstring_examples(func,globals())
class Smarts(object): """A Smarts Pattern Matcher Required parameters: smartspattern Methods: match(molecule) Example: >>> mol = readstring("smi","CCN(CC)CC") # triethylamine >>> smarts = Smarts("[#6][#6]") # Matches an ethyl group >>> smarts.match(mol) True """ def __init__(self, smartspattern): """Initialise with a SMARTS pattern.""" self.pat = smartspattern def match(self, molecule): """Does a SMARTS pattern match a particular molecule? Required parameters: molecule """ resp = rajweb("substruct", _quo(molecule.smiles), _quo(self.pat)).rstrip() return resp == "true" if __name__=="__main__": #pragma: no cover import doctest doctest.run_docstring_examples(rajweb, globals())
#doctest.testmod() doctest.run_docstring_examples(rp_extract, globals(), verbose=True) if __name__ == '__main__': import sys from audiofile_read import * # import our library for reading wav and mp3 files # process file given on command line or default song (included) if len(sys.argv) > 1: if sys.argv[1] == '-test': # RUN DOCSTRING SELF TEST print "Doing self test. If nothing is printed, it is ok." import doctest doctest.run_docstring_examples(rp_extract, globals()) #, verbose=True) exit() # Note: no output means that everything went fine else: audiofile = sys.argv[1] else: audiofile = "music/BoxCat_Games_-_10_-_Epic_Song.mp3" # Read audio file and extract features try: samplerate, samplewidth, wavedata = audiofile_read(audiofile) np.set_printoptions(suppress=True) bark_bands = 24 # choose the number of Bark bands (2..24) mod_ampl_limit = 60 # number modulation frequencies on x-axis
def get_reverse_complement(dna): """ Computes the reverse complementary sequence of DNA for the specfied DNA sequence dna: a DNA sequence represented as a string returns: the reverse complementary DNA sequence represented as a string >>> get_reverse_complement("ATGCCCGCTTT") 'AAAGCGGGCAT' >>> get_reverse_complement("CCGCGTTCA") 'TGAACGCGG' >>> get_reverse_complement("ATCG") 'CGAT' """ # TODO: implement this reversed_dna = dna[::-1] result = ' ' for letter in reversed_dna: result = result + get_complement(letter) return result def divide_to_codons(dna): """Takes a DNA sequence and outputs a list of string triplets(codons) that makes up the sequence Last element might be incomplete codon with less then three letters >>> divide_to_codons("ATGTGAA") ['ATG', 'TGA', 'A'] >>> divide_to_codons("ATGTGA") ['ATG', 'TGA'] >>> divide_to_codons("ATGTGAAA") ['ATG', 'TGA', 'AA'] """ index = 0 result = [] while index < len(dna): result.append(dna[index:index+3]) index = index + 3 return result def rest_of_ORF(dna): """ Takes a DNA sequence that is assumed to begin with a start codon and returns the sequence up to but not including the first in frame stop codon. If there is no in frame stop codon, returns the whole string. dna: a DNA sequence returns: the open reading frame represented as a string >>> rest_of_ORF("ATGTGAA") 'ATG' >>> rest_of_ORF("ATGAGATAGG") 'ATGAGA' >>> rest_of_ORF("ATG") 'ATG' >>> rest_of_ORF("AT") 'AT' >>> rest_of_ORF("ATGASDASDWASDWADASDSAD") 'ATGASDASDWASDWADASDSAD' >>> rest_of_ORF("ATGTGTTAAATGAAAAAATAGAA") 'ATGTGT' """ stop_codons = ['TAG', 'TAA, TGA'] #list of codons from which the dna is composed of codons = divide_to_codons(dna) result = "" index = 0 while index + 1 < len(codons): #If next codons isn't a stop codon, add it to string and iterate if codons[index + 1] not in stop_codons: result = result + codons[index] index = index + 1 else: #Add codon before stop codon result = result + codons[index] return result return dna def find_all_ORFs_oneframe(dna): """ Finds all non-nested open reading frames in the given DNA sequence and returns them as a list. This function should only find ORFs that are in the default frame of the sequence (i.e. they start on indices that are multiples of 3). By non-nested we mean that if an ORF occurs entirely within another ORF, it should not be included in the returned list of ORFs. dna: a DNA sequence returns: a list of non-nested ORFs >>> find_all_ORFs_oneframe("ATGCATGAATGTAGATAGATGTGCCC") ['ATGCATGAATGTAGA', 'ATGTGCCC'] >>> find_all_ORFs_oneframe("ATGTGAA") ['ATG'] >>> find_all_ORFs_oneframe('ASDASDAWSDSD') [] >>> find_all_ORFs_oneframe('TATATGCATGAATGTAGATAGATGTGCTAAATAATAATGTTTTAAATT') ['ATGCATGAATGTAGA', 'ATGTGC', 'ATGTTT'] """ index = 0 orf_list = [] while index < len(dna): if dna[index:index+3] == 'ATG': #appended ORF orf = rest_of_ORF(dna[index:]) orf_list.append(orf) index = index + len(orf) else: index = index + 3 return orf_list def find_all_ORFs(dna): """ Finds all non-nested open reading frames in the given DNA sequence in all 3 possible frames and returns them as a list. By non-nested we mean that if an ORF occurs entirely within another ORF and they are both in the same frame, it should not be included in the returned list of ORFs. dna: a DNA sequence returns: a list of non-nested ORFs This unit testing would be enough because there isn't any special exceptions that needs to be tested. Also, this case tests this function's ability to grab orf from three different possible reading frames. >>> find_all_ORFs("ATGCATGAATGTAG") ['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG'] """ #orf list from all frames orf_list = [] #zero offset frame orf_list = orf_list + find_all_ORFs_oneframe(dna) #first offset frame orf_list = orf_list + find_all_ORFs_oneframe(dna[1:]) #second offset frame orf_list = orf_list + find_all_ORFs_oneframe(dna[2:]) return orf_list def find_all_ORFs_both_strands(dna): """ Finds all non-nested open reading frames in the given DNA sequence on both strands. dna: a DNA sequence returns: a list of non-nested ORFs >>> find_all_ORFs_both_strands("ATGCGAATGTAGCATCAAA") ['ATGCGAATG', 'ATGCTACATTCGCAT'] """ reverse = get_reverse_complement(dna) #finds orfs in both direction orf_list = find_all_ORFs(dna) + find_all_ORFs(reverse_complement) return orf_list def longest_ORF(dna): """ Finds the longest ORF on both strands of the specified DNA and returns it as a string >>> longest_ORF("ATGCGAATGTAGCATCAAA") 'ATGCTACATTCGCAT' """ longest_length = 0 orfs = find_all_ORFs_both_strands(dna) for orf in orfs: if len(orf) > longest_length: longest_orf = orf longest_length = len(orf) return longest_orf def longest_ORF_noncoding(dna, num_trials): """ Computes the maximum length of the longest ORF over num_trials shuffles of the specfied DNA sequence dna: a DNA sequence num_trials: the number of random shuffles returns: the maximum length longest ORF """ x = 0 longest = 0 while x < num_trials: shuffled_dna = shuffle_string(dna) longest_orf_length = len(longest_ORF(shuffled_dna)) if longest_orf_length > longest: longest = longest_orf_length x = x + 1 return longest def coding_strand_to_AA(dna): """ Computes the Protein encoded by a sequence of DNA. This function does not check for start and stop codons (it assumes that the input DNA sequence represents an protein coding region). dna: a DNA sequence represented as a string returns: a string containing the sequence of amino acids encoded by the the input DNA fragment >>> coding_strand_to_AA("ATGCGA") 'MR' >>> coding_strand_to_AA("ATGCCCGCTTT") 'MPA' >>> coding_strand_to_AA("TTTATCATGTTAGTTA") 'FIMLV' """ codons = divide_to_codons(dna) amino_acid = '' for codon in codons: if len(codon) == 3: amino_acid = amino_acid + aa_table[codon] return amino_acid def gene_finder(dna): """ Returns the amino acid sequences that are likely coded by the specified dna dna: a DNA sequence returns: a list of all amino acid sequences coded by the sequence dna. """ threshold = longest_ORF_noncoding(dna, 1500) all_orfs = find_all_ORFs_both_strands(dna) amnio_acids = [] for orf in all_orfs: if len(orf) > threshold : amino_acids.append(coding_strang_to_AA(orf)) return amino_acids if __name__ == "__main__": import doctest doctest.testmod(verbose = True) doctest.run_docstring_examples(coding_strand_to_AA, globals(), verbose = True) dna_seq = load_seq('data/X73525.fa') print (gene_finder(dna_seq))
for i, hofer in enumerate(self): # hofer = hall of famer if not dominates_one and hofer.fitness.dominates(ind.fitness): is_dominated = True break elif ind.fitness.dominates(hofer.fitness): dominates_one = True to_remove.append(i) elif ind.fitness == hofer.fitness and self.similar(ind, hofer): has_twin = True break for i in reversed(to_remove): # Remove the dominated hofer self.remove(i) if not is_dominated and not has_twin: self.insert(ind) __all__ = ['HallOfFame', 'ParetoFront', 'History', 'Statistics', 'MultiStatistics', 'Logbook'] if __name__ == "__main__": import doctest from operator import itemgetter import numpy doctest.run_docstring_examples(Statistics, globals()) doctest.run_docstring_examples(Statistics.register, globals()) doctest.run_docstring_examples(Statistics.compile, globals()) doctest.run_docstring_examples(MultiStatistics, globals()) doctest.run_docstring_examples(MultiStatistics.register, globals()) doctest.run_docstring_examples(MultiStatistics.compile, globals())
def self_test(): import doctest #doctest.testmod() doctest.run_docstring_examples(audiofile_read, globals())
elif ind.fitness.dominates(hofer.fitness): dominates_one = True to_remove.append(i) elif ind.fitness == hofer.fitness and self.similar(ind, hofer): has_twin = True break for i in reversed(to_remove): # Remove the dominated hofer self.remove(i) if not is_dominated and not has_twin: self.insert(ind) __all__ = [ 'HallOfFame', 'ParetoFront', 'History', 'Statistics', 'MultiStatistics', 'Logbook' ] if __name__ == "__main__": import doctest from operator import itemgetter import numpy doctest.run_docstring_examples(Statistics, globals()) doctest.run_docstring_examples(Statistics.register, globals()) doctest.run_docstring_examples(Statistics.compile, globals()) doctest.run_docstring_examples(MultiStatistics, globals()) doctest.run_docstring_examples(MultiStatistics.register, globals()) doctest.run_docstring_examples(MultiStatistics.compile, globals())
Job specific exception raised in job manager implementation Examples: >>> raise JobException(msg="sandesh init error", job_execution_id="12345") Traceback (most recent call last): ... JobException: JobException in execution (12345): sandesh init error >>> >>> raise JobException("sandesh init error", "12345") Traceback (most recent call last): ... JobException: JobException in execution (12345): sandesh init error """ def __init__(self, msg=None, job_execution_id=None): self.job_execution_id = job_execution_id self.msg = msg def __str__(self): return "JobException in execution (%s): %s" % \ (self.job_execution_id, self.msg) def __repr__(self): return self.msg if __name__ == "__main__": import doctest doctest.run_docstring_examples(__str__, globals())
def runtest(testname, verbose=False): if type(testname) is type(runtest): doctest.run_docstring_examples(testname, None, verbose) builtins.print("\n") else: builtins.print("Your input is not a function!")
def self_test(): import doctest #doctest.testmod() doctest.run_docstring_examples(rp_extract, globals(), verbose=True)
import doctest #doctest.testmod() doctest.run_docstring_examples(rp_extract, globals(), verbose=True) if __name__ == '__main__': import sys from audiofile_read import * # import our library for reading wav and mp3 files # process file given on command line or default song (included) if len(sys.argv) > 1: if sys.argv[1] == '-test': # RUN DOCSTRING SELF TEST print "Doing self test. If nothing is printed, it is ok." import doctest doctest.run_docstring_examples(rp_extract, globals()) #, verbose=True) exit() # Note: no output means that everything went fine else: audiofile = sys.argv[1] else: audiofile = "music/BoxCat_Games_-_10_-_Epic_Song.mp3" # Read audio file and extract features try: samplerate, samplewidth, wavedata = audiofile_read(audiofile) np.set_printoptions(suppress=True) bark_bands = 24 # choose the number of Bark bands (2..24) mod_ampl_limit = 60 # number modulation frequencies on x-axis
# For example: # >>> custom_equality(['Jan', 'Feb', 'Mar'], ['Jan', 'Feb', 'Mar']) # True # >>> custom_equality(['Jan', 'Feb', 'Mar'], ['Jan', 'Mar', 'Feb']) # False # """ # return None # ############################################################################## # # END OF EXTRA CREDIT # # # # Please ask for a code review. Also, give your partner a high-five! # ############################################################################## # # This is the part were we actually run the doctests. if __name__ == "__main__": import doctest for k, v in globals().items(): if k[0].isalpha(): if k.startswith('custom_') and not FURTHER_STUDY: continue result = doctest.run_docstring_examples(v, globals(), name=k) print "END OF TEST OUTPUT"
"""Returns the ith item in the rlist. If the index exceeds the length of the rlist, return 'Error'. >>> lst = tup_to_rlist((1, 2, 3, 4)) >>> getitem_rlist(0, lst) 1 >>> getitem_rlist(3, lst) 4 >>> getitem_rlist(4, lst) 'Error' """ "*** YOUR CODE HERE ***" if lst == empty_rlist: return 'Error' if i == 0: return first(lst) return getitem_rlist(i-1, rest(lst)) if __name__ == '__main__': from doctest import run_docstring_examples run_docstring_examples(reverse_iter1, globals(), True) run_docstring_examples(reverse_iter2, globals(), True) run_docstring_examples(reverse_recursive, globals(), True) run_docstring_examples(merge_iter1, globals(), True) run_docstring_examples(merge_iter2, globals(), True) run_docstring_examples(merge_recursive, globals(), True) run_docstring_examples(deep_len, globals(), True) run_docstring_examples(tup_to_rlist, globals(), True) run_docstring_examples(len_rlist, globals(), True) run_docstring_examples(getitem_rlist, globals(), True)
def test(target=None, show=False, onlydoctests=False, coverage=False, htmlreport=False, abort=False, verbose=True): """Run docstring examples and additional tests. Examples -------- >>> import pygimli as pg >>> # You can test everything with pg.test() or test a single function: >>> pg.test("pg.utils.boxprint", verbose=False) >>> # The target argument can also be the function directly >>> from pygimli.utils import boxprint >>> pg.test(boxprint, verbose=False) Parameters ---------- target : function or string, optional Function or method to test. By default everything is tested. show : boolean, optional Show matplotlib windows during test run. They will be closed automatically. onlydoctests : boolean, optional Run test files in ../tests as well. coverage : boolean, optional Create a coverage report. Requires the pytest-cov plugin. htmlreport : str, optional Filename for HTML report such as www.pygimli.org/build_tests.html. Requires pytest-html plugin. abort : boolean, optional Return correct exit code, e.g. abort documentation build when a test fails. """ printopt = np.get_printoptions() # Numpy compatibility (array string representation has changed) if np.__version__[:4] == "1.14": np.set_printoptions(legacy="1.13") old_backend = plt.get_backend() if not show: plt.switch_backend("Agg") if target: if isinstance(target, str): # If target is a string, such as "pg.solver.solve" # the code below will overwrite target with the corresponding # imported function, so that doctest works. target = target.replace("pg.", "pygimli.") import importlib mod_name, func_name = target.rsplit('.', 1) mod = importlib.import_module(mod_name) target = getattr(mod, func_name) import doctest doctest.run_docstring_examples(target, globals(), verbose=verbose, optionflags=doctest.ELLIPSIS, name=target.__name__) return try: import pytest except ImportError: raise ImportError("pytest is required to run test suite. " "Try 'sudo pip install pytest'.") cwd = join(realpath(__path__[0]), '..') excluded = [ "gui", "physics/traveltime/example.py", "physics/em/fdemexample.py" ] if onlydoctests: excluded.append("testing") cmd = ([ "-v", "-rsxX", "--color", "yes", "--doctest-modules", "--durations", 5, cwd ]) for directory in excluded: cmd.extend(["--ignore", join(cwd, directory)]) if coverage: pc = pg.optImport("pytest_cov", "create a code coverage report") if pc: cmd.extend(["--cov", "pygimli"]) cmd.extend(["--cov-report", "term"]) if htmlreport: ph = pg.optImport("pytest_html", "create a html report") if ph: cmd.extend(["--html", htmlreport]) exitcode = pytest.main(cmd) plt.switch_backend(old_backend) plt.close('all') np.set_printoptions(**printopt) if abort: sys.exit(exitcode)
"""Returns an interval that is the sum of the squares of the non-zero intervals in seq, using using reduce and a generator expression. >>> str_interval(sum_nonzero_with_generator_reduce(seq)) '0.25 to 2.25' """ "*** YOUR CODE HERE ***" return reduce( add_interval, [ square_interval(x) for x in seq if non_zero(x) ]) # Q10. def polynomial(x, c): """Return the interval that is the range of the polynomial defined by coefficients c, for domain interval x. >>> str_interval(polynomial(interval(0, 2), (-1, 3, -2))) '-3 to 0.125' >>> str_interval(polynomial(interval(1, 3), (1, -3, 2))) '0 to 10' >>> str_interval(polynomial(interval(0.5, 2.25), (10, 24, -6, -8, 3))) '18.0 to 23.0' """ "*** YOUR CODE HERE ***" if __name__ == "__main__": import doctest doctest.run_docstring_examples( sum_nonzero_with_generator_reduce, globals(), verbose=True)
Field('issuer'), Field('signature',signing=False) ] class Coin(Container): fields = [ Field('standardId'), Field('currencyId'), Field('denomination'), Field('keyId'), Field('serial'), Field('signature',signing=False) ] def setNewSerial(self): self.serial = occrypto.createSerial() if __name__ == "__main__": import doctest,sys if len(sys.argv) > 1 and sys.argv[-1] != '-v': name = sys.argv[-1] gb = globals() verbose = '-v' in sys.argv doctest.run_docstring_examples(gb[name],gb,verbose,name) else: doctest.testmod(optionflags=doctest.ELLIPSIS)
def test(target=None, show=False, onlydoctests=False, abort=False, verbose=True): """Run docstring examples and additional tests. Parameters ---------- target : function or string, optional Function or method to test. By default everything is tested. show : boolean, optional Show matplotlib windows during test run. They will be closed automatically. onlydoctests : boolean, optional Run test files in ../tests as well. abort : boolean, optional Return correct exit code, e.g. abort documentation build when a test fails. """ old_backend = plt.get_backend() if not show: plt.switch_backend("Agg") if target: if isinstance(target, str): # If target is a string, the code below will overwrite target # with the corresponding imported function, so that doctest works. import importlib mod_name, func_name = target.rsplit('.', 1) mod = importlib.import_module(mod_name) target = getattr(mod, func_name) import doctest doctest.run_docstring_examples(target, globals(), verbose=verbose, optionflags=doctest.ELLIPSIS, name=target.__name__) return try: import pytest except ImportError: raise ImportError("pytest is required to run test suite. " "Try 'sudo pip install pytest'.") cwd = join(realpath(__path__[0]), '..') excluded = [ # path... ] if onlydoctests: excluded.append("testing") cmd = ([ "-v", "-rsxX", "--color", "yes", "--doctest-modules", "--durations", 5, cwd ]) for directory in excluded: cmd.extend(["--ignore", join(cwd, directory)]) exitcode = pytest.main(cmd) plt.switch_backend(old_backend) plt.close('all') if abort: sys.exit(exitcode)
# Use doctest.run_docstring_examples to run print_first_n_powers_of_2's test cases, twice: # -. In a second mode that simply shows failed tests (default) # -. In a first mode that shows all test cases and their results as the cases execute # # More on docstring execution: # -. Test cases are signaled with initial ">>>" prompt strings. # -. Expected results are given after the commands to execute. # -. "Traceback" results are treated specially: # ..., with the ELLIPSIS option enabled, causes doctest to ignore Traceback details # when checking expected results. import doctest doctest.run_docstring_examples(print_first_n_powers_of_2, None, optionflags=doctest.ELLIPSIS) doctest.run_docstring_examples(print_first_n_powers_of_2, None, optionflags=doctest.ELLIPSIS, verbose=True) class Fib: def __init__(self, val_count=float('inf')): self.initial_val_count = val_count # def __iter__(self): self.val_count, self.result_queue = self.initial_val_count, [0, 1]
if __name__ == "__main__": # Test with doctests. Helpful to debug individual lab.py functions. import doctest _doctest_flags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS doctest.testmod(optionflags=_doctest_flags) #runs ALL doctests # Alternatively, can run the doctests JUST for specified function/methods, # e.g., for render_2d or any other function you might want. To do so, comment # out the above line, and uncomment the below line of code. This may be # useful as you write/debug individual doctests or functions. Also, the # verbose flag can be set to True to see all test results, including those # that pass. # doctest.run_docstring_examples(dig_2d, globals(), optionflags=_doctest_flags, verbose=False) # ********RENDER 2D TESTS******* # g = {'dimensions': (2, 4), # 'state': 'ongoing', # 'board': [['.', 3, 1, 0], # ['.', '.', 1, 0]], # 'mask': [[False, True, True, False], # [False, False, True, False]]} # game = {'dimensions': (2, 4), # 'state': 'ongoing', # 'board': [['.', 3, 1, 0], # ['.', '.', 1, 0]], # 'mask': [[True, True, True, False], # [False, False, True, False]]}
CFCs + Siloxanes + PseudoCompounds id_mEoS = [i.id for i in __all__] if __name__ == "__main__": import doctest # import timeit # def test(): for module in __all__: if "Air" not in module.__module__: continue print(module.__module__) inst = module() for eq in inst.eq[0:1]: if "__test__" in eq: inst.__doc__ += eq["__test__"] if inst._viscosity is not None: for eq in inst._viscosity: if "__test__" in eq: inst.__doc__ += eq["__test__"] if inst._thermal is not None: for eq in inst._thermal: if "__test__" in eq: inst.__doc__ += eq["__test__"] doctest.run_docstring_examples(inst, globs={module.__module__: module}) # timeit.timeit("test()", setup="from __main__ import test", number=3) # TODO: Add 1-propanol from 10.1016_j.fluid.2004.06.028 # TODO: Add 2-propanol from 10.1063/1.3112608
def task0_true(): """ >>> 2+2 4 """ def task0_false(): """ >>> 2+2 5 """ doctest.run_docstring_examples(task0_true, globals(), name="task0", verbose=True) doctest.run_docstring_examples(task0_false, globals(), name="task0", verbose=True) def task1(): """ >>> process("I have no problems") "Are you saying 'no' just to be negative?" >>> process("no") 'You are being a bit negative' >>> process("no")
fill the container. :param n: Number of times to iterate through the list of functions. :returns: An instance of the container filled with data from the returned by the functions. This helper function can be used in conjunction with a Toolbox to register a generator of filled containers, as individuals or population. >>> func_seq = [lambda:1 , lambda:'a', lambda:3] >>> initCycle(list, func_seq, n=2) [1, 'a', 3, 1, 'a', 3] See the :ref:`funky` tutorial for an example. """ return container(func() for _ in range(n) for func in seq_func) __all__ = ['initRepeat', 'initIterate', 'initCycle'] if __name__ == "__main__": import doctest import random random.seed(64) doctest.run_docstring_examples(initRepeat, globals()) random.seed(64) doctest.run_docstring_examples(initIterate, globals()) doctest.run_docstring_examples(initCycle, globals())
def update_event(self, inp=-1): self.set_output_val(0, doctest.run_docstring_examples(self.input(0), self.input(1), self.input(2), self.input(3), self.input(4), self.input(5)))
def test_path_to(): import doctest from minghu6.etc.path import path_to doctest.run_docstring_examples(path_to, locals())
ultraTB2.enable() # hack sys.argv so that it no longer contains this script's options sys.argv = scriptargs if opts.coverage: from coverage import coverage cov = coverage(data_suffix=True, branch=True) cov.start() if opts.doctest or opts.verbose_doctest or opts.doctest_for is not None: import doctest, atexit if opts.doctest_for is not None: # XXX: not sure how useful this is print 'running doctest for %s only' % opts.doctest_for atexit.register(lambda: doctest.run_docstring_examples(eval(opts.doctest_for).__doc__, globals(), verbose=opts.verbose_doctest)) else: atexit.register(lambda: doctest.testmod(verbose=opts.verbose_doctest)) if opts.pm: from debug.utils import enable_pm enable_pm() if opts.breakin: from debug import breakin breakin.enable() # execute the file execfile(source[0][1])
def tri_votes(votes): ''' >>> tri_votes([]) [] >>> tri_votes([1, 0]) [0, 1] >>> tri_votes([2, 1]) [1, 2] >>> tri_votes([0, 0, 0]) [0, 0, 0] >>> tri_votes([1, 1, 1]) [1, 1, 1] >>> tri_votes([2, 2, 2]) [2, 2, 2] >>> tri_votes([1, 1, 0]) [0, 1, 1] >>> tri_votes([2, 1, 0, 1, 0, 1, 2, 0, 1, 1, 0, 2, 2, 1, 0, 1, 1, 0]) [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2] ''' indices = [0, 0, len(votes) - 1] while indices[1] <= indices[2]: if not reordonner(votes, indices, 2, -1): reordonner(votes, indices, 0, +1) indices[1] += 1 return votes import doctest doctest.run_docstring_examples(tri_votes, globals())
############################################################################## # You can ignore everything after here def print_dict(d): # This method is just used to print dictionaries in key-alphabetical # order, and is only used for our documentation tests. You can ignore it. if isinstance(d, dict): print "{" + ", ".join("%r: %r" % (k, d[k]) for k in sorted(d)) + "}" else: print d def sort_pairs(l): # Print sorted list of pairs where the pairs are sorted. This is used only # for documentation tests. You can ignore it. return sorted(sorted(pair) for pair in l) if __name__ == "__main__": print import doctest for k, v in globals().items(): if k[0].isalpha(): if k.startswith('adv_') and not ADVANCED: continue a = doctest.run_docstring_examples(v, globals(), name=k) print "** END OF TEST OUTPUT" print
'MR' >>> coding_strand_to_AA("ATGCCCGCTTT") 'MPA' """ a="" #New List for results to be put into for i in range(0,len(dna),3): #Tell the function how long to look for codon = dna[i:i+3] #Tell the function where to look amino_acid = aa_table[codon] #assign value to amino_acid a = a + amino_acid #continue the string return a #actually return the amino acid def gene_finder(dna): """ Returns the amino acid sequences that are likely coded by the specified dna dna: a DNA sequence returns: a list of all amino acid sequences coded by the sequence dna. """ a=[] #creating an empty list threshold = longest_ORF_noncoding(dna,1500) #Assign Value to threshold Long_Orfs = len(longest_ORF(dna)) #assign value to Long_Orfs if Long_Orfs>threshold): #Compare values a.append(coding_strand_to_AA(dna)) #add to the list dna = load_seq("./data/X73525.fa") #obtaining genes print gene_finder(dna) #showing the list of Amino Acids if __name__ == "__main__": import doctest doctest.run_docstring_examples(coding_strand_to_AA, globals(),verbose=True) # doctest.
def map(self, fn): return self nil = nil() # Assignment hides the nil class; there is only one instance def read_eval_print_loop(): """Run a read-eval-print loop for the Brackulator language.""" global Pair, nil from scheme_reader import Pair, nil from scalc import calc_eval while True: try: src = tokenize(input('> ')) while len(src) > 0: expression = brack_read(src) print(calc_eval(expression)) except (SyntaxError, ValueError, TypeError, ZeroDivisionError) as err: print(type(err).__name__ + ':', err) except (KeyboardInterrupt, EOFError): # <Control>-D, etc. return if __name__ == '__main__': # if isvalid(tokenize('<(( [{}] [{}] ))>')): # print('valid') from doctest import run_docstring_examples run_docstring_examples(isvalid, globals(), True)
def test(): import doctest Documentation = type('Documentation', (object, ), {'__doc__': __doc__}) doctest.run_docstring_examples(Documentation, globals(), verbose=True)
# Test def fib_test(): assert fib(2) == 1, 'The 2nd Fibonacci number should be 1' assert fib(3) == 1, 'The 3nd Fibonacci number should be 1' assert fib(50) == 7778742049, 'Error at the 50th Fibonacci number' fib_test() # Doctest from doctest import run_docstring_examples def sum_naturals(n): """Return the sum of the first n natural numbers >>> sum_naturals(10) 55 >>> sum_naturals(100) 5050 """ total, k = 0, 1 while k <= n: total, k = total + k, k + 1 return total run_docstring_examples(sum_naturals, globals())
"""Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ count = 0 print(n) while n != 1: count += 1 if n % 2 != 0: n = (n * 3) + 1 print(n) else: n = n // 2 print(n) return count + 1 from doctest import run_docstring_examples run_docstring_examples(hailstone, globals(), True)