Django Testing: How to stub that model.ForeignKey property?

I have a model in django that has a foreign key to another model, and during unit testing I want to avoid tight-coupling of the two models and create a stub for the other model that will return different values each time.

Contrived example:

class Moon(models.Model): def phase(self): # some extremely complex code class Wolf(models.Model): moon = models.ForeignKey(Moon) mood = models.CharField() def update_mood(self): if (self.moon.phase == 'new moon'): self.mood = "good" if (self.moon.phase == 'waxing crescent'): self.mood = "hopefull" ...

Example for the above:

w = Wolf() m = Moon() # m.phase = 'new moon' w.moon = m w.update_mood() w.mood # 'good'

Now I want to test the Wolf().moon property after I do an update_mood() call, without actually touching the Moon model at all - because its a very complex model that goes out into all kinds of external systems to figure out its phase.

Usually I would use monkey-patching for this, but since .mood is a property ... I can't really assign to it in a monkey-patching way.



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'
assert w.mood == 'good'

w.moon.phase = 'waxing crescent'
assert w.mood == 'hopefull'

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.

Category:django Time:2011-03-31 Views:1

Related post

  • Django-models ForeignKey Objects display Field Name instead of Object Values 2010-02-01

    I am using a ForeignKey called Memberno in My Django models. After entering data in the Members Class, it appears in the other classes as "member object" in the 'memberno' field. For ForeignKey, I am using 'raw_id_fields' as a workaround, but for nor

  • Django Model ForeignKey 2 2010-08-24

    I dont understand how I can "import"(I dont know the right terminology, so please dont crucify me on this) a Foreignkey from 1 model class to a another: e.g. class1 (models.Model): variable1 = models.CharField() variable2 = models.CharField() class2

  • django models foreignkey beetwen apps 2010-09-24

    I have problems with making my models to work. Here is my appname.misc.models file from django.db import models class user(models.Model): login=models.CharField(max_length=20) email=models.EmailField(max_length=50) banned=models.BooleanField() key=mo

  • Django - Limit the entries in models.ForeignKey() 2010-11-24

    Is to possible to limit the entries in models.ForeignKey() field based on some condition? customer = models.ForeignKey(Customer) I just need to show the customer who are in active status. --------------Solutions------------- Assuming you're using the

  • Django: Why are quotes around the model in a ForeignKey definition 2011-01-16

    I want to know what the difference between these two foreignkey definitions are. (1) MyFKField = models.ForeignKey('MyModel') (2) MyFKField = models.ForeignKey(MyModel) I understand (I think...) that (1) MyModel needs to be defined in that same file

  • django save model ForeignKey relation 2011-02-17

    in my class Layer(models.Model): user = models.IntegerField() name = models ... class Point(models.Model): layers = models.ForeignKey(Layer) meta = models.TextField() ... in my def datasave(request, id): mid = request.POST.get("layer

  • Django views - optimum query set in a ForeignKey model 2011-09-15

    Having the model: class Notebook(models.Model): n_id = models.AutoField(primary_key = True) class Note(models.Model): b_nbook = models.ForeignKey(Notebook) the URL pattern passing one parameter: (r'^(?P<n_id>\d+)/$', 'notebook_notes') and the f

  • django model foreignkeys question 2011-09-21

    I am very new to programming and databases and I have a question about foreignkeys in django. Say I have a model called Expenses that has a foreignkey pointed to Employees model. class Employees(models.Model): ... class Expenses(models.Model): ... em

  • Django models ForeignKey on_delete attribute: does it really delete all related objects? 2011-12-17

    Here some models: class UserProfile(models.Model): name = models.CharField(max_length=30) email = models.EmailField(unique=True, db_index=True) birthday = models.DateField() class Photo(models.Model): user = models.ForeignKey(UserProfile) description

  • Getting a filtered list of objects in django admin from django model.ForeignKey field 2012-03-02

    I have five models: Class League(models.Model): type = models.CharField(max_length=30) class Team(models.Model): name = models.CharField(max_length=30) league = models.ForeignKey(max_length=30) class Player(models.Model): name = models.CharField(max_

  • Django Model ForeignKey 2010-08-24

    If I want to add a Foreignkey to a model from another class in the same model e.g. class1 (models.Model): variable1 = models.IntegerField() class2 (models.Model): variable2 = models.CharField() foreignkey = models.Foreignkey(class1.variable1) Is that

  • Django models.ForeignKey filter 2011-09-13

    I have a 2 models: class Foo(models.Model): name... type = models.CharField(choices=TYPE_CHOICES) class Fighter(models.Model): foo = models.ForeignKey(Foo, filter(type="A") Can you filter the drop down list of the foreign key? --------------Solutions

  • django - how can I join two models with ForeignKeys to the same users? 2011-10-25

    I have multiple models like this: class Model1(models.Model): user = models.ForeignKey(User) model1_filed1 = models.CharField() class Model2(models.Model): user = models.ForeignKey(User) model2_filed1 = models.CharField() .... As you can see all the

  • Django admin - inline inlines (or, three model editing at once) 2009-03-31

    I've got a set of models that look like this: class Page(models.Model): title = models.CharField(max_length=255) class LinkSection(models.Model): page = models.ForeignKey(Page) title = models.CharField(max_length=255) class Link(models.Model): linkse

  • using django, how to create method in model to return query data 2009-05-06

    In the following code, I'm tyring to create the method show_pro that will show all Arguments for the Case that are pro. I am getting this error: >>> Case.objects.all()[0].show_pro() Traceback (most recent call last): File "<console>",

  • Writing Python/Django view to "join" across three models/tables 2009-08-19

    Just begin my Python/Django experience and i have a problem :-) So i have a like this: from django.db import models class Priority(models.Model): name = models.CharField(max_length=100) class Projects(models.Model): name = models.CharField(m

  • django queryset excluding entries in second model 2009-10-28

    I'm making a little vocabulary-quiz app, and the basic model for a word is this: class Word(models.Model): id = models.AutoField(primary_key=True) word = models.CharField(max_length=80) id_image = models.ForeignKey(Image) def __unicode__(self): retur

  • How to distuingish between Django's automatically created ManyToMany through-models and manually defined ones? 2010-02-10

    Say we have models: from django.db import models class AutomaticModel(models.Model): others = models.ManyToManyField('OtherModel') class ManualModel(models.Model): others = models.ManyToManyField('OtherModel', through='ThroughModel') class OtherModel

  • Django multi tennant architecture - Should all models have a reference to the tennant_id 2010-03-04

    Let's say that accounts in my SAAS are of the type Account(models.Model). Would the following be a good idea? class MyModel(models.Model): account = models.ForeignKey(Account) spam = models.CharField(max_length=255) class MyOtherModel(models.Model):

Copyright (C), All Rights Reserved.

processed in 0.464 (s). 13 q(s)