0

I have written an endpoint in my flask server, that when triggered, with a GET request, and a parameter, the server will parse the parameter, and serve the file (specified in the parameter) to the user to download.

This is the server's code:

@app.route('/getfile', methods=['GET'])
def dl_file():
   requestedFile = request.args.get('id')
   allFiles = os.listdir('myFiles')
   if requestedFile not in allFiles:
      return make_response(json.dumps({'error_message': 'item does not exist'}), 400)
   else:
      return send_file(pathAndFilename, as_attachment=True, attachment_filename = requestedFile)

I am able to trigger this with:

curl -X GET "0000:5000/getfile?id=myFile.txt"

How do i trigger this in pytest?

But i do not know how to pass the parameter in the GET request, and how to grab the server's response.

user1584421
  • 3,499
  • 11
  • 46
  • 86

1 Answers1

1

You should be able to pass those parameters as you do when performing curl requests, ie.

response = client.get('/getfile?id=myFile.txt')

Alternatively, you can use Python's standard library, urllib and its urlencode method.

In [1]: import urllib

In [2]: data = {'id': 'myFile.txt'}

In [3]: urllib.parse.urlencode(data)
Out[3]: 'id=myFile.txt'

This can be combined together:

import urllib

@pytest.mark.parametrize("filename, status, error_message_template", [
        ('myFile.txt', 200, 'null'),
        ('does_not_exist.txt', 400, 'item does not exist')
            ])

def test_dl_file(change_directory, filename, status, error_message_template):
   client = app.test_client()
   data = {"id": filename}
   query = urllib.parse.urlencode(data)
   response = client.get('/getfile' + query)
user1584421
  • 3,499
  • 11
  • 46
  • 86
gonczor
  • 3,994
  • 1
  • 21
  • 46