简体   繁体   中英

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 ).

We have two functions, is_prime and 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. In this case, the function print_next_prime is one unit, and is_prime is another. 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.

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

#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 . There are other examples as test_is_four_non_prime , test_is_zero_not_prime . In the same way, you can write tests for other function 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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