Django Rest: как издеваться над FileField и ImageField to_representation()

У меня есть модель с 2 полями: изображение (ImageField) и медиа (FileField). Они оба используют пользовательское хранилище GoogleCloudMediaStorage.

При написании тестов я не могу получить доступ к GCS, поэтому я сымитировал запись файлов, сделав следующее:

from unittest.mock import patch

@patch('my_project.storage_backends.CustomGoogleCloudMediaStorage.save')
    def test(self, mock_save):
        mock_save.return_value = 'mocked_file.png'
        # rest of the test

И все работает нормально. Проблема в том, что теперь мне нужно протестировать обновление и представление списка. Когда я это делаю, у меня, конечно же, возникает эта ошибка:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application.

Покопавшись немного, вижу, что ошибку вызывает сериализатор to_representation(). Точнее, в последовательности FileField:

    def to_representation(self, value):
        if not value:
            return None

        use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL)
        if use_url:
            try:
                url = value.url #  !! THIS LINE CAUSE THE ISSUE
            except AttributeError:
                return None
            request = self.context.get('request', None)
            if request is not None:
                return request.build_absolute_uri(url)
            return url

Так что я попытался поиздеваться FileField.to_representation(), сделав вот что:

@patch('django.db.models.FileField.to_representation')
    def test_update(self, mock_representation):
        mock_representation.return_value = 'mocked_training_file_url'
        data = {
            'title': 'Updated',
        }

        response = self.client.patch(. . .)

Но у меня есть эта ошибка:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/unittest/mock.py", line 1322, in patched
    with self.decoration_helper(patched,
  File "/usr/local/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/usr/local/lib/python3.8/unittest/mock.py", line 1304, in decoration_helper
    arg = exit_stack.enter_context(patching)
  File "/usr/local/lib/python3.8/contextlib.py", line 425, in enter_context
    result = _cm_type.__enter__(cm)
  File "/usr/local/lib/python3.8/unittest/mock.py", line 1393, in __enter__
    original, local = self.get_original()
  File "/usr/local/lib/python3.8/unittest/mock.py", line 1366, in get_original
    raise AttributeError(
AttributeError: <class 'django.db.models.fields.files.FileField'> does not have the attribute 'to_representation'

Есть идеи, как я могу высмеять FileField и ImageField to_representation()? Правильно ли я это делаю

Вернуться на верх