Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Implement a Python script to perform unit testing with pytest.

  1. User

    Implement a Python script to perform unit testing with pytest.

  2. GLM Assistant

    1. Understand the Goal: The user wants a Python script that demonstrates how to perform unit testing using the pytest framework.

    1. Identify Key Components:

      • Code to Test (SUT - System Under Test): I need a simple Python module with a few functions to test. Good candidates are:
        • A basic arithmetic function (e.g., add).
        • A function with edge cases (e.g., division by zero, string manipulation).
        • A class method (optional, but good for completeness).
      • Test Code (The Unit Tests): I need a separate file (or a clearly defined section) containing test functions that pytest can discover.
        • Use assert statements.
        • Demonstrate checking for exceptions (using pytest.raises).
      • Execution Instructions: Explain how to run the tests (command line).
      • Project Structure: Show how files should be organized.
    2. Drafting the Code - Step-by-Step:

      • Step 1: The Application Code (main.py or calculator.py) Let's create a simple calculator.py.

        def add(a, b):
            return a + b
        
        def subtract(a, b):
            return a - b
        
        def divide(a, b):
            if b == 0:
                raise ValueError("Cannot divide by zero")
            return a / b
        
      • Step 2: The Test Code (test_calculator.py) pytest looks for files starting with test_ or ending with _test.py.

        import pytest
        from calculator import add, subtract, divide
        
        def test_add_positive_numbers():
            assert add(2, 3) == 5
        
        def test_add_negative_numbers():
            assert add(-1, -1) == -2
        
        def test_subtract():
            assert subtract(5, 2) == 3
        
        def test_divide_by_zero():
            # Check if exception is raised
            with pytest.raises(ValueError):
                divide(10, 0)
        
      • Step 3: Putting it together in a single script representation (if requested, but usually better as separate files). However, the user asked for "a Python script". While unit testing is best done with separate files, for a demonstration, I can provide the code blocks clearly and explain how to set them up. I will provide a self-contained example where the logic is defined, then tested, but strictly speaking, pytest requires importable modules. The best approach is to provide two files in the answer and explain the directory structure.

    3. Refining the Content:

      • Prerequisites: Mention pip install pytest.
      • Structure:
        1. Directory layout.
        2. operations.py (The logic).
        3. test_operations.py (The tests).
      • Key Features to Demonstrate:
        • Simple assertion (assert).
        • Testing exceptions (pytest.raises).
        • Parameterization (Bonus: makes the answer better). Let's add @pytest.mark.parametrize. It shows the power of pytest.
    4. Writing the Response (Mental Draft):

      • Intro: Explain what pytest is and how to install it.
      • File 1: app.py (contains the code to test).
      • File 2: test_app.py (contains the tests).
      • Execution: Show the terminal command pytest -v.
      • Explanation: Break down what assert and pytest.raises do.
    5. Adding Parameterization (Self-Correction/Enhancement): Instead of writing test_add_1, test_add_2, I'll use parameterization. It's a very "pytest" way of doing things.

      @pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (0, 0, 0), (-1, 1, 0)])
      def test_add(a, b, expected):
          assert add(a, b) == expected
      
    6. Final Polish: Ensure the code is copy-pasteable and runnable. Make sure to explain why we separate the code (SUT) from the tests.

      • Code Logic: A simple math class/function is easiest to understand.
      • Error Handling: Include a division function that raises an error to show how to test errors.
    7. Constructing the Final Output:

      • Step 1: Installation.
      • Step 2: Project Structure.
      • Step 3: The Logic (operations.py).
      • Step 4: The Tests (test_operations.py).
      • Step 5: Running the tests.
      • Step 6: Explanation of features used (assert, raises, parametrize).

    This structure looks solid. It answers the prompt directly while providing best practices (separation of concerns) and advanced features (parameterization).

    (Self-Correction during drafting): The user asked for "a Python script". If I just give one file, pytest might get confused trying to import itself or run tests on the test code logic if not careful. The standard is two files. I will stick to the standard 2-file approach because it is the correct way to use pytest. I will explain that clearly.

    Let's double check the code syntax. pytest.raises(ValueError) matches raise ValueError(...). Correct. assert func() == expected. Correct. Command pytest or pytest -v. Correct.

    Ready to generate. Here is a complete guide and implementation for unit testing using pytest.

    To follow best practices, we will separate the code into two files:

    1. The Application Code: The logic you want to test.
    2. The Test Code: The script that verifies the logic.

    Prerequisites

    First, ensure you have pytest installed:

    pip install pytest
    

    Step 1: Create the Application Code

    Create a file named operations.py. This contains the actual logic we want to test.

    # operations.py
    
    def add(a, b):
        """Returns the sum of two numbers."""
        return a + b
    
    def subtract(a, b):
        """Returns the difference of two numbers."""
        return a - b
    
    def divide(a, b):
        """Divides a by b. Raises ValueError if b is zero."""
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b
    

    Step 2: Create the Test Script

    Create a file named test_operations.py. By default, pytest automatically discovers files that start with test_ or end with _test.py.

    # test_operations.py
    import pytest
    from operations import add, subtract, divide
    
    # 1. Basic Test
    def test_add_positive_numbers():
        assert add(2, 3) == 5
    
    def test_add_negative_numbers():
        assert add(-1, -1) == -2
    
    # 2. Testing Exceptions
    def test_divide_by_zero():
        # We assert that the following code raises a ValueError
        with pytest.raises(ValueError) as excinfo:
            divide(10, 0)
        
        # Optional: Check the error message content
        assert str(excinfo.value) == "Cannot divide by zero"
    
    # 3. Parameterized Tests (Running the same test with different data)
    # This is a powerful feature of pytest to avoid writing repetitive code.
    @pytest.mark.parametrize("a, b, expected", [
        (10, 2, 5),
        (0, 5, 0),
        (-10, 2, -5),
        (5, 2, 2.5),
    ])
    def test_divide_various_inputs(a, b, expected):
        assert divide(a, b) == expected
    
    # 4. Fixture (Setup/Teardown)
    # Fixtures are used to initialize data or objects needed for tests.
    @pytest.fixture
    def sample_numbers():
        return (10, 5)
    
    def test_subtract_with_fixture(sample_numbers):
        a, b = sample_numbers
        assert subtract(a, b) == 5
    

    Step 3: Run the Tests

    Open your terminal or command prompt, navigate to the folder containing these files, and run:

    pytest
    

    To see more details (verbose mode):

    pytest -v
    

    Explanation of Key Concepts Used

    1. assert: The core of testing. If the statement following assert is True, the test passes. If it is False, the test fails.
    2. pytest.raises: Used to verify that a function specifically throws an error (like trying to divide by zero). If the error is not thrown, the test fails.
    3. @pytest.mark.parametrize: Allows you to run a single test function multiple times with different input arguments. This keeps your code clean.
    4. @pytest.fixture: Used to set up data (like database connections or sample variables) that can be shared across multiple tests.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.