2016-02-28 155 views
6

我爲我的Flask集成測試使用Flask-Testing。我有一個文件上傳的文件,我試圖編寫測試,但我不斷收到一個錯誤:TypeError: 'str' does not support the buffer interface在Flask中測試文件上傳

我正在使用Python 3.我找到的最接近的答案是this,但它不適用於我。

這是我的許多嘗試之一是這樣的:

def test_edit_logo(self): 
    """Test can upload logo.""" 
    data = {'name': 'this is a name', 'age': 12} 
    data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg') 
    self.login() 
    response = self.client.post(
     url_for('items.save'), data=data, follow_redirects=True) 
    }) 
    self.assertIn(b'Your item has been saved.', response.data) 
    advert = Advert.query.get(1) 
    self.assertIsNotNone(item.logo) 

怎樣一個測試在燒瓶內的文件上傳?

回答

6

問題結束了不是當將content_type='multipart/form-data'添加到post方法中時,它期望data中的所有值都是是文件或字符串。我的數據字典中有整數,我通過this評論意識到了這一點。

所以最終的解決方案最終看上去像這樣:

def test_edit_logo(self): 
    """Test can upload logo.""" 
    data = {'name': 'this is a name', 'age': 12} 
    data = {key: str(value) for key, value in data.items()} 
    data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg') 
    self.login() 
    response = self.client.post(
     url_for('adverts.save'), data=data, follow_redirects=True, 
     content_type='multipart/form-data' 
    ) 
    self.assertIn(b'Your item has been saved.', response.data) 
    advert = Item.query.get(1) 
    self.assertIsNotNone(item.logo) 
+0

我非常愛你,現在我會吻你。我花了整整一小時試圖弄清楚什麼是錯誤的......好的先生,你是我的救世主。 – Rodrigo

7

你需要兩樣東西:

1)在你的.post()
2. content_type='multipart/form-data')在data=傳中file=(BytesIO(b'my file contents'), "file_name.jpg")

完整的例子:

data = dict(
     file=(BytesIO(b'my file contents'), "work_order.123"), 
    ) 

    response = app.post(url_for('items.save'), content_type='multipart/form-data', data=data) 
+0

感謝@ mam8cc。你能澄清點2嗎?這聽起來像你說的將關鍵字參數傳遞給字典,我不認爲這是你的意思。你能給我一個簡短的代碼示例嗎? – hammygoonan

+0

@hammygoonan我用更完整的例子更新了這個問題。 – mam8cc

+0

再次感謝@ mam8cc,我想我們正在某個地方。如果我使用你的答案中的代碼,那麼它解決了這個問題。但是,當我添加額外的字段到數據字典時,它會與TypeError斷開。我編輯了我的問題,使其更清晰。 – hammygoonan