Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Stop Flaky Float Tests with pytest.approx()

Table of Contents

Stop Flaky Float Tests with pytest.approx()

When working with floating-point numbers in tests, comparing exact equality often fails due to inherent precision limitations, which results in flaky or unreliable tests.

You can use pytest.approx() to compare floating-point numbers with a reasonable tolerance, making your tests more robust and readable.

Here’s a code example to show its usefulness:

# Without pytest.approx - test fails
def test_calculation_without_approx():
    result = 0.1 + 0.2
    assert result == 0.3  # This fails!

# With pytest.approx - test passes
def test_calculation_with_approx():
    result = 0.1 + 0.2
    assert result == pytest.approx(0.3)  # This passes!

# Works with sequences too
def test_list_of_floats():
    results = [0.1 + 0.2, 0.2 + 0.4]
    expected = [0.3, 0.6]
    assert results == pytest.approx(expected)

In these examples:

  • The first test fails because 0.1 + 0.2 in floating-point arithmetic doesn’t exactly equal 0.3.
  • The second test passes because pytest.approx() allows for a small tolerance in the comparison (by default, relative tolerance of 1e-6).
  • The third example shows how it works with lists of numbers, making it convenient for comparing multiple results at once.

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran