0
0
PyTesttesting~15 mins

Comparing values (equality, inequality) in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify equality and inequality comparisons between two values
Preconditions (2)
Step 1: Create a test function named test_compare_values
Step 2: Inside the function, define two variables: a = 10 and b = 20
Step 3: Assert that a is not equal to b
Step 4: Assert that a is less than b
Step 5: Assert that b is greater than a
Step 6: Define another variable c = 10
Step 7: Assert that a is equal to c
✅ Expected Result: All assertions pass without errors, confirming correct equality and inequality comparisons.
Automation Requirements - pytest
Assertions Needed:
assert a != b
assert a < b
assert b > a
assert a == c
Best Practices:
Use descriptive test function names
Keep assertions simple and clear
Avoid hardcoding values multiple times by using variables
Run tests with pytest command line for clear output
Automated Solution
PyTest
import pytest

def test_compare_values():
    a = 10
    b = 20
    c = 10

    assert a != b, f"Expected {a} to not equal {b}"
    assert a < b, f"Expected {a} to be less than {b}"
    assert b > a, f"Expected {b} to be greater than {a}"
    assert a == c, f"Expected {a} to equal {c}"

This test function test_compare_values defines three variables a, b, and c with values 10, 20, and 10 respectively.

It then uses assert statements to check:

  • Equality: a == c confirms both have the same value.
  • Inequality: a != b confirms they differ.
  • Less than and greater than: a < b and b > a confirm the relative order.

Each assertion includes a message to help understand failure if it occurs.

Running this with pytest will show a pass if all conditions hold true.

Common Mistakes - 3 Pitfalls
{'mistake': "Using assignment operator '=' instead of equality '==' in assertions", 'why_bad': "This causes syntax errors or unintended behavior because '=' assigns values, it does not compare.", 'correct_approach': "Always use '==' to compare values for equality in assertions."}
Not providing assertion messages
Comparing variables without initializing them
Bonus Challenge

Now add data-driven testing with 3 different pairs of values to compare equality and inequality.

Show Hint