首页 > 解决方案 > 修补 Django FileSystemStorage 位置不生效 [pytest]

问题描述

我有一个简单的模型:

#models.py

from django.core.files.storage import FileSystemStorage

LOCATION = 'old_location'


class FileArchive(models.Model):
    file = models.FileField(storage=FileSystemStorage(location=LOCATION))

我有一个视图,通过它我可以填充提到的模型并调用 .save()。我的目标是进行功能测试以尝试上传文件并断言该文件存在于提供的(修补的)位置上。

问题是无论我如何修补LOCATION位于 mymodels.py中的 ,测试仍然使用我模型中的硬编码位置。

以下是我尝试修补的方法LOCATION

我尝试修补 LOCATION 属性的一些方法:

from . import models
def test_uploaded_file_is_stored(monkeypatch):
    monkeypatch.setattr(models, 'LOCATION', 'new_location')
    ...

另一种方式:

def test_uploaded_file_is_stored(mocker):
    mocker.patch.object(modesl, 'LOCATION', 'new_location')
    ...

另一种方式:

from unittest.mock import patch
def test_uploaded_file_is_stored(mocker):

    with patch('filestorage.models', 'LOCATION', 'new_location')
    ...

我猜我正在修补错误的地方。有任何想法吗?

标签: pythondjangomockingpytest

解决方案


推荐阅读