|
| 1 | +#13 { Retos para Programadores } PRUEBAS UNITARIAS |
| 2 | + |
| 3 | +# Bibliography reference |
| 4 | +# Professional JavaScript for web developers by Matt Frisbie [Frisbie, Matt] (z-lib.org) |
| 5 | +#Python Notes for Professionals. 800+ pages of professional hints and tricks (GoalKicker.com) (Z-Library) |
| 6 | +# Additionally, I use GPT as a reference and sometimes to correct or generate proper comments. |
| 7 | + |
| 8 | +""" |
| 9 | +* EJERCICIO: |
| 10 | + * Crea una función que se encargue de sumar dos números y retornar |
| 11 | + * su resultado. |
| 12 | + * Crea un test, utilizando las herramientas de tu lenguaje, que sea |
| 13 | + * capaz de determinar si esa función se ejecuta correctamente. |
| 14 | + * |
| 15 | + * DIFICULTAD EXTRA (opcional): |
| 16 | + * Crea un diccionario con las siguientes claves y valores: |
| 17 | + * "name": "Tu nombre" |
| 18 | + * "age": "Tu edad" |
| 19 | + * "birth_date": "Tu fecha de nacimiento" |
| 20 | + * "programming_languages": ["Listado de lenguajes de programación"] |
| 21 | + * Crea dos test: |
| 22 | + * - Un primero que determine que existen todos los campos. |
| 23 | + * - Un segundo que determine que los datos introducidos son correctos. |
| 24 | + |
| 25 | + """ |
| 26 | + |
| 27 | +from datetime import datetime |
| 28 | + |
| 29 | +# Short for print |
| 30 | +log = print |
| 31 | + |
| 32 | +def assert_condition(condition, message, errors): |
| 33 | + """Custom assert function that logs an error instead of throwing.""" |
| 34 | + if not condition: |
| 35 | + log(message) |
| 36 | + errors.append(message) # Collect the error message |
| 37 | + |
| 38 | +def sum_numbers(a, b): |
| 39 | + """Returns the sum of two numbers, raises TypeError if arguments are not numbers.""" |
| 40 | + if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): |
| 41 | + raise TypeError('Both arguments must be numbers') |
| 42 | + return a + b |
| 43 | + |
| 44 | +def test_sum(errors): |
| 45 | + """Tests the sum_numbers function.""" |
| 46 | + assert_condition(sum_numbers(2, 3) == 5, 'Error: 2 + 3 should be 5', errors) |
| 47 | + assert_condition(sum_numbers(-1, 1) == 0, 'Error: -1 + 1 should be 0', errors) |
| 48 | + assert_condition(sum_numbers(0, 0) == 0, 'Error: 0 + 0 should be 0', errors) |
| 49 | + |
| 50 | + try: |
| 51 | + sum_numbers(2, '3') # Caught an error: Both arguments must be numbers |
| 52 | + except Exception as e: |
| 53 | + log('Caught an error:', e) # Log the caught error |
| 54 | + assert_condition(isinstance(e, TypeError), 'Error: Invalid argument type not handled', errors) |
| 55 | + assert_condition(str(e) == 'Both arguments must be numbers', 'Error: Argument type mismatch', errors) |
| 56 | + |
| 57 | + log('All sum tests have been executed.') # All sum tests have been executed. |
| 58 | + |
| 59 | +personal_info = { |
| 60 | + "name": "Niko Zen", |
| 61 | + "age": 41, |
| 62 | + "birth_date": "1983/08/08", |
| 63 | + "programming_languages": ["JavaScript", "Python", "Rust", "Ruby", "Java"] |
| 64 | +} |
| 65 | + |
| 66 | +def test_personal_info(obj, errors): |
| 67 | + """Tests the personal information object.""" |
| 68 | + if not obj: |
| 69 | + log('The obj is empty, skipping personal info tests.') |
| 70 | + return |
| 71 | + |
| 72 | + # Check that all fields exist |
| 73 | + assert_condition('name' in obj, 'Missing field "name"', errors) |
| 74 | + assert_condition('age' in obj, 'Missing field "age"', errors) |
| 75 | + assert_condition('birth_date' in obj, 'Missing field "birth_date"', errors) |
| 76 | + assert_condition('programming_languages' in obj, 'Missing field "programming_languages"', errors) |
| 77 | + |
| 78 | + # Check data types |
| 79 | + assert_condition(isinstance(obj['name'], str), '"name" must be a string', errors) |
| 80 | + assert_condition(isinstance(obj['age'], (int, float)), '"age" must be a number', errors) |
| 81 | + |
| 82 | + # Check if birth_date is a valid date |
| 83 | + try: |
| 84 | + birth_date = datetime.strptime(obj['birth_date'], '%Y/%m/%d') |
| 85 | + assert_condition(birth_date is not None, '"birth_date" must be a valid Date', errors) |
| 86 | + except ValueError: |
| 87 | + assert_condition(False, '"birth_date" must be a valid Date', errors) |
| 88 | + |
| 89 | + assert_condition(isinstance(obj['programming_languages'], list), '"programming_languages" is not an array', errors) |
| 90 | + |
| 91 | + # Validate each programming language |
| 92 | + for lang in obj['programming_languages']: |
| 93 | + assert_condition(isinstance(lang, str), 'Each language must be a string', errors) |
| 94 | + |
| 95 | + # Check fields are not empty |
| 96 | + assert_condition(len(obj['name']) > 0, '"name" cannot be empty', errors) |
| 97 | + assert_condition(obj['age'] > 0, '"age" must be greater than 0', errors) |
| 98 | + assert_condition(len(obj['birth_date']) > 0, '"birth_date" cannot be empty', errors) |
| 99 | + assert_condition(len(obj['programming_languages']) > 0, '"programming_languages" should have at least one language', errors) |
| 100 | + |
| 101 | + log('All personal info tests have been executed.') # All personal info tests have been executed. |
| 102 | + |
| 103 | +nikita_info = {} |
| 104 | + |
| 105 | +errors = [] |
| 106 | +test_sum(errors) |
| 107 | +test_personal_info(personal_info, errors) # Should pass |
| 108 | +test_personal_info(nikita_info, errors) # The obj is empty, skipping personal info tests. |
| 109 | + |
| 110 | +# Log all collected errors at the end |
| 111 | +if errors: |
| 112 | + log('Errors encountered during tests:') |
| 113 | + for error in errors: |
| 114 | + log(error) |
| 115 | +else: |
| 116 | + log('No errors encountered during tests.') # No errors encountered during tests. |
0 commit comments