0
0
PyTesttesting~15 mins

Deterministic tests in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify deterministic behavior of a function that returns a fixed output
Preconditions (2)
Step 1: Create a function named get_fixed_value that always returns the integer 42
Step 2: Write a pytest test function named test_get_fixed_value
Step 3: Call get_fixed_value inside the test
Step 4: Assert that the returned value is exactly 42
✅ Expected Result: The test passes every time with the value 42 returned and assertion successful
Automation Requirements - pytest
Assertions Needed:
Assert returned value equals 42
Best Practices:
Use clear function and test names
Keep tests independent and repeatable
Avoid randomness or external dependencies in the function
Automated Solution
PyTest
import pytest

def get_fixed_value():
    return 42


def test_get_fixed_value():
    result = get_fixed_value()
    assert result == 42, f"Expected 42 but got {result}"

The get_fixed_value function always returns 42, making it deterministic.

The test test_get_fixed_value calls this function and asserts the result is 42.

This ensures the test will pass every time, showing deterministic behavior.

Assertions include a helpful message if the test fails.

Common Mistakes - 3 Pitfalls
Using random or time-based values inside the function
Not asserting the exact expected value
Writing tests that depend on external state or files
Bonus Challenge

Now add data-driven testing with 3 different fixed values returned by separate functions

Show Hint