Testing file uploads in Flask

前端 未结 4 419
庸人自扰
庸人自扰 2021-02-02 07:32

I\'m using Flask-Testing for my Flask integration tests. I\'ve got a form that has a file upload for a logo that I\'m trying to write tests for but I keep getting an error sayin

4条回答
  •  太阳男子
    2021-02-02 08:07

    You can use Werkzeug's FileStorage (as used by Flask under the hood).

    You can mock a file like this:

    from werkzeug.datastructures import FileStorage
    import io
    import json
    
    # Here we are mocking a JSON file called Input.json
    my_dict = {"msg": "hello!"}
    input_json = json.dumps(my_dict, indent=4).encode("utf-8")
    
    mock_file = FileStorage(
        stream=io.BytesIO(input_json),
        filename="Input.json",
        content_type="application/json",
    )
    

    Notice that I use a real file on my server: tests/assets/my_video.mp4

    from werkzeug.datastructures import FileStorage
    
    
    my_video = os.path.join("tests/assets/my_video.mp4")
    
    my_file = FileStorage(
        stream=open(my_video, "rb"),
        filename="my_video.mp4",
        content_type="video/mpeg",
    ),
    
    rv = client.post(
       "/api/v1/video",
       data={
          "my_video": my_file,
       },
       content_type="multipart/form-data"
    )
    

    Test to see it returns a response status code of 200:

    assert "200" in rv.status
    

    I can then test that the file arrives in a test directory on the server:

    assert "my_video.mp4" in os.listdir("tests/my_test_path")
    

    Also note, you need to set the mocked file to None on teardown otherwise you'll get a ValueError: I/O operation on closed file. . Below is a Pytest example:

        def setup_method(self):
            self.mock_file = FileStorage(
                stream=io.BytesIO(input_json),
                filename="Input.json",
                content_type="application/json",
            )
    
        def teardown_method(self):
            self.mock_file = None
    

提交回复
热议问题