pytest.approx
时间: 2023-10-26 22:22:44 浏览: 86
pytest.approx is a utility provided by the pytest testing framework. It is used to perform approximate comparisons between floating-point values.
When writing tests for floating-point values, it is often impractical to expect exact equality due to rounding errors. pytest.approx allows you to specify a tolerance within which the values should be considered approximately equal.
Here's an example usage of pytest.approx:
```python
def test_approximate_comparison():
assert 0.1 + 0.2 == pytest.approx(0.3)
```
In this example, instead of checking for exact equality, we use pytest.approx to compare the sum of 0.1 and 0.2 with the expected value of 0.3. The assertion will pass because pytest.approx takes into account a default tolerance for floating-point comparisons.
You can also specify a custom tolerance by providing a second argument to pytest.approx, like this:
```python
def test_custom_tolerance():
assert 0.1 + 0.2 == pytest.approx(0.3, abs=1e-6)
```
In this case, we set the absolute tolerance to 1e-6, meaning that the values will be considered approximately equal if their difference is within this tolerance.
Overall, pytest.approx is a useful tool for performing approximate comparisons in tests involving floating-point numbers, helping to handle the inherent imprecision of floating-point arithmetic.
阅读全文