Issue
I wrote a decorator for asynchronous functions, but it does't work - an assertion is not thrown. Where is an error? The code in attachment.
import asyncio
import pytest
def tmi_freq_check(needed_value: int, tmi_freq_tolerance: int, tmi_freq_critical: bool, info_message: str = ""):
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
result = await func(*args, **kwargs)
if tmi_freq_critical:
assert needed_value == pytest.approx(result, tmi_freq_tolerance)
return result
return wrapper
return decorator
@tmi_freq_check(600, 10, True)
async def my_function():
return 500
async def main():
await my_function()
asyncio.run(main())
Solution
Your decorator works and the underlying assertion passes. But the issue is in tolerance parameter. It's not really a simple diff between two arguments but a relative tolerance.
From pytest.approx
doc:
Tolerances
By default, approx considers numbers within a relative tolerance of
1e-6
(i.e. one part in a million) of its expected value to be equal. This treatment would lead to surprising results if the expected value was 0.0, because nothing but 0.0 itself is relatively close to 0.0. To handle this case less surprisingly,approx
also considers numbers within an absolute tolerance of1e-12
of its expected value to be equal. Infinity and NaN are special cases. Infinity is only considered equal to itself, regardless of the relative tolerance. NaN is not considered equal to anything by default, but you can make it be equal to itself by setting the nan_ok argument to True. (This is meant to facilitate comparing arrays that use NaN to mean “no data”.)
...
In your case: 10
is 0.02
part of 500
and should be specified in that pattern:
@tmi_freq_check(600, 2e-2, True)
async def my_function():
return 500
Now, the it's seen that the relative threshold is exceeded:
Traceback (most recent call last):
...
assert needed_value == pytest.approx(result, tmi_freq_tolerance)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError
Answered By - RomanPerekhrest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.