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

Prevent patch_attribute from patching instance attributes at classes #224

Open
fornellas opened this issue Aug 19, 2020 · 2 comments
Open
Labels
enhancement New feature or request patch_attribute

Comments

@fornellas
Copy link
Contributor

This:

import testslide

class A:
  def __inti__(self):
    self.attr = 1


class TestA(testslide.TestCase):
  def test_attr(self):
    self.patch_attribute(A, "attr", "mock")

yields:

AttributeError: type object 'A' has no attribute 'attr'

However, patching instance attributes at classes should not be allowed. mock_callable already prevents that.

Let's make patch_attribute refuse to patch instance attributes at classes as well.

Probably a good idea to reuse logic from mock_callable to define if "is this good to patch?".

@fornellas fornellas added enhancement New feature or request patch_attribute labels Aug 19, 2020
@ldfsilva
Copy link
Contributor

Hey @fornellas, I got a question while refactoring the fix for this one, are classes attributes allowed to be patched at class level or should we enforce the same behavior as in for instance attributes?

For example, should the following work? (it works now)

class A:
    ATTR: str = "ATTR"


class TestA(testslide.TestCase):
  
    def test_class_attribute_work(self):
        self.patch_attribute(A, "ATTR", "mock")
        self.assertEqual(A.ATTR, "mock")

@fornellas
Copy link
Contributor Author

What you described LGTM as:

  • Attribute exists at the class, patching it there is no different from patching an attribute at a module or instance.
    • If it were to be patched at the instance, would only affect that instance, nothing more.
  • The issue here is when the attribute does not exist at the class, but only at the instance. Allowing to patch it at the class would mean not respecting the class interface (which does not have the attribute).

I crossed some wire when I mentioned mock_callable blocking patching instance methods at the class, which is a different issue rooted at this RSPec decision to not support it, as it is kind of a code smell, sorry about the confusion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request patch_attribute
Projects
None yet
Development

No branches or pull requests

2 participants