繁体   English   中英

数值回归测试

[英]Numerical regression testing

我正在研究一种科学计算代码(用C ++编写),除了对较小的组件进行单元测试之外,我还想通过比较一个“已知的好”来对一些数字输出进行回归测试。从以前的修订回答。 我想要一些功能:

  • 允许将数字与指定的容差进行比较(对于舍入误差和更宽松的期望)
  • 能够区分整数,双精度等,并在必要时忽略文本
  • 格式良好的输出,以告诉出错的地方和位置:在多列数据表中,只显示不同的列条目
  • 返回EXIT_SUCCESSEXIT_FAILURE具体取决于文件是否匹配

是否有任何好的脚本或应用程序可以执行此操作,或者我是否必须在Python中自行编写以读取和比较输出文件? 当然,我不是第一个有这种要求的人。

您应该选择PyUnit ,它现在是名称unittest的标准库的一部分。 它支持您要求的一切。 例如,使用assertAlmostEqual()完成容差检查。

ndiff实用程序可能接近你正在寻找的东西:它就像diff一样,但它会将数字的文本文件与所需的容差进行比较。

我最终写了一个Python脚本来做我想要的更多或更少。

#!/usr/bin/env python

import sys
import re
from optparse import OptionParser
from math import fabs

splitPattern = re.compile(r',|\s+|;')

class FailObject(object):
    def __init__(self, options):
        self.options = options
        self.failure = False

    def fail(self, brief, full = ""):
        print ">>>> ", brief
        if options.verbose and full != "":
            print "     ", full
        self.failure = True


    def exit(self):
        if (self.failure):
            print "FAILURE"
            sys.exit(1)
        else:
            print "SUCCESS"
            sys.exit(0)

def numSplit(line):
    list = splitPattern.split(line)
    if list[-1] == "":
        del list[-1]

    numList = [float(a) for a in list]
    return numList

def softEquiv(ref, target, tolerance):
    if (fabs(target - ref) <= fabs(ref) * tolerance):
        return True

    #if the reference number is zero, allow tolerance
    if (ref == 0.0):
        return (fabs(target) <= tolerance)

    #if reference is non-zero and it failed the first test
    return False

def compareStrings(f, options, expLine, actLine, lineNum):
    ### check that they're a bunch of numbers
    try:
        exp = numSplit(expLine)
        act = numSplit(actLine)
    except ValueError, e:
#        print "It looks like line %d is made of strings (exp=%s, act=%s)." \
#                % (lineNum, expLine, actLine)
        if (expLine != actLine and options.checkText):
            f.fail( "Text did not match in line %d" % lineNum )
        return

    ### check the ranges
    if len(exp) != len(act):
        f.fail( "Wrong number of columns in line %d" % lineNum )
        return

    ### soft equiv on each value
    for col in range(0, len(exp)):
        expVal = exp[col]
        actVal = act[col]
        if not softEquiv(expVal, actVal, options.tol):
            f.fail( "Non-equivalence in line %d, column %d" 
                    % (lineNum, col) )
    return

def run(expectedFileName, actualFileName, options):
    # message reporter
    f = FailObject(options)

    expected  = open(expectedFileName)
    actual    = open(actualFileName)
    lineNum   = 0

    while True:
        lineNum += 1
        expLine = expected.readline().rstrip()
        actLine = actual.readline().rstrip()

        ## check that the files haven't ended,
        #  or that they ended at the same time
        if expLine == "":
            if actLine != "":
                f.fail("Tested file ended too late.")
            break
        if actLine == "":
            f.fail("Tested file ended too early.")
            break

        compareStrings(f, options, expLine, actLine, lineNum)

        #print "%3d: %s|%s" % (lineNum, expLine[0:10], actLine[0:10])

    f.exit()

################################################################################
if __name__ == '__main__':
    parser = OptionParser(usage = "%prog [options] ExpectedFile NewFile")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="Don't print status messages to stdout")

    parser.add_option("--check-text",
                      action="store_true", dest="checkText", default=False,
                      help="Verify that lines of text match exactly")

    parser.add_option("-t", "--tolerance",
                      action="store", type="float", dest="tol", default=1.e-15,
                      help="Relative error when comparing doubles")

    (options, args) = parser.parse_args()

    if len(args) != 2:
        print "Usage: numdiff.py EXPECTED ACTUAL"
        sys.exit(1)

    run(args[0], args[1], options)

我知道我参加派对已经很晚了,但几个月前我写了nrtest实用程序,试图让这个工作流更容易。 听起来它也可能对你有所帮助。

这是一个快速概述。 每个测试都由其输入文件及其预期的输出文件定义。 执行后,输出文件存储在便携式基准测试目录中。 然后,第二步将此基准与参考基准进行比较。 最近的更新启用了用户扩展,因此您可以为自定义数据定义比较函数。

我希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM