Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle B015 within pytest.raises blocks #462

Open
jvavrek opened this issue Feb 22, 2024 · 3 comments
Open

How to handle B015 within pytest.raises blocks #462

jvavrek opened this issue Feb 22, 2024 · 3 comments

Comments

@jvavrek
Copy link

jvavrek commented Feb 22, 2024

Often when defining custom objects we end up testing that the __eq__ raises a particular error for unsupported comparisons. In practice, this means we have an unused comparison that triggers the B015 rule—see the MWE below. I wonder if there's a recommended way to get around this (without suppressing B015 altogether), or whether it could say be disabled within a with pytest.raises context.

Minimal working example:

# B015.py
import pytest


class MyClass:
    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        if not isinstance(other, MyClass):
            raise TypeError(f"Cannot compare with {type(other)}")
        return self.x == other.x


a = MyClass(5)
b = MyClass(5)
c = MyClass(4)

assert a == b
assert a != c
with pytest.raises(TypeError):
    a == a.x
$ flake8 B015.py 
B015.py:21:5: B015 Result of comparison is not used. This line doesn't do anything. Did you intend to prepend it with assert?
@jakkdl
Copy link
Contributor

jakkdl commented Oct 28, 2024

For cases like this you should just use in-line noqa https://flake8.pycqa.org/en/latest/user/violations.html#in-line-ignoring-errors

But for this specific case I'd personally just change the last line to be assert a == a.x

@cooperlees you can close this issue

@JelleZijlstra
Copy link
Collaborator

But for this specific case I'd personally just change the last line to be assert a == a.x

That's not right, the test is asserting that the __eq__ operation raises TypeError.

I think it's reasonable to disable this rule inside pytest.raises blocks (as well as self.assertRaises etc. for unittest).

@jakkdl
Copy link
Contributor

jakkdl commented Oct 29, 2024

But for this specific case I'd personally just change the last line to be assert a == a.x

That's not right, the test is asserting that the __eq__ operation raises TypeError.

no yeah, the assert would be an intentional no-op. Or something like _ = a == a.x. I guess it could slightly confuse readers though

I think it's reasonable to disable this rule inside pytest.raises blocks (as well as self.assertRaises

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants