简体   繁体   English

Django:如何使用rest_framework中的APIClient在单元测试用例中上传CSV文件

[英]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).系统检查未发现任何问题(0 静音)。 .F. 。F。

FAIL: test_upload_csv_success (core.tests.test_csv_api.CsvUploadTests) Test uploading a csv file失败:test_upload_csv_success (core.tests.test_csv_api.CsvUploadTests) 测试上传 csv 文件

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回溯(最近一次通话):文件“/Users/rounaktadvi/django_rest_api_projects/csv-store-api/core/tests/test_csv_api.py”,第 56 行,在 test_upload_csv_success self.assertEqual(res.status_code, status.HTTP_201_CREATTIONError) : 400 != 201

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用传递参数并从rest_framework请求JSON的Django测试客户端发布方法创建单元测试 - Create a unit test using Django's test client post method passing parameters and requesting JSON from rest_framework 创建删除用户单元测试 Django rest_framework - Creating Delete User Unit Test Django rest_framework 使用Django Rest Framework中APIClient的帖子测试将多个文件上传到模型视图集 - Testing multiple file upload to a model viewset using APIClient's post in Django Rest Framework 如何使Django rest_framework会话身份验证不区分大小写? - How to make Django rest_framework Session Authentication case insensitive? 如何使用PUT在Django rest框架中测试文件上传? - How to test file upload in Django rest framework using PUT? 如何使用django rest_framework序列化带有直通模型的ManyToManyFields - How to serialize using django rest_framework a ManyToManyFields with a Through Model 如何使用rest_framework和Django获取多个对象的响应 - How to get a response of multiple objects using rest_framework and Django 如何使用django rest框架APIClient测试登录后生成的oauth访问令牌? - How to use django rest framework APIClient to test oauth access token generated after login? [Django rest_framework]使用redis作为Django DRF缓存的问题 - [Django rest_framework]Problems in using redis as Django DRF cache Django rest_framework关系 - Django rest_framework relations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM