import unittest
import sys
def is_prime(n):
"""Checks if a number is prime."""
if not isinstance(n, int) or n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def sum_of_first_n_primes(n):
"""Calculates the sum of the first n prime numbers."""
if not isinstance(n, int) or n <= 0:
return 0
count = 0
num = 2
prime_sum = 0
while count < n:
if is_prime(num):
prime_sum += num
count += 1
num += 1
return prime_sum
class TestPrimeFunctions(unittest.TestCase):
def test_is_prime_small_primes(self):
self.assertTrue(is_prime(2))
self.assertTrue(is_prime(3))
self.assertTrue(is_prime(5))
self.assertTrue(is_prime(7))
self.assertTrue(is_prime(11))
def test_is_prime_small_composites(self):
self.assertFalse(is_prime(1))
self.assertFalse(is_prime(4))
self.assertFalse(is_prime(6))
self.assertFalse(is_prime(8))
self.assertFalse(is_prime(9))
def test_is_prime_edge_cases(self):
self.assertFalse(is_prime(0))
self.assertFalse(is_prime(-1))
self.assertTrue(is_prime(101))
def test_sum_of_first_n_primes_small_n(self):
self.assertEqual(sum_of_first_n_primes(1), 2)
self.assertEqual(sum_of_first_n_primes(2), 5)
self.assertEqual(sum_of_first_n_primes(3), 10)
self.assertEqual(sum_of_first_n_primes(4), 17)
self.assertEqual(sum_of_first_n_primes(5), 28)
def test_sum_of_first_n_primes_zero_n(self):
self.assertEqual(sum_of_first_n_primes(0), 0)
def test_sum_of_first_n_primes_larger_n(self):
self.assertEqual(sum_of_first_n_primes(10), 129)
def test_sum_of_first_n_primes_none(self):
self.assertEqual(sum_of_first_n_primes(None), 0)
def test_is_prime_none(self):
self.assertEqual(is_prime(None), False)
def test_sum_of_first_n_primes_string(self):
self.assertEqual(sum_of_first_n_primes(''), 0)
def test_is_prime_string(self):
self.assertEqual(is_prime(''), False)
def test_sum_of_first_n_primes_boolean(self):
self.assertEqual(sum_of_first_n_primes(False), 0)
def test_is_prime_boolean(self):
self.assertEqual(is_prime(False), False)
class CustomTestResult(unittest.TestResult):
def __init__(self, stream):
super().__init__()
self.stream = stream
def addSuccess(self, test):
self.stream.write("*** test_passed ***\n")
def addFailure(self, test, err):
self.stream.write("*** assertion_failed ***\n")
def addError(self, test, err):
error_message = str(err[1])
self.stream.write(
f"*** exception_raised ***, error message: {error_message}\n")
class CustomTestRunner(unittest.TextTestRunner):
def run(self, test):
result = CustomTestResult(self.stream)
test(result)
return result
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestPrimeFunctions)
runner = CustomTestRunner(stream=sys.stdout)
runner.run(suite)