Skip to content

'approx' should error immediately if an invalid parameter is passed #3473

@michaelboulton

Description

@michaelboulton

Using pytest.approx with an invalid parameter (eg, a string) should fail immediately rather than waiting until it calls repr(). Example:

>>> import pytest
>>> x = pytest.approx("abc")
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/michael/.virtualenvs/tavern/lib/python3.5/site-packages/_pytest/python_api.py", line 181, in __repr__
    if math.isinf(self.expected):
TypeError: a float is required

I would expected it to fail on the second line rather than when it prints it out.

This gets more confusing when you're logging it:

# example.py
import pytest
import logging

x = pytest.approx("abc")

logging.basicConfig(level=logging.DEBUG)

logging.info(x)

output:

$ python example.py 
--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.5/logging/__init__.py", line 980, in emit
    msg = self.format(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 830, in format
    return fmt.format(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 567, in format
    record.message = record.getMessage()
  File "/usr/lib/python3.5/logging/__init__.py", line 328, in getMessage
    msg = str(self.msg)
  File "/home/michael/.virtualenvs/tavern/lib/python3.5/site-packages/_pytest/python_api.py", line 181, in __repr__
    if math.isinf(self.expected):
TypeError: a float is required
Call stack:
  File "example.py", line 8, in <module>
    logging.info(x)
Unable to print the message and arguments - possible formatting error.
Use the traceback above to help find the error.

This issue in particular would be solved by putting the math.isinf check in the constructor rather than only checking when printing out the value.

Metadata

Metadata

Assignees

Labels

type: enhancementnew feature or API change, should be merged into features branch

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions