Skip to content

Latest commit

 

History

History
43 lines (29 loc) · 1.33 KB

index.rst

File metadata and controls

43 lines (29 loc) · 1.33 KB

patch_attribute()

patch_attribute() will, for the duration of the test, change the value of a given attribute:

import math

class ChangePi(TestCase):
  def test_pi(self):
    self.patch_attribute(math, "pi", 4)
    self.assertEqual(math.pi, 4)

patch_attribute() works exclusively with non-callable attributes.

Note

TestSlide provides mock_callable()<../mock_callable/index>, mock_async_callable()<../mock_async_callable/index> and mock_constructor()<../mock_constructor/index> for callables and classes because those require specific functionalities.

You can use patch_attribute() with:

  • Modules.
  • Classes.
  • Instances of classes.
  • Class attributes at instances of classes.
  • Properties at instances of classes.

Properties are tricky to patch because of the quirky mechanics that Python's Descriptor Protocol requires. patch_attribute() has support for that so things "just work":

class WithProperty:
  @property
  def prop(self):
    return "prop"

class PatchingProperties(TestCase):
  def test_property(self):
    with_property = WithProperty()
    self.patch_attribute(with_property, "prop", "mock")
    self.assertEqual(with_property.prop, "mock")