1

I have the following Django code in my system:

zip_file = zipfile.ZipFile(file, 'r')
for filename in zip_file.namelist():
    try:
        file_read = zip_file.read(filename)
        print(filename)

I am trying to test this code by passing in a zip file from a python TestCase. When I use this code with the web interface, I noticed the zip file is an InMemoryUploadedFile type. So I'm trying to mimic this functionality with my TestCase, but can't seem to create an InMemoryUploadedFile() in my test with a zip file.

I've tried this:

file_name = 'file.zip'
in_memory_uploaded_file = InMemoryUploadedFile(file_name, None, file_name, 'application/zip', 0, None, None)

Any recommendations?

Kamilski81
  • 14,409
  • 33
  • 108
  • 161

1 Answers1

1

According to the source the InMemoryUploadedFile should be called with InMemoryUploadedFile(file, field_name, name, content_type, size, charset, [content_type_extra])

So, you should pass all these parameters:

with file as open('file.zip', 'r'):
    InMemoryUploadedFile(file, relevant_field,'arquivo',
                         'application/zip', file_size, 'utf8')

For file size you could use fixed number for the test, or if needed use the technique in https://stackoverflow.com/a/19079887/3930971

f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(0, os.SEEK_SET)
chicocvenancio
  • 629
  • 5
  • 14