0
0
PyTesttesting~20 mins

Approximate comparisons (pytest.approx) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Approximate Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of approximate float comparison with pytest.approx
What is the result of running this pytest assertion code snippet?
PyTest
import pytest

def test_approx():
    assert 0.1 + 0.2 == pytest.approx(0.3)
ATest passes (no assertion error)
BAssertionError: 0.1 + 0.2 is not approximately equal to 0.3
CSyntaxError due to incorrect pytest.approx usage
DTypeError because pytest.approx cannot compare floats
Attempts:
2 left
💡 Hint
Remember that floating point arithmetic can cause small precision errors, pytest.approx helps with that.
assertion
intermediate
2:00remaining
Choosing the correct pytest.approx usage for relative tolerance
Which assertion correctly tests that variable x is approximately 10 with a relative tolerance of 1%?
Aassert x == pytest.approx(10, rel=1)
Bassert x == pytest.approx(10, rel=0.01)
Cassert x == pytest.approx(10, abs=0.01)
Dassert x == pytest.approx(10, tol=0.01)
Attempts:
2 left
💡 Hint
Check the parameter name for relative tolerance in pytest.approx.
🔧 Debug
advanced
2:00remaining
Identify the error in pytest.approx usage
What error will this test raise when run?
PyTest
import pytest

def test_value():
    assert 5 == pytest.approx(5, rel=-0.1)
ATest passes without error
BAssertionError because 5 is not approximately equal to 5 with negative tolerance
CTypeError due to invalid argument type
DValueError: relative tolerance must be non-negative
Attempts:
2 left
💡 Hint
Check the allowed range for relative tolerance values in pytest.approx.
🧠 Conceptual
advanced
2:00remaining
Understanding pytest.approx behavior with sequences
Given two lists a = [1.0, 2.0, 3.0] and b = [1.0, 2.01, 3.0], which pytest assertion will pass?
PyTest
import pytest
a = [1.0, 2.0, 3.0]
b = [1.0, 2.01, 3.0]
Aassert a == pytest.approx(b, rel=0.005)
Bassert a == pytest.approx(b, abs=0.005)
Cassert a == pytest.approx(b, abs=0.02)
Dassert a == pytest.approx(b, rel=0.01)
Attempts:
2 left
💡 Hint
Consider the difference between 2.0 and 2.01 and the tolerance values.
framework
expert
3:00remaining
Configuring pytest to globally change default tolerance for approx
How can you globally set pytest.approx to use a relative tolerance of 0.001 for all tests without changing each assertion?
AOverride pytest.approx in conftest.py to wrap original approx with rel=0.001
BUse a pytest fixture that monkeypatches pytest.approx to set rel=0.001 by default
CSet an environment variable PYTEST_APPROX_REL=0.001 before running tests
DCreate a pytest.ini file with [pytest] and add approx-rel = 0.001
Attempts:
2 left
💡 Hint
Think about how to customize pytest behavior programmatically.