rounak tadvi
rounak tadvi

Reputation: 29

Django : How to upload CSV file in unit test case using APIClient from rest_framework

def test_upload_csv_success(self):
    """Test uploading a csv file"""
    
    with open("innovators.csv", "w") as file:
        writer = csv.writer(file)
        writer.writerow(["SN", "Name", "Contribution"])
        writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
        writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
        writer.writerow([3, "Guido van Rossum", "Python Programming"])                       
        
    with open("innovators.csv", "r") as file:              
        res = self.client.post(
            CSV_URL, {"file": file}, content_type="multipart/form-data"
        )        
    file.close()

    

    self.assertEqual(res.status_code, status.HTTP_201_CREATED)
    #self.assertIn('file', res.data)
    #self.assertTrue(os.path.exists(self.csv_model.file.path))

Below is the error, I/m getting

System check identified no issues (0 silenced). .F.

FAIL: test_upload_csv_success (core.tests.test_csv_api.CsvUploadTests) Test uploading a csv file

Traceback (most recent call last): File "/Users/rounaktadvi/django_rest_api_projects/csv-store-api/core/tests/test_csv_api.py", line 56, in test_upload_csv_success self.assertEqual(res.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201

Upvotes: 0

Views: 1192

Answers (1)

rounak tadvi
rounak tadvi

Reputation: 29

I figured it, out here's what i did

@patch("pandas.read_csv")
@patch("pandas.DataFrame.to_sql")
def test_upload_csv_success(self, mock_read_csv, mock_to_sql) -> None:
    """Test uploading a csv file"""
    file_name = "test.csv"
    # Open file in write mode (Arrange)
    with open(file_name, "w") as file:
        writer = csv.writer(file)
        # Add some rows in csv file
        writer.writerow(["name", "area", "country_code2", "country_code3"])
        writer.writerow(
            ["Albania", 28748, "AL", "ALB"],
        )
        writer.writerow(
            ["Algeria", 2381741, "DZ", "DZA"],
        )
        writer.writerow(
            ["Andorra", 468, "AD", "AND"],
        )
    # open file in read mode
    data = open(file_name, "rb")
    # Create a simple uploaded file
    data = SimpleUploadedFile(
        content=data.read(), name=data.name, content_type="multipart/form-data"
    )

    # Perform put request (Act)
    res = self.client.put(CSV_URL, {"file_name": data}, format="multipart")
    # Mock read_csv() and to_sql() functions provided by pandas module
    mock_read_csv.return_value = True
    mock_to_sql.return_value = True

    # Assert
    self.assertEqual(res.status_code, status.HTTP_201_CREATED)
    self.assertEqual(res.data, "Data set uploaded")
    # Delete the test csv file
    os.remove(file_name)

Upvotes: 0

Related Questions