[英]testing whether the data is matching upto 4 decimal places using pytest and publish report by using it
您可以使用 decimal.Decimal 将数字表示为特定的小数位数,然后简单地在 pytest 中断言。
import decimal
four_decimal= decimal.Decimal('0.0001')
def test():
# get your data from database or something, if they are currently
# representing as string, do not convert to float first but use
# decimal.Decimal right away
# just to show how to get the specific number of decimal places
# usually you dont want to go float->decimal if you dont have to
d = decimal.Decimal(1/3.0).quantize(four_decimal)
d2 = decimal.Decimal("3214143214214321.3134").quantize(four_decimal)
d3 = decimal.Decimal(3214143214214321/3).quantize(four_decimal)
d4 = d2 - d - d3 + d3 + d
# run with -s to see what's going on
print(d)
print(d2)
print(d3)
print(d4)
# and now just assert
assert d != d2
assert d2 != 1/3.0
assert d2 == d4
请注意, quantize
方法也可以采用参数rounding
来指定如何舍入到小数点后 4 位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.