61 lines
1.4 KiB
Python
61 lines
1.4 KiB
Python
"""
|
|
Ejemplo de implementacion de test y pruebas de la funcion factorial
|
|
|
|
factorial(0) = 1
|
|
factorial(1) = 1
|
|
factorial(2) = 2
|
|
factorial(3) = 6
|
|
factorial(4) = 24
|
|
factorial(5) = 120
|
|
|
|
n! = n*(n-1)*(n-2)*...*1
|
|
"""
|
|
import unittest
|
|
|
|
class ErrorValorNegativo(Exception):
|
|
pass
|
|
|
|
# Esta función se puede definir de forma recursiva o iterativa
|
|
# Para este caso se define usando recursión.
|
|
def factorial(n):
|
|
if n < 0:
|
|
raise ErrorValorNegativo("Número Negativo")
|
|
elif n == 0:
|
|
return 1
|
|
elif n == 1:
|
|
return 1
|
|
else:
|
|
return n * factorial(n - 1)
|
|
|
|
class FactoriaTestCase(unittest.TestCase):
|
|
|
|
def test_factorial_numero_negativo(self):
|
|
self.assertRaises(ErrorValorNegativo, factorial, -1)
|
|
|
|
def test_factorial_0(self):
|
|
self.assertEqual(1, factorial(0))
|
|
|
|
def test_factorial_1(self):
|
|
self.assertEqual(1, factorial(1))
|
|
|
|
def test_factorial_2(self):
|
|
self.assertEqual(2, factorial(2))
|
|
|
|
def test_factorial_3(self):
|
|
self.assertEqual(6, factorial(3))
|
|
|
|
def test_factorial_4(self):
|
|
self.assertEqual(24, factorial(4))
|
|
|
|
def test_factorial_5(self):
|
|
self.assertEqual(120, factorial(5))
|
|
|
|
def test_factorial_6(self):
|
|
self.assertEqual(720, factorial(6))
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|
|
|
|
#for i in range(10):
|
|
# print(factorial(i))
|