2022-03-17 TIL

Grolar Kim·2022년 3월 17일
0

TIL-WIL

목록 보기
10/17


Django로 Imagefield를 사용한 모델을 위한 테스트 코드를 작성중 여러 문제가 생겼다.

1. 이미지 파일로 테스트하는법 모름

Imagefield를 테스트 하는 법을 검색해보니 다음과 같은 해결책이 나왔다.

from django.core.files.uploadedfile import SimpleUploadedFile
newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')

출처 : https://stackoverflow.com/questions/26298821/django-testing-model-with-imagefield

2. 이미지 파일이 다르다고 함

이를 적용한 뒤 테스트를 해보았더니 다음 에러가 뜨면서 작동이 되지 않았다.

AssertionError: <ImageFieldFile: logo_kQhWinh.png> != <SimpleUploadedFile: logo.png (image/png)>

원인을 알아보던 중 장고에서 미디어 파일을 업로드하면서 이름이 중복될 시 다른이름으로 저장한다는 것을 알고 파일 저장소를 확인하니 많은 양의 이미지가 쌓여 있었다.

그래서 처음에는 이걸 사용하여 해결하려고 했지만 여전히 중복업로드가 해결되지 않았다.

@override_settings(MEDIA_ROOT=tempfile.gettempdir())

출처 : https://swapps.com/blog/testing-files-with-pythondjango/

그래서 그 다음은 이걸 사용하여 해결하려고 했다. 이 경우, 테스트 별로 폴더를 새로 만들기에 이미지 파일이 다른 에러는 해결이 되었다.

@override_settings(MEDIA_ROOT=tempfile.TemporaryDirectory(prefix='mediatest').name) 

출처 : https://stackoverflow.com/questions/25792696/automatically-delete-media-root-between-tests

하지만 tempfile이 점점 쌓여있기에 이를 테스트마다 지워주는 방법을 찾기로 했다.

from django.test import override_settings
import shutil
TEST_DIR = 'test_data'
class SomeTests(TestCase):
    ...
    # use the `override_settings` decorator on 
    # those methods where you're uploading images
    @override_settings(MEDIA_ROOT=(TEST_DIR + '/media'))
    def test_file_upload(self):
        ...
        # your code
        ...
...
# then create a tearDownModule function
# to remove the `TEST_DIR` folder at the 
# end of tests
def tearDownModule():
    print "\n Deleting temporary files..."
    try:
        shutil.rmtree(TEST_DIR)
    except OSError:
        pass

출처 : https://bhch.github.io/posts/2018/12/django-how-to-clean-up-images-and-temporary-files-created-during-testing/

테스트용 폴더를 지정한 뒤, 테스트를 실행 할 때 마다 이를 실행해서 모든 미디어 파일을 지워주는 방법을 사용하여 파일이 쌓이는 것을 방지하였다.

0개의 댓글