Subsequent Django Unittests raise "MySQLdb.OperationalError: (2006, '')"

63 Views Asked by At

I am unittesting a method creating an HttpReponse and delivering a CSV file.

def _generate_csv(self):
    filename = self._get_filename('csv')

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    writer = csv.DictWriter(response, csv_header_list, delimiter=";")
    writer.writeheader()

    for obj in object_list:
        writer.writerow(csv_dict)
    response.close()

    return response

When running my unittests, all test before this tests passt but all subsequent fail with this obscure error:

MySQLdb.OperationalError: (2006, '')

Any idea why testing this method breaks the other tests?

1

There are 1 best solutions below

0
Ron On

Ok, found it! Closing the response is killing the database connection (2206 means "Database gone away")

response.close()

Just mock the close away in your tests:

@mock.patch.object(HttpResponse, 'close')
def test_generate_csv_case_x(self, *args):
    ...