Verify Your Function with Pytest

Objective: Verify Your Function with Pytest

Let's begin by reviewing our objective.

Our goal is to create a Python script operations.py with a function multiply(x, y) that returns the product of x and y. We will then create a test_operations.py file with a pytest test function test_multiply_positive_numbers that uses assert to verify multiply(3, 4) returns 12.

Check Spec: Run the Tests

Next, we'll run pytest to see the failing tests. This confirms the engineering specification we need to meet.

Run the command pytest in your terminal.

Test Results:

  • test_multiply_positive_numbers

As expected, the test fails because the multiply function is not yet implemented.

Implement: `operations.py`

Now, let's build the solution by following the TODO comments in the skeleton code.

Step by step checklist:

  1. Implement the logic inside the multiply function to calculate the product of the two input parameters.
  2. Return the calculated product from the function.

The following documentation sections are going to be helpful:

  • Defining a Python Function

Implement: `test_operations.py`

Let's continue building the solution.

Step by step checklist:

  1. Create a new file named test_operations.py in the same directory as operations.py.
  2. Add the test function test_multiply_positive_numbers to the test_operations.py file.
  3. Inside the test function, add the assert statement to check if calling multiply(3, 4) returns the value 12.

The following documentation sections are going to be helpful:

  • Introduction to Testing with Pytest
  • Writing a Basic Test Function

Validate: Run the Tests Again

With the code in place, let's run the tests again to validate our work.

Run the command pytest in your terminal.

Test Results:

  • test_multiply_positive_numbers All tests passed!

Great job! You've successfully implemented the multiply function and written your first basic pytest test to verify its correctness.

Documentation

Python Functions and Basic Testing Cheat Sheet

This document provides a quick reference for defining Python functions and writing basic tests using pytest.

Defining a Python Function

A function is a block of code that performs a specific task. You define a function using the def keyword.

def function_name(parameter1, parameter2):
    """
    This is a docstring. It explains what the function does.
    Args:
        parameter1: Description of the first parameter.
        parameter2: Description of the second parameter.
    Returns:
        Description of the value the function returns.
    """
    # Function body starts here, indented
    # Code to perform the task
    result = parameter1 + parameter2
    return result # Use return to send a value back
  • def: Keyword to start a function definition.
  • function_name: Choose a descriptive name.
  • (parameter1, parameter2): Input values the function accepts. Can be zero or more.
  • :: Marks the end of the function header.
  • Docstring ("""..."""): Explains the function's purpose, arguments (Args), and return value (Returns). Good practice for documentation.
  • Indented block: The code that runs when the function is called.
  • return: Sends a value back from the function. If return is not used, the function returns None by default.

Image showing the structure of a Python function definition with labels for def, name, parameters, colon, docstring, indented body, and return statement.

Introduction to Testing with Pytest

Testing helps verify that your code works as expected. pytest is a framework for writing and running tests in Python.

  • Test files should be named starting with test_ or ending with _test.py.
  • Test functions inside these files should be named starting with test_.

GIF showing the pytest command being run in a terminal.

Writing a Basic Test Function

A test function calls the code you want to test and uses assert statements to check if the results are correct.

# Example test function structure
def test_something():
    # Call the function you are testing
    actual_result = your_function(input_value)
    # Use assert to check if the actual result matches the expected result
    assert actual_result == expected_result
  • def test_...: Defines a test function. pytest finds and runs functions named this way.
  • assert condition: Checks if condition is True. If it's False, the test fails.

Image showing a simple pytest test function using assert to compare a function call result to an expected value.

Testing Multiple Scenarios

You can include multiple assert statements within a single test function to check different inputs or cases for the same function.

# Example test function with multiple assertions
def test_example_function():
    # Test case 1: Positive input
    assert example_function(5) == 25

    # Test case 2: Negative input
    assert example_function(-3) == 9

    # Test case 3: Zero input
    assert example_function(0) == 0

This approach helps ensure your function handles various situations correctly. If any assert fails, the test function stops and is marked as failed.

Image showing a pytest test function with several assert lines, each checking a different input value for the function being tested.

Running Pytest

Navigate to your project directory in the terminal and run the command:

pytest

pytest will discover and run your test files and functions, reporting the results (PASSED, FAILED, etc.).

GIF showing pytest output in the terminal, showing both PASSED and FAILED states.