データベースへの負担を避けるために、DjangoモデルをFactoryオブジェクトで上書きする方法を教えてください。このテストケースでのデータベースへの移動を回避する方法
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()
クエリでデータベースにぶつからないテストを書くにはどうすればよいですか?関数にパラメータとして "Model"を渡すことができますか?これは良い設計ですか?
この種のシナリオでは、特に優れたテストを可能にするために、アプリケーション/機能の代替構造を自由に指定することができます。
はあなたが設定した所定の値を返すために、データベースへのコールにパッチを適用することができPython3.5、pytest-ジャンゴとfactory_boy