【问题标题】:Nose Test Three Versions of the Same Function鼻子测试三个版本的相同功能
【发布时间】:2017-02-10 20:37:32
【问题描述】:

我有执行计算的同一函数的三个不同版本。给定相同的输入,所有三个将产生相同的输出。但是,不同之处在于这三个函数的实现方式不同,并且在不同情况下的表现可能更好/更差。

类比就像拥有 3 种不同的排序功能。如何使用鼻子测试编写单元测试以免重复自己?

def sort_a(array):
    """
    sort using and return
    """
    return sorted_array

def sort_b(array):
    """
    sort using and return
    """
    return sorted_array

def sort_c(array):
    """
    sort using and return
    """
    return sorted_array

我的测试可能如下所示:

class TestCore:
    def test_sort_a_positive_vals(self):
        # run test

    def test_sort_a_negative_vals(self):
        # run test

    def test_sort_b_positive_vals(self):
        # run test

    def test_sort_b_negative_vals(self):
        # run test

    def test_sort_c_positive_vals(self):
        # run test

    def test_sort_c_negative_vals(self):
        # run test

感觉这里有很多冗余。

【问题讨论】:

    标签: python unit-testing nose


    【解决方案1】:

    查看nose-parameterized

    from nose_parameterized import parameterized
    
    def square_exp(x):
        return x**2
    
    def square_mul(x):
        return x*x
    
    class SquareTest(TestCase):    
    
        @parameterized.expand([(square_exp,), (square_mul,)])
        def test_square(self, square_impl):
            self.assertEqual(square_impl(3), 9)
    

    【讨论】:

    • 但这需要添加nose_parameterized 包。有没有办法直接在鼻子里做到这一点?
    • 好吧,那又怎样?添加包有什么问题?
    • 试图减少依赖
    • 测试/开发依赖并不重要,无论如何你都应该将它们与运行时依赖分开。
    • 你是说不使用nose_parameterized就不可能做到这一点?
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多