单元测试以发现错误的实现

时间:2020-07-28 10:26:15

标签: python unit-testing

前几天,我正在观看Scott Wlaschin的有关基于属性的单元测试的演讲,我认为那很棒。对我来说,这是一个全新的概念,但是很容易理解。如果有兴趣,您可以找到the lecture on Youtube

Scott经历的一个例子是对简单加法函数的错误实现以及允许捕获它的基于属性的测试。使用了加法的标准属性-可交换,分布等。

所有这些都很好,但是我在想,如果我决定以这种奇怪的方式实现加法呢?

import random
from math import log

def technically_not_a_sum(x, y):
    i = random.randint(1e10, 1e15)
    t = i**x * i**y
    return log(t, i)

从技术上讲,添加操作没有实现或实现,而是以一种非常恐怖和低效的方式进行。但是,它可以顺利通过所有基于属性的测试。

def test_is_commutative():
    x = round(random.random()*10, 5)
    y = round(random.random()*10, 5)
    
    assert round(technically_not_a_sum(x, y), 5) == round(technically_not_a_sum(y, x), 5)
    
def test_is_associative():
    x = round(random.random()*10, 5)
    y = round(random.random()*10, 5)
    z = round(random.random()*10, 5)
    
    assert round(technically_not_a_sum(x, y) + z, 5) == round(technically_not_a_sum(y, z) + x, 5)
    
def test_is_identity():
    x = round(random.random()*10, 5)
    y = 0
    
    assert round(technically_not_a_sum(x, y), 5) == x
    
def test_is_distributive():
    x = round(random.random()*10, 5)
    y = round(random.random()*10, 5)
    z = round(random.random()*10, 5)

    assert round(technically_not_a_sum(x, y)*z, 5) == round(x*z + y*z, 5)

是否有任何方法可以通过单元测试来捕获此特定实现?还是这不是单元测试的正确问题?

0 个答案:

没有答案