Debian Codegraph @

tests/contrib/test_fitbit.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.fitbit import fitbit, make_fitbit_blueprint
9
10
11 @pytest.fixture
12 def make_app():
13 "A callable to create a Flask app with the Fitbit provider"
14
15 def _make_app(*args, **kwargs):
16 app = Flask(__name__)
17 app.secret_key = "whatever"
18 blueprint = make_fitbit_blueprint(*args, **kwargs)
19 app.register_blueprint(blueprint)
20 return app
21
22 return _make_app
23
24
25 def test_blueprint_factory():
26 fitbit_bp = make_fitbit_blueprint(
27 client_id="foo", client_secret="bar", scope="user:email", redirect_to="index"
28 )
29 assert isinstance(fitbit_bp, OAuth2ConsumerBlueprint)
30 assert fitbit_bp.session.scope == "user:email"
31 assert fitbit_bp.session.base_url == "https://api.fitbit.com/"
32 assert fitbit_bp.session.client_id == "foo"
33 assert fitbit_bp.client_secret == "bar"
34 assert fitbit_bp.authorization_url == "https://www.fitbit.com/oauth2/authorize"
35 assert fitbit_bp.token_url == "https://api.fitbit.com/oauth2/token"
36
37
38 def test_load_from_config(make_app):
39 app = make_app()
40 app.config["FITBIT_OAUTH_CLIENT_ID"] = "foo"
41 app.config["FITBIT_OAUTH_CLIENT_SECRET"] = "bar"
42
43 resp = app.test_client().get("/fitbit")
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 `fitbit` object
68 # will raise an exception
69 with pytest.raises(RuntimeError):
70 fitbit.get("https://google.com")
71
72 # inside of a request context, `fitbit` should be a proxy to the correct
73 # blueprint session
74 with app1.test_request_context("/"):
75 app1.preprocess_request()
76 fitbit.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 fitbit.get("https://google.com")
83 request = responses.calls[1].request
84 assert request.headers["Authorization"] == "Bearer app2"