0
0
PyTesttesting~5 mins

Comparing values (equality, inequality) in PyTest

Choose your learning style9 modes available
Introduction

We compare values to check if things are the same or different. This helps us find mistakes in our code.

Check if a function returns the expected result.
Verify that two variables hold the same value after some operation.
Ensure that an error message is not equal to an empty string.
Confirm that a list length is not equal to zero after adding items.
Test if user input matches the required format or value.
Syntax
PyTest
assert actual == expected  # checks if values are equal
assert actual != unexpected  # checks if values are not equal

Use == to check if two values are exactly the same.

Use != to check if two values are different.

Examples
This test passes because 5 is equal to 5.
PyTest
def test_equal():
    assert 5 == 5
This test passes because 5 is not equal to 3.
PyTest
def test_not_equal():
    assert 5 != 3
Checks if two strings are the same.
PyTest
def test_string_equal():
    assert 'hello' == 'hello'
Checks if two strings are different.
PyTest
def test_string_not_equal():
    assert 'hello' != 'world'
Sample Program

This sample has two tests. The first checks if adding 2 and 3 equals 5. The second checks that adding 2 and 2 does not equal 5.

PyTest
import pytest

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

def test_add_equal():
    result = add(2, 3)
    assert result == 5

def test_add_not_equal():
    result = add(2, 2)
    assert result != 5
OutputSuccess
Important Notes

Always use assert in pytest to compare values.

Clear and simple comparisons help find bugs quickly.

Use meaningful variable names to make tests easy to read.

Summary

Use == to check if values are equal.

Use != to check if values are not equal.

Assertions help confirm your code works as expected.