2017-03-06 77 views
0

如何用Factory對象覆蓋django模型以避免觸擊數據庫。如何避免在此測試用例中訪問數據庫

models.py

from django.db import models 

class ApplicationType(models.Model): 
    """ 
    Types of applications available in the system/ 
    """ 
    title = models.CharField(max_length=30) 

    def __str__(self): 
     return self.title 

utils.py

from .models import ApplicationType 

self.base_details = {} 

def get_application_type(self, value): 
""" 
Get types of applications. When successful it Populates the 
self.base_details with an application_type key 

Args: 
    value (object): value to be parsed 

Returns: 
    bool: True when value is ok, Else false 

Raises: 
""" 
item_name = "Application Type" 
self.base_details['application_type'] = None 
try: 
    if value: 
     try: 
      result = ApplicationType.objects.get(title=value) # <== How do I avoid hitting this DB object? 
      self.base_details['application_type'] = result.id 
      return True 
     except ApplicationType.DoesNotExist: 
      self.error_msg = "Invalid Value: {}".format(item_name) 
      return False 
    else: 
     self.error_msg = "Blank Value: {}".format(item_name) 
     return False 
except: 
    raise 

所以測試,我創建一個ApplicationType工廠

tests.py

import factory 
import pytest 
application_types = ['Type 1', 'Type 2'] 

class ApplicationTypeFactory(factory.Factory): 
    class Meta: 
     model = ApplicationType 

    title = "application_type_title" 


@pytest.mark.django_db() 
def test_get_application_type_populates_dict_when_value_provided_exists_in_database(self): 
    """Populates base_details dict when value is found in database""" 
    for entry in application_types: 
     application_type = ApplicationTypeFactory.build(title=entry) 
     assert self.base_info_values.get_application_type(entry) == True 
     assert self.base_info_values.base_details["application_type"] is not None 

因此,你會如何去編寫一個測試,以避免擊中ApplicationType.objects.get()查詢中的數據庫?我可以將「模型」作爲參數傳遞給函數嗎?這會是一個好的設計嗎?

您可以自由地爲應用程序/功能提供替代結構,特別是爲了在這種情況下進行更好的測試。

正在運行Python3.5,pytest,Django和factory_boy

回答

0

可以修補調用數據庫,退還您設定的預設值。在你的情況,你可以做這樣的事情:

import factory 
import pytest 
from unittest.mock import Mock, patch 
application_types = ['Type 1', 'Type 2'] 
@pytest.mark.django_db() 
@patch('ApplicationType.objects.get') 
def test_get_application_type_populates_dict_when_value_provided_exists_in_database(self, db_mocked_call): 
    """Populates base_details dict when value is found in database""" 
    mocked_db_object = {'id': 'test_id'} 
    db_mocked_call.return_value = mocked_db_object 
    for entry in application_types: 
     application_type = ApplicationTypeFactory.build(title=entry) 
     assert self.base_info_values.get_application_type(entry) == True 
     assert self.base_info_values.base_details["application_type"] is not None 

我建議你檢查以及pytest.parametrize,以避免對循環利用的在您的測試,閱讀更多關於它在這裏:http://doc.pytest.org/en/latest/parametrize.html

在您的示例中,測試可能類似於以下內容:

@pytest.mark.django_db() 
@pytest.mark.parametrize("entry", ['Type 1', 'Type 2']) 
@patch('ApplicationType.objects.get') 
def test_get_application_type_populates_dict_when_value_provided_exists_in_database(self, db_mocked_call, entry): 
    """Populates base_details dict when value is found in database""" 
    mocked_db_object = {'id': 'test_id'} 
    db_mocked_call.return_value = mocked_db_object 
    application_type = ApplicationTypeFactory.build(title=entry) 
    assert self.base_info_values.get_application_type(entry) == True 
    assert self.base_info_values.base_details["application_type"] is not None 
相關問題