def select_file(self, request, *args, **kwargs): """View containing a form to select a CSV file to import.""" if request.method != 'POST': return self._select_file_form_response(request, InteractionCSVForm()) form = InteractionCSVForm(request.POST, request.FILES) if not form.is_valid(): return self._select_file_form_response(request, form) if not form.are_all_rows_valid(): return self._error_list_response(request, form) return self._preview_response(request, form)
def test_to_csv(self): """Test CSV file generation.""" collector = UnmatchedRowCollector() input_rows = make_unmatched_rows(2) for input_row in input_rows: collector.append_row(InteractionCSVForm(data=input_row)) csv_contents = collector.to_raw_csv() with io.BytesIO(csv_contents) as stream: reader = csv.reader(io.TextIOWrapper(stream, encoding='utf-8-sig')) csv_rows = list(reader) assert csv_rows == [ [ 'theme', 'kind', 'date', 'adviser_1', 'contact_email', 'service', 'communication_channel', ], [ input_rows[0]['theme'], input_rows[0]['kind'], input_rows[0]['date'], input_rows[0]['adviser_1'], input_rows[0]['contact_email'], input_rows[0]['service'], input_rows[0]['communication_channel'], ], [ input_rows[1]['theme'], input_rows[1]['kind'], input_rows[1]['date'], input_rows[1]['adviser_1'], input_rows[1]['contact_email'], input_rows[1]['service'], input_rows[1]['communication_channel'], ], ] # Check that the file re-validates (so it can be re-uploaded) form = InteractionCSVForm( files={ 'csv_file': SimpleUploadedFile('test.csv', csv_contents), }, ) assert form.is_valid() assert form.are_all_rows_valid()