Debian Codegraph @

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