Skip to content

Instantly share code, notes, and snippets.

@awesmubarak
Created December 6, 2024 13:49
Show Gist options
  • Save awesmubarak/837a3258b1eacc9b2f9ee2fcffdf24c5 to your computer and use it in GitHub Desktop.
Save awesmubarak/837a3258b1eacc9b2f9ee2fcffdf24c5 to your computer and use it in GitHub Desktop.

Testing

This is what a simple python test would look like:

def add_numbers(a, b):
    return a + b

def test_add_numbers():
    assert add_numbers(2, 2) == 4
    assert add_numbers(-1, 1) == 0
    assert add_numbers(0, 0) == 0
   
test_add_numbers()

Try and run it and see what happens. Now change the code to use a minus - notice what happens.

Tasks

  1. Write a function sub_numbers(a, b) that subtracts two numbers. Write assertions to verify it handles positive numbers, negative numbers, and zeros correctly.
  2. Create a function capitalize_words(text) that takes a string and capitalizes the first letter of each word. Write assertions to check it works with different word combinations and spaces.
  3. Build a function find_largest(numbers) that finds the largest number in a list. Verify it works with positive numbers, negative numbers, single-item lists, and empty lists.
  4. Create an is_valid_email(email) function that checks if a string looks like an email address (just check for @ and at least one . after it). Write assertions to test valid and invalid email patterns.
  5. Write a divide_numbers(a, b) function that divides two numbers but needs to handle division by zero appropriately. Your assertions should verify both successful division and proper error handling.
  6. Create a calculate_grade_average(grades) function that takes a dictionary of subject:grade pairs and returns the average. Assert it handles regular grades, single subjects, and empty dictionaries correctly.
  7. Write a clean_text(text) function that takes a string and normalizes spaces (no double spaces, no leading/trailing spaces). Assert it handles normal text, empty strings, multiple spaces, and non-string inputs appropriately.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment