Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Using the Assert Statement in Pytest: Validating Test Conditions | Mastering Pytest Framework
Python Structural Programming

bookUsing the Assert Statement in Pytest: Validating Test Conditions

The assert statement is used to verify that a condition is True. If the condition is False, the test fails. Pytest enhances the basic assert by providing detailed output when the assertion fails, making it easier to understand what went wrong.

Simple Assertions:

Check that the condition is evaluated as True. If it is evaluated as False, Pytest raises an AssertionError and marks the test as failed.

assert condition

In the next example, word.isupper() should return True if word is in uppercase. If not, the test fails.

def test_is_uppercase():
    word = "HELLO"
    assert word.isupper()

Comparative Assertions:

assert actual == expected

To verify that the result of an operation (actual) matches the expected value.

def test_addition():
    assert add(5, 3) == 8, "The addition function should return 8 for 5 + 3"

Here, the add function is tested to ensure it correctly adds two numbers. The message after the comma provides additional context if the test fails.

Assertions with Detailed Feedback:

assert condition, message

To provide a custom error message that displays when the assertion fails, offering more insight into the issue.

def test_multiply():
    result = multiply(2, 5)
    assert result == 10, f"Expected 10, got {result}"

This assertion checks whether the multiply function returns 10 when multiplying 2 and 5. The custom message clarifies the expected outcome versus the actual result if the test fails.

Assertions for Exceptions:

pytest.raises(ExceptionType)

To confirm that a certain exception is raised by a block of code.

import pytest

def divide(x, y):
    return x / y

def test_divide_zero():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

This test ensures that dividing by zero raises a ZeroDivisionError. It’s essential for testing error handling in your code.

Advanced Assertions:

Use assertions to check more complex conditions, such as contents of lists, dictionaries, or more nuanced states in your application.

def test_inventory():
    inventory = ["apple", "banana", "cherry"]
    assert "banana" in inventory, "Banana should be in the inventory"

This test checks for the presence of an item in a list, providing clear feedback if the item is missing.

Завдання

Swipe to start coding

Write pytest test functions to validate the following conditions:

  • Check that calling is_even(4) returns True.
  • Check that calling add(2, 3) equals 5.
  • Check that calling multiply(3, 7) returns 21, and provide a detailed error message if the assertion fails.
  • Check that calling divide(10, 0) raises a ZeroDivisionError.
  • Check that the string 'grape' exists in the fruit_list.

Write each test as a separate function using the test_ prefix. Use assert statements for validation. For the exception, use the pytest.raises context manager. For the detailed message, use an f-string that shows the actual result if the assertion fails.

Рішення

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

Can you explain how pytest improves the output of failed assertions?

What are some best practices for writing custom error messages in assertions?

How do I use pytest to test for exceptions in my code?

close

bookUsing the Assert Statement in Pytest: Validating Test Conditions

Свайпніть щоб показати меню

The assert statement is used to verify that a condition is True. If the condition is False, the test fails. Pytest enhances the basic assert by providing detailed output when the assertion fails, making it easier to understand what went wrong.

Simple Assertions:

Check that the condition is evaluated as True. If it is evaluated as False, Pytest raises an AssertionError and marks the test as failed.

assert condition

In the next example, word.isupper() should return True if word is in uppercase. If not, the test fails.

def test_is_uppercase():
    word = "HELLO"
    assert word.isupper()

Comparative Assertions:

assert actual == expected

To verify that the result of an operation (actual) matches the expected value.

def test_addition():
    assert add(5, 3) == 8, "The addition function should return 8 for 5 + 3"

Here, the add function is tested to ensure it correctly adds two numbers. The message after the comma provides additional context if the test fails.

Assertions with Detailed Feedback:

assert condition, message

To provide a custom error message that displays when the assertion fails, offering more insight into the issue.

def test_multiply():
    result = multiply(2, 5)
    assert result == 10, f"Expected 10, got {result}"

This assertion checks whether the multiply function returns 10 when multiplying 2 and 5. The custom message clarifies the expected outcome versus the actual result if the test fails.

Assertions for Exceptions:

pytest.raises(ExceptionType)

To confirm that a certain exception is raised by a block of code.

import pytest

def divide(x, y):
    return x / y

def test_divide_zero():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

This test ensures that dividing by zero raises a ZeroDivisionError. It’s essential for testing error handling in your code.

Advanced Assertions:

Use assertions to check more complex conditions, such as contents of lists, dictionaries, or more nuanced states in your application.

def test_inventory():
    inventory = ["apple", "banana", "cherry"]
    assert "banana" in inventory, "Banana should be in the inventory"

This test checks for the presence of an item in a list, providing clear feedback if the item is missing.

Завдання

Swipe to start coding

Write pytest test functions to validate the following conditions:

  • Check that calling is_even(4) returns True.
  • Check that calling add(2, 3) equals 5.
  • Check that calling multiply(3, 7) returns 21, and provide a detailed error message if the assertion fails.
  • Check that calling divide(10, 0) raises a ZeroDivisionError.
  • Check that the string 'grape' exists in the fruit_list.

Write each test as a separate function using the test_ prefix. Use assert statements for validation. For the exception, use the pytest.raises context manager. For the detailed message, use an f-string that shows the actual result if the assertion fails.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3
single

single

some-alt