Introduction
We compare values to check if things are the same or different. This helps us find mistakes in our code.
We compare values to check if things are the same or different. This helps us find mistakes in our code.
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.
def test_equal(): assert 5 == 5
def test_not_equal(): assert 5 != 3
def test_string_equal(): assert 'hello' == 'hello'
def test_string_not_equal(): assert 'hello' != 'world'
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.
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
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.
Use == to check if values are equal.
Use != to check if values are not equal.
Assertions help confirm your code works as expected.
== is used to check if two values are equal in Python and pytest assertions.!= checks if values are not equal, so it is not the correct choice for equality.a is not equal to b in pytest?!=, so the assertion should be assert a != b.=! or ==! are invalid syntax and will cause errors.def test_numbers():
x = 10
y = 5 + 5
assert x == yx is 10, and y is calculated as 5 + 5, which equals 10.assert x == y checks if 10 equals 10, which is true, so the test passes.def test_strings():
s1 = "hello"
s2 = "Hello"
assert s1 != s2assert s1 != s2 correctly checks that the strings are not equal, so the test passes without error.get_status() returns a value that is not equal to None. Which assertion is the best choice?is not None rather than != None.is not None which is best practice. assert get_status() is None checks if value is None (opposite of requirement).Pass the test and this pattern moves unknown