Debian Codegraph @

tests/contrib/test_heroku.py

raw
1 import pytest
2 import responses
3 from flask import Flask
4 from urlobject import URLObject
5
6 from flask_dance.consumer import OAuth2ConsumerBlueprint
7 from flask_dance.consumer.storage import MemoryStorage
8 from flask_dance.contrib.heroku import heroku, make_heroku_blueprint
9
10
11 @pytest.fixture
12 def make_app():
13 "A callable to create a Flask app with the Heroku provider"
14
15 def _make_app(*args, **kwargs):
16 app = Flask(__name__)
17 app.secret_key = "whatever"
18 blueprint = make_heroku_blueprint(*args, **kwargs)
19 app.register_blueprint(blueprint)
20 return app
21
22 return _make_app
23
24
25 def test_blueprint_factory():
26 heroku_bp = make_heroku_blueprint(
27 client_id="foo", client_secret="bar", scope="global", redirect_to="index"
28 )
29 assert isinstance(heroku_bp, OAuth2ConsumerBlueprint)
30 assert heroku_bp.session.scope == "global"
31 assert heroku_bp.session.base_url == "https://api.heroku.com/"
32 assert heroku_bp.session.client_id == "foo"
33 assert heroku_bp.client_secret == "bar"
34 assert heroku_bp.authorization_url == "https://id.heroku.com/oauth/authorize"
35 assert heroku_bp.token_url == "https://id.heroku.com/oauth/token"
36
37
38 def test_load_from_config(make_app):
39 app = make_app()
40 app.config["HEROKU_OAUTH_CLIENT_ID"] = "foo"
41 app.config["HEROKU_OAUTH_CLIENT_SECRET"] = "bar"
42
43 resp = app.test_client().get("/heroku")
44 url = resp.headers["Location"]
45 client_id = URLObject(url).query.dict.get("client_id")
46 assert client_id == "foo"
47
48
49 @responses.activate
50 def test_context_local(make_app):
51 responses.add(responses.GET, "https://google.com")
52
53 # set up two apps with two different set of auth tokens
54 app1 = make_app(
55 "foo1",
56 "bar1",
57 redirect_to="url1",
58 storage=MemoryStorage({"access_token": "app1"}),
59 )
60 app2 = make_app(
61 "foo2",
62 "bar2",
63 redirect_to="url2",
64 storage=MemoryStorage({"access_token": "app2"}),
65 )
66
67 # outside of a request context, referencing functions on the `heroku` object
68 # will raise an exception
69 with pytest.raises(RuntimeError):
70 heroku.get("https://google.com")
71
72 # inside of a request context, `heroku` should be a proxy to the correct
73 # blueprint session
74 with app1.test_request_context("/"):
75 app1.preprocess_request()
76 heroku.get("https://google.com")
77 request = responses.calls[0].request
78 assert request.headers["Authorization"] == "Bearer app1"
79
80 with app2.test_request_context("/"):
81 app2.preprocess_request()
82 heroku.get("https://google.com")
83 request = responses.calls[1].request
84 assert request.headers["Authorization"] == "Bearer app2"