Debian Codegraph @

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