简体   繁体   English

如何进行Python单元测试

[英]How to Python Unit Test

I'm tying to get into unit testing for python and I'm having trouble with finding a way to tackel the following problem ( source ). 我想进入python的单元测试,但在寻找解决以下问题的方法时遇到了麻烦( )。

We have two functions, is_prime and print_next_prime. 我们有两个函数,is_prime和print_next_prime。 If we wanted to testprint_next_prime, we would need to be sure that is_prime is correct, asprint_next_prime makes use of it. 如果我们想测试print_next_prime,则需要确保is_prime是正确的,asprint_next_prime会使用它。 In this case, the function print_next_prime is one unit, and is_prime is another. 在这种情况下,函数print_next_prime是一个单元,而is_prime是另一个单元。 Since unit tests test only a single unit at a time, we would need to think carefully about how we could accurately test print_next_prime. 由于单元测试一次只能测试一个单元,因此我们需要仔细考虑如何才能准确地测试print_next_prime。

def is_prime(number):
    """Return True if *number* is prime."""
    for element in range(number):
        if number % element == 0:
            return False

    return True

def print_next_prime(number):
    """Print the closest prime number larger than *number*."""
    index = number
    while True:
        index += 1
        if is_prime(index):
            print(index) 

How would you write a unit test for both of these methods? 您将如何为这两种方法编写单元测试? Unfortunately the source never gives an answer to this question. 不幸的是,消息来源从未给出这个问题的答案。

The code has been fixed at the later parts of that blog , first you have to define the is_prime 该代码已在该博客的后续部分修复,首先您必须定义is_prime

#primes.py

def is_prime(number):
    """Return True if *number* is prime."""
    if number <= 1:
        return False

    for element in range(2, number):
        if number % element == 0:
            return False

    return True

This is the unit test case for one case test_is_five_prime . 这是一个案例test_is_five_prime的单元测试案例。 There are other examples as test_is_four_non_prime , test_is_zero_not_prime . 还有其他示例,例如test_is_four_non_primetest_is_zero_not_prime In the same way, you can write tests for other function print_next_prime . 同样,您可以为其他函数print_next_prime编写测试。 You could try in the same way. 您可以用相同的方式尝试。

#test_primes.py

import unittest
from primes import is_prime

class PrimesTestCase(unittest.TestCase):
    """Tests for `primes.py`."""

    def test_is_five_prime(self):
        """Is five successfully determined to be prime?"""
        self.assertTrue(is_prime(5))

if __name__ == '__main__':
    unittest.main()

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

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