Debian Codegraph @

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