0

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.

3
  • 1
    The is_prime function's broken as it'll attempt to divide by zero. Commented Mar 22, 2017 at 16:19
  • Yes, that is true. This is just an example for setting up unit tests. It is meant to fail on that part. Commented Mar 22, 2017 at 16:20
  • The source has explained unit tests. Read that until the end, there is correct implementation of is_prime function. Commented Mar 22, 2017 at 17:26

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.