Search code examples
pythonpython-3.xassertflake8

Changing assert statement to remove "== True" according to flake8 E712 produces error


I am trying to write a pytest of the form

import numpy as np
import pytest

def test(blah):
    # ...
    assert (np.isclose(computed_value, expected_value, atol = 0.001, rtol = 0) == True), 
    "error message" 

The pytests pass, but once I try to commit to GitLab, I get the following message and the commit fails to go through.

>  flake8...................................................................Failed
- hook id: flake8
- exit code: 1
  E712 comparison to True should be 'if cond is True:' or 'if cond:

Replacing the above assert by

assert if np.isclose(computed_value, expected_value, atol = 0.001, rtol = 0) is True,"Error message"

does not help either.

Further,

assert (np.isclose(computed_value, expected_value, atol = 0.001, rtol = 0) is True), 
        "error message" 

causes my pytest to fail! How can I resolve this?


Solution

  • the original code was not testing what you expect -- == in numpy is a projection (meaning numpy.array([1, 2, 3]) == True => numpy.array([True, False, False])

    numpy.isclose is also a projection of sorts, returning an array with values for each comparison -- your original assertion only passed because a numpy array is "truthy" -- not that every value was close within the tolerance

    you probably want to use numpy.all to validate that everything was "isclose" --

    assert numpy.all(numpy.isclose(...))