Debian Codegraph @

tests/contrib/test_jira.py

raw
1 import os
2 import tempfile
3 from unittest import mock
4
5 import pytest
6 import responses
7 from flask import Flask
8 from oauthlib.oauth1.rfc5849.utils import parse_authorization_header
9
10 from flask_dance.consumer import OAuth1ConsumerBlueprint
11 from flask_dance.consumer.storage import MemoryStorage
12 from flask_dance.contrib.jira import jira, make_jira_blueprint
13
14
15 @pytest.fixture
16 def make_app():
17 "A callable to create a Flask app with the JIRA provider"
18
19 def _make_app(*args, **kwargs):
20 app = Flask(__name__)
21 app.secret_key = "whatever"
22 blueprint = make_jira_blueprint(*args, **kwargs)
23 app.register_blueprint(blueprint)
24 return app
25
26 return _make_app
27
28
29 def test_blueprint_factory():
30 jira_bp = make_jira_blueprint(
31 consumer_key="foobar",
32 rsa_key="supersecret",
33 base_url="https://flask.atlassian.net",
34 redirect_to="index",
35 )
36 assert isinstance(jira_bp, OAuth1ConsumerBlueprint)
37 assert jira_bp.session.base_url == "https://flask.atlassian.net"
38 assert jira_bp.session.auth.client.client_key == "foobar"
39 assert jira_bp.session.auth.client.rsa_key == "supersecret"
40 assert (
41 jira_bp.request_token_url
42 == "https://flask.atlassian.net/plugins/servlet/oauth/request-token"
43 )
44 assert (
45 jira_bp.access_token_url
46 == "https://flask.atlassian.net/plugins/servlet/oauth/access-token"
47 )
48 assert (
49 jira_bp.authorization_url
50 == "https://flask.atlassian.net/plugins/servlet/oauth/authorize"
51 )
52
53
54 def test_blueprint_factory_rule_kwargs(make_app):
55 app = make_app(
56 "https://flask.atlassian.net",
57 redirect_to="index",
58 rule_kwargs={"host": "example2.com"},
59 )
60 rules = [
61 rule for rule in app.url_map.iter_rules() if rule.endpoint.startswith("jira.")
62 ]
63 assert all(rule.host == "example2.com" for rule in rules)
64 assert len(rules) == 2
65
66
67 def test_blueprint_factory_no_rule_kwargs(make_app):
68 app = make_app(
69 "https://flask.atlassian.net",
70 redirect_to="index",
71 )
72 rules = [
73 rule for rule in app.url_map.iter_rules() if rule.endpoint.startswith("jira.")
74 ]
75 assert all(rule.host is None for rule in rules)
76 assert len(rules) == 2
77
78
79 def test_rsa_key_file(tmp_path):
80 rsa_key = tmp_path / "fake.key"
81 rsa_key.write_text("my-fake-key")
82
83 jira_bp = make_jira_blueprint(
84 rsa_key=str(rsa_key), base_url="https://flask.atlassian.net"
85 )
86 assert jira_bp.rsa_key == "my-fake-key"
87
88
89 @responses.activate
90 @mock.patch(
91 "oauthlib.oauth1.rfc5849.Client.get_oauth_signature", return_value="fakesig"
92 )
93 def test_load_from_config(sign_func, make_app):
94 responses.add(
95 responses.POST,
96 "https://flask.atlassian.net/plugins/servlet/oauth/request-token",
97 body="oauth_token=faketoken&oauth_token_secret=fakesecret",
98 )
99 app = make_app("https://flask.atlassian.net", redirect_to="index")
100 app.config["JIRA_OAUTH_CONSUMER_KEY"] = "foo"
101 app.config["JIRA_OAUTH_RSA_KEY"] = "bar"
102
103 resp = app.test_client().get("/jira")
104 assert len(responses.calls) > 0
105 auth_header = dict(
106 parse_authorization_header(
107 responses.calls[0].request.headers["Authorization"].decode("utf-8")
108 )
109 )
110 assert auth_header["oauth_consumer_key"] == "foo"
111 sign_func.assert_called()
112 request = sign_func.call_args[0][0]
113 assert dict(request.oauth_params)["oauth_signature"] == "fakesig"
114
115
116 @responses.activate
117 @mock.patch(
118 "oauthlib.oauth1.rfc5849.Client.get_oauth_signature", return_value="fakesig"
119 )
120 def test_content_type(sign_func, make_app):
121 responses.add(responses.GET, "https://flask.atlassian.net/")
122
123 storage = MemoryStorage(
124 {
125 "oauth_token": "faketoken",
126 "oauth_token_secret": "fakesecret",
127 "oauth_session_handle": "fakehandle",
128 "oauth_expires_in": "157680000",
129 "oauth_authorization_expires_in": "160272000",
130 }
131 )
132 app = make_app(
133 "https://flask.atlassian.net",
134 rsa_key="fakersa",
135 consumer_key="fakekey",
136 storage=storage,
137 )
138
139 @app.route("/test")
140 def api_request():
141 jira.get("/")
142 return "success"
143
144 resp = app.test_client().get("/test")
145 assert len(responses.calls) > 0
146 headers = responses.calls[0].request.headers
147 assert "Content-Type" in headers
148 assert headers["Content-Type"] == b"application/json"
149
150
151 @responses.activate
152 def test_context_local():
153 responses.add(responses.GET, "https://google.com")
154
155 # set up two apps with two different set of auth tokens
156 app1 = Flask(__name__)
157 jbp1 = make_jira_blueprint(
158 "https://t1.atlassian.com", "foo1", "bar1", redirect_to="url1"
159 )
160 app1.register_blueprint(jbp1)
161
162 app2 = Flask(__name__)
163 jbp2 = make_jira_blueprint(
164 "https://t2.atlassian.com", "foo2", "bar2", redirect_to="url2"
165 )
166 app2.register_blueprint(jbp2)
167
168 # outside of a request context, referencing functions on the `jira` object
169 # will raise an exception
170 with pytest.raises(RuntimeError):
171 jira.get("https://google.com")
172
173 # inside of a request context, `jira` should be a proxy to the correct
174 # blueprint session
175 with app1.test_request_context("/"):
176 jbp1.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig1")
177 jbp2.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig2")
178
179 app1.preprocess_request()
180 jira.get("https://google.com")
181 assert len(responses.calls) > 0
182 auth_header = dict(
183 parse_authorization_header(
184 responses.calls[0].request.headers["Authorization"].decode("utf-8")
185 )
186 )
187 assert auth_header["oauth_consumer_key"] == "foo1"
188 assert auth_header["oauth_signature"] == "sig1"
189
190 with app2.test_request_context("/"):
191 jbp1.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig1")
192 jbp2.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig2")
193
194 app2.preprocess_request()
195 jira.get("https://google.com")
196 assert len(responses.calls) > 0
197 auth_header = dict(
198 parse_authorization_header(
199 responses.calls[1].request.headers["Authorization"].decode("utf-8")
200 )
201 )
202 assert auth_header["oauth_consumer_key"] == "foo2"
203 assert auth_header["oauth_signature"] == "sig2"