我花时间看了看
doctest
并提出了以下建议。它似乎对我的
float
s是格式化的,但是我非常感谢您对如何使它更健壮、如何传递所有选项等方面的建议(在我的例子中,这是特别容易的,因为
全部的
我的docstring测试将是float或float列表,因此我没有测试其他用例。)
import doctest
def extractsigfmt(numstr):
"""Find a standard formatter from a string.
From a string representing a float, find the number of
significant digits and return a string formatter to standardize
its representation.
"""
# Pull out the digits term, removing newline and accounting
# for either E or e in exponential notation
digs = numstr.lower().rstrip('\n').split('e')[0]
# Separate from decimal point, removing sign and leading zeros
res = digs.split('.')
if len(res) == 1:
l, r = res, ''
else:
l, r = res
l = l.lstrip(' -+0')
nsig = len(l) + len(r)
# Create a standardized exponential formatter
fmt = '{:+' + '{0:d}.{1:d}'.format(nsig+6,nsig-1) + 'e}'
return fmt
# Create new OutputChecker class
class fltOutputChecker(doctest.OutputChecker):
"""OutputChecker customized for floats.
Overrides check_output to compare standardized floats.
"""
def check_output(self,want,got,optionflags):
"""Check whether actual output agrees with expected.
Return True iff the actual output agrees with the expected
output within the number of significant figures of the
expected output.
"""
fmt = extractsigfmt(want)
want_std = fmt.format(float(want))
got_std = fmt.format(float(got))
return (want_std == got_std)
def testfun(n):
"""Function to test new OutputChecker on.
>>> testfun(0)
-6.96239965190e+05
>>> testfun(1)
8.01977741e-10
>>> testfun(2)
-95019.5943231
>>> testfun(3)
0.164195952060
>>> testfun(4)
-0.687329742959e-3
>>> testfun(5)
0.876543210e3
"""
testlist = [-696239.9651898777,8.01977740740741e-10,
-95019.59432308903,0.1641959520603997,
-0.0006873297429586108,876.54320956893102]
return testlist[n]
# Construct and run doctest on this function
finder = doctest.DocTestFinder()
dtlist = finder.find(testfun)
checker = fltOutputChecker()
runner = doctest.DocTestRunner(checker)
for dt in dtlist:
runner.run(dt)
results = runner.summarize(verbose=True)