Rewrite @property model in Factory Boy factory object

I want to find a way to test my code correctly with Factory Boy.

There is a model, for example:

from django.db import models class MyModel(models.Model): param1 = <some field> param1 = <some field> param1 = <some field> @property def is_smth(self): <some complicated code that returns boolean> 

There is a Factory for this model:

 import factory class MyModelFactory(factory.DjangoModelFactory): param1 = <some value> param2 = <some value> param3 = <some value> # And here i need to "rewrite" property of the model # so that it would always return true 

Can anyone help me with this? I did not find any mention of this in the documentation for the Factory boy, and the various options I tried did not work.

+4
source share
2 answers

Have you tried using mocks?

 def test_is_smith(self): mymodel = MyModel() with mock.patch('MyModel.is_smith', new_callable=mock.PropertyMock) as mocked_model: mocked_model.return_value = True self.assertTrue(mymodel.is_smith) 
+1
source

As suganti said, you can use mock.

But I propose another solution:

  @classmethod def _create(cls, model_class, *args, **kwargs): with mock.patch('MyModel.is_smth', new_callable=mock.PropertyMock) as m: m.return_value = True return super()._create(model_class, *args, **kwargs) 

Just a layout of the property during generation models. It works on factoryboy==2.5.2

0
source

Source: https://habr.com/ru/post/1440738/


All Articles