2012-10-19 90 views
4

我想找到一種方法來正確測試我的廠男孩代碼。重寫模式@property在廠男孩的對象工廠

有一個模型,像這樣:

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> 

有這個模型工廠:

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 

誰能幫助我嗎?我沒有在工廠男孩的文檔中發現這件事,我嘗試過的各種變體似乎都不起作用。

回答

1

您是否嘗試過使用嘲笑?

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) 
0

正如Suganthi所說,你可以使用模擬。

但我提供了另一種解決方案:在一代車型

@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) 

只是模擬性能。它適用於factoryboy==2.5.2