Django:创建CSV文件以测试上传端点,并在测试完成后将其删除

时间:2018-08-14 12:20:33

标签: django

我正在使用Django为/upload端点编写一个测试用例。为此,我创建了一个使用给定数据集创建csv文件的方法。当我运行测试用例时,有时测试数据库无法删除。如何克服这个问题? 这是我的测试代码:

import csv
import os
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient


def create_csv(data):
    with open('some.csv', 'w') as map_file:
        writer = csv.writer(map_file)
        writer.writerows(data)
        map_file.close()


class CSVUploadTest(TestCase):

    def setUp(self):
        self._map_data = [
            [3, "05, Banagram Road, Hatkhola, Ray Shaheb Bazar, 1203", 23.72054135, 90.4141324, "Ghulsan 1"],
            [1, "#04, Dhaka-Chittagong Highway, Hatkhola, Lakshmi Bazar, 1203", 23.7210324, 90.4174495033668, "Ghulsan 2"],
            [2, "04, Road 4, Mirpur 10, 1216", 23.8093795, 90.3731244],
        ]
        create_csv(self._map_data)
        self._csv_filename = "some.csv"
        self._client = APIClient()

    def test_location_csv_upload(self):
        url = reverse('upload')
        csv_file = open(self._csv_filename, "r")
        resp = self._client.post(url, {"file": csv_file})
        csv_file.close()
        os.remove("some.csv")
        self.assertEqual(resp.status_code, 200)

这是我得到的错误:

django.db.utils.OperationalError: database "test_postgres" is being accessed by other users
DETAIL:  There is 1 other session using the database.

0 个答案:

没有答案