[Answered ]-Django Testing: How to stub that model.ForeignKey property?

2πŸ‘

βœ…

With a bit of digging, stumbled on the model add_to_class() method that does proper monkey patching and can override foreign key properties on a model.

Example of usage:

class FakeMoon(object):
    def get_phase(self): return self._phase
    def set_phase(self, phase): self._phase = phase
    phase = property(get_phase, set_phase)

# this bit is the answer to the question above
Wolf.add_to_class("moon", FakeMoon())

w = Wolf()

w.moon.phase = 'new moon'
w.update_mood()
assert w.mood == 'good'

w.moon.phase = 'waxing crescent'
w.update_mood()
assert w.mood == 'hopefull'
πŸ‘€Evgeny Zislis

0πŸ‘

For the sake of testing, you could override (monkey patch, if you want to use it in test environment only) __ getattribute__.

In __ getattribute__ check if the property moon is called, return the value or set the value in a temporary var.

πŸ‘€Roel Kramer

Leave a comment