Python unit test: Check prime number
1. Unit Test for Prime Number Checker
Write a Python unit test program to check if a given number is prime or not.
Sample Solution:
Python Code:
Sample Output:
Ran 2 tests in 0.002s OK Non prime numbers: [4, 6, 8, 10, 12, 14, 16, 18, 20] Prime numbers: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
Ran 2 tests in 0.002s FAILED (failures=2) Non prime numbers: [4, 6, 8, 9, 11, 12, 14, 17, 16, 18, 20] Prime numbers: [2, 3, 4, 8, 11, 13, 17, 19, 23, 30, 31]
Explanation:
In the above exercise,
We define a function is_prime() that checks if a given number is prime. Then, we create a test case class PrimeNumberTestCase that subclasses unittest.TestCase. Inside this class, we define multiple test methods using the test_ prefix. Each test method uses the assertion methods provided by unittest.TestCase to check if the expected condition is true or false.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python unit test program using unittest that verifies a prime-check function returns True for known prime numbers and False for non-prime numbers.
- Write a Python unit test program that tests edge cases for a prime function such as 0, 1, and negative numbers.
- Write a Python unit test program that parameterizes multiple inputs to check if the prime function correctly identifies primes over a range.
- Write a Python unit test program that asserts the performance of the prime-check function on large input values within an acceptable time limit.
Go to:
Previous: Python Unit test Exercises Home.
Next: Check list sorting.
Python Code Editor :
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.