3

Django ビューのテストを書いていて、ファイルを POST したいです。これはかなり簡単なテストであり、ディレクトリにさまざまなテキスト ファイルを散らかしたくないtests/ので、インメモリ ファイルを使用してその場でコンテンツを作成したいと考えています。

from StringIO import StringIO
file = StringIO('content')
client.post("/", data={'file': file})

残念ながら、これは機能しません:

Traceback (most recent call last):
  File "/Users/brad/project/tests/files.py", line 57, in test_set_and_save
    'mgmt-current_step': 'Attachments',
  File "/Users/brad/django/test/client.py", line 423, in post
    response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
  File "/Users/brad/django/test/client.py", line 245, in post
    post_data = self._encode_data(data, content_type)
  File "/Users/brad/django/test/client.py", line 211, in _encode_data
    return encode_multipart(BOUNDARY, data)
  File "/Users/brad/django/test/client.py", line 117, in encode_multipart
    lines.extend(encode_file(boundary, key, value))
  File "/Users/brad/django/test/client.py", line 145, in encode_file
    content_type = mimetypes.guess_type(file.name)[0]
AttributeError: StringIO instance has no attribute 'name'
4

1 に答える 1

6

Django には、Python の組み込みfileオブジェクト用の一連のラッパーが付属しています。この状況django.core.files.base.ContentFileでは適切です:

from django.core.files.base import ContentFile
file = ContentFile(b'content', name='plain.txt')
client.post('/', data={'file': file})

ContentFileバイトで動作することを期待しているので、Unicode データを与えないでください。

別のトリック (ファイルの内容を気にしない場合) は、現在のファイルを送信することです。

client.post('/', data={'file': open(__file__, 'rb'))
于 2012-12-10T04:35:33.107 に答える