Accept common spreadsheet formats, not just CSV

We require users to export their spreadsheets as CSV files before
uploading them. But this seems like the sort of thing a computer should
be able to do.

So this commit adds a wrapper class which:
- takes a the uploaded file
- returns it in a normalised format, or reads it using pyexcel[1]
- gives the data back in CSV format

This allows us to accept `.csv`, `.xlsx`, `.xls` (97 and 95), `.ods`,
`.xlsm` and `.tsv` files. We can upload the resultant CSV just like
normal, and process it for errors as before.

Testing
---

To test this I’ve added a selection of common spreadsheet files as test
data. They all contain the same data, so the tests look to see that the
resultant CSV output is the same for each.

UI changes
---

This commit doesn’t change the UI, apart from to give a different error
message if a user uploads a file type that we still don’t understand.

I intend to do this as a separate pull request, in order to fulfil
https://www.pivotaltracker.com/story/show/119371637
This commit is contained in:
Chris Hill-Scott
2016-05-05 15:41:11 +01:00
parent a348bce191
commit 1409ca36ca
13 changed files with 111 additions and 9 deletions

View File

@@ -1,6 +1,8 @@
import pytest
import re
from io import BytesIO
from os import path
from glob import glob
from bs4 import BeautifulSoup
from flask import url_for
from unittest.mock import ANY
@@ -8,6 +10,43 @@ from tests import validate_route_permission, job_json_with_created_by
template_types = ['email', 'sms']
# The * ignores hidden files, eg .DS_Store
test_spreadsheet_files = glob(path.join('tests', 'spreadsheet_files', '*'))
def test_that_test_files_exist():
assert len(test_spreadsheet_files) == 8
@pytest.mark.parametrize("filename", test_spreadsheet_files)
def test_upload_files_in_different_formats(
filename,
app_,
api_user_active,
mocker,
mock_login,
mock_get_service,
mock_get_service_template,
mock_s3_upload,
mock_has_permissions,
fake_uuid
):
with app_.test_request_context(), app_.test_client() as client, open(filename, 'rb') as uploaded:
client.login(api_user_active)
client.post(
url_for('main.send_messages', service_id=fake_uuid, template_id=fake_uuid),
data={'file': (BytesIO(uploaded.read()), filename)},
content_type='multipart/form-data'
)
assert mock_s3_upload.call_args[0][2]['data'].strip() == (
"phone number,name,favourite colour,fruit\r\n"
"07739 468 050,Pete,Coral,tomato\r\n"
"07527 125 974,Not Pete,Magenta,Avacado\r\n"
"07512 058 823,Still Not Pete,Crimson,Pear"
)
def test_upload_csvfile_with_errors_shows_check_page_with_errors(
app_,
@@ -74,7 +113,7 @@ def test_upload_csv_invalid_extension(app_,
)
assert resp.status_code == 200
assert "{} is not a CSV file".format(filename) in resp.get_data(as_text=True)
assert "{} isnt a spreadsheet that Notify can read".format(filename) in resp.get_data(as_text=True)
def test_send_test_sms_message(