Debian Codegraph @

docs/testing.rst

raw
1 Testing Apps That Use Flask-Dance
2 =================================
3
4 Automated tests are a great way to keep your Flask app stable
5 and working smoothly. The Flask documentation has
6 :doc:`some great information on how to write automated tests
7 for Flask apps <flask:testing>`.
8
9 However, Flask-Dance presents some challenges for writing tests.
10 What happens when you have a view function that requires OAuth
11 authorization? How do you handle cases where the user has a valid
12 OAuth token, an expired token, or no token at all?
13 Fortunately, we've got you covered.
14
15 Mock Storages
16 -------------
17
18 The simplest way to write tests with Flask-Dance is to use a
19 mock token storage. This allows you to easily control
20 whether Flask-Dance believes the current user is authorized
21 with the OAuth provider or not. Flask-Dance provides two
22 mock token storages:
23
24 .. currentmodule:: flask_dance.consumer.storage
25
26 .. autoclass:: NullStorage
27
28 .. autoclass:: MemoryStorage
29
30 Let's say you are testing the following code::
31
32 from flask import redirect, url_for
33 from flask_dance.contrib.github import make_github_blueprint, github
34
35 app = Flask(__name__)
36 github_bp = make_github_blueprint()
37 app.register_blueprint(github_bp, url_prefix="/login")
38
39 @app.route("/")
40 def index():
41 if not github.authorized:
42 return redirect(url_for("github.login"))
43 return "You are authorized"
44
45 You want to write tests to cover two cases: what happens when the user
46 is authorized with the OAuth provider, and what happens when they are not.
47 Here's how you could do that with `pytest`_ and the :class:`MemoryStorage`:
48
49 .. code-block:: python
50 :emphasize-lines: 6, 16
51
52 from flask_dance.consumer.storage import MemoryStorage
53 from myapp import app, github_bp
54
55 def test_index_unauthorized(monkeypatch):
56 storage = MemoryStorage()
57 monkeypatch.setattr(github_bp, "storage", storage)
58
59 with app.test_client() as client:
60 response = client.get("/", base_url="https://example.com")
61
62 assert response.status_code == 302
63 assert response.headers["Location"] == "https://example.com/login/github"
64
65 def test_index_authorized(monkeypatch):
66 storage = MemoryStorage({"access_token": "fake-token"})
67 monkeypatch.setattr(github_bp, "storage", storage)
68
69 with app.test_client() as client:
70 response = client.get("/", base_url="https://example.com")
71
72 assert response.status_code == 200
73 text = response.get_data(as_text=True)
74 assert text == "You are authorized"
75
76 In this example, we're using the
77 `monkeypatch fixture <https://docs.pytest.org/en/latest/how-to/monkeypatch.html>`__
78 to set a mock storage on the Flask-Dance blueprint. This fixture will
79 ensure that the original storage is put back on the blueprint after the
80 test is finished, so that the test doesn't change the code being tested.
81 Then, we create a test client and access the ``index`` view.
82 The mock storage will control whether ``github.authorized`` is ``True``
83 or ``False``, and the rest of the test asserts that the result is what
84 we expect.
85
86 Mock API Responses
87 ------------------
88
89 Once you've gotten past the question of whether the current user is
90 authorized or not, you still have to account for any API calls that
91 your view makes. It's usually a bad idea to make real API calls in an
92 automated test: not only does it make your tests run significantly
93 more slowly, but external factors like rate limits can affect whether
94 your tests pass or fail.
95
96 There are several other libraries that you can use to mock API responses,
97 but I recommend Betamax_. It's powerful, flexible, and it's designed
98 to work with Requests_, the HTTP library that Flask-Dance is built on.
99 Betamax is also created and maintained by one of the primary maintainers
100 of the Requests library, `@sigmavirus24`_.
101
102 Let's say your testing the same code as before, but now the ``index``
103 view looks like this::
104
105 @app.route("/")
106 def index():
107 if not github.authorized:
108 return redirect(url_for("github.login"))
109 resp = github.get("/user")
110 return "You are @{login} on GitHub".format(login=resp.json()["login"])
111
112 Here's how you could test this view using Betamax::
113
114 import os
115 from flask_dance.consumer.storage import MemoryStorage
116 from flask_dance.contrib.github import github
117 import pytest
118 from betamax import Betamax
119 from myapp import app as _app
120 from myapp import github_bp
121
122 with Betamax.configure() as config:
123 config.cassette_library_dir = 'cassettes'
124
125 @pytest.fixture
126 def app():
127 return _app
128
129 @pytest.fixture
130 def betamax_github(app, request):
131
132 @app.before_request
133 def wrap_github_with_betamax():
134 recorder = Betamax(github)
135 recorder.use_cassette(request.node.name)
136 recorder.start()
137
138 @app.after_request
139 def unwrap(response):
140 recorder.stop()
141 return response
142
143 request.addfinalizer(
144 lambda: app.after_request_funcs[None].remove(unwrap)
145 )
146
147 request.addfinalizer(
148 lambda: app.before_request_funcs[None].remove(wrap_github_with_betamax)
149 )
150
151 return app
152
153 @pytest.mark.usefixtures("betamax_github")
154 def test_index_authorized(app, monkeypatch):
155 access_token = os.environ.get("GITHUB_OAUTH_ACCESS_TOKEN", "fake-token")
156 storage = MemoryStorage({"access_token": access_token})
157 monkeypatch.setattr(github_bp, "storage", storage)
158
159 with app.test_client() as client:
160 response = client.get("/", base_url="https://example.com")
161
162 assert response.status_code == 200
163 text = response.get_data(as_text=True)
164 assert text == "You are @singingwolfboy on GitHub"
165
166 In this example, we first
167 :doc:`configure Betamax globally <betamax:configuring>`
168 so that it stores cassettes (recorded HTTP interactions) in the ``cassettes``
169 directory. Betamax expects you to commit these cassettes to your repository,
170 so that if the HTTP interactions change, that will show up in code review.
171
172 Next, we define a utility function that will wrap Betamax around the ``github``
173 :class:`~requests.Session` object at the start of the incoming HTTP request,
174 and unwrap it afterwards.
175 This allows Betamax to record and intercept HTTP requests
176 during the test. Note that we also use ``request.addfinalizer`` to remove
177 these "before_request" and "after_request" functions, so that they don't
178 interfere with other tests. If you are recreating your ``app`` object
179 from scratch each time using
180 :doc:`the application factory pattern <flask:patterns/appfactories>`,
181 you don't need to include these ``request.addfinalizer`` lines.
182
183 In the actual test, we check for the :envvar:`GITHUB_OAUTH_ACCESS_TOKEN`
184 environment variable. When recording a cassette with Betamax, it will
185 send real HTTP requests to the OAuth provider, so you'll need to include
186 a real OAuth access token if you expect the API call to succeed.
187 However, once the cassette has been recorded, you can re-run the tests
188 without setting this environment variable.
189
190 Also notice that you can (and should!) make assertions in your test that
191 expect a particular API response. In this test, I assert that the current
192 user is named ``@singingwolfboy``. I can do that, because when I recorded
193 the cassette, that was the GitHub user that I used. When the cassette is
194 replayed in the future, the API response will always be the same, so
195 I can write my assertions expecting that.
196
197 Provided Pytest Fixture
198 -----------------------
199
200 .. automodule:: flask_dance.fixtures.pytest
201
202 .. _pytest: https://docs.pytest.org/
203 .. _Betamax: https://github.com/betamaxpy/betamax
204 .. _Requests: https://requests.kennethreitz.org/
205 .. _@sigmavirus24: https://github.com/sigmavirus24/