jeudi 22 octobre 2020

Mocking External Service Call in Flask App

I'm trying to write tests for my flask app that has a very simple flow. It receives a string in its json, posts to an external api, gets data back, then returns the data. It looks like the following:

import requests
import flask
from flask import request, jsonify, make_response
from xml.etree import ElementTree
import os


app = flask.Flask(__name__)


port = int(os.getenv("PORT"))
base_url = os.getenv("URL")




@app.route('/my-route', methods=['POST'])
def authenticate():
    data = request.get_json()
    string_in_json = data['string_in_the_json']


    passing_parameter = f"String={string_in_json}"


    r = requests.get(f'{base_url}?{passing_parameter}')
    return make_response(jsonify(response_text=r.text), 200)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)

I'm trying to write a test for it where when authenticate() is called, it doesn't actually call the requests.get but instead just returns the status code of 200 and a json of {"test_string": "test"} I tried the following:

from my_api import app
from flask import json
from unittest.mock import Mock, patch
import unittest


class TestAuthenticate(unittest.TestCase):
    
    @patch('authenticate')
    def test_authenticate(self, api):
        with app.test_client() as client:
            sent = {'return_url'}
            api.return_value.ok = True
        
            response = app.authenticate()
        
            assert response.status_code == 200

But it gives me an error saying the authenticate module doesn't exist. How do I get this to work? I'd also prefer to use pytest, but I'm not sure what the procedures look like for it.

Aucun commentaire:

Enregistrer un commentaire