Background
I would like to write a unittest for my Flask application which utilize an external API on some routes.
When running my tests I don't want to make any calls to the external API, rather, I want to pass some static dummy data to the route.
This is how I currently have everything set up. I can't figure out how to refactor my code to achieve what I want.
get_name.py:
from flask import render_template, Blueprint, request, redirect, url_for, session
name_blueprint = Blueprint('name_blueprint', __name__)
@name_blueprint.route("/name", methods=['POST', 'GET'])
def name():
name = requests.get('https://name.com/getname') <<< Let's say this api call returns 'Bob'
return render_template('name.html', name=name)
init.py
from flask import Flask
from app.name.get_name import name_blueprint
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some-secret-key'
app.register_blueprint(name_blueprint)
return app
name.html
<!DOCTYPE html>
<html>
<body>
<h1></h1>
</body>
</html>
I want to be able to mock the API call and instead of receiving name from the server I want to pass some dummy data to it.
import unittest
from unittest.mock import patch
from flask_testing import LiveServerTestCase
from selenium import webdriver
class TestName(LiveServerTestCase):
def create_app(self):
app = create_app()
app.config['TESTING'] = True
app.config.update(LIVESERVER_PORT=9898)
return app
def setUp(self):
self.driver = webdriver.Chrome()
def test_name_route(self):
self.driver.get(f'{self.driver.get(self.get_server_url())}/name')
with patch('get_name.requests.get') as mocked_get:
mocked_get.return_value.text = 'Michael'
res_name = self.driver.find_element_by_tag_name('h1')
self.assert res_name == 'Michael'
if __name__ == '__main__':
unittest.main()
Aucun commentaire:
Enregistrer un commentaire