Reputation: 71
I have this code which used to work:
import unittest
from flask import url_for
from dm.web import create_app, db
class TestApi(unittest.TestCase):
def setUp(self):
"""Create and configure a new app instance for each test."""
self.app = create_app('test')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
def tearDown(self) -> None:
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_url(self):
self.assertEqual('/', url_for('root.home'))
if __name__ == '__main__':
unittest.main()
But since today I am getting this error:
ERROR: test_url (__main__.TestApi)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/joan/.PyCharmCE2019.3/config/scratches/scratch.py", line 17, in test_url
self.assertEqual('/', url_for('root.home'))
File "/home/joan/venvs/dimensigon3.7/lib/python3.7/site-packages/flask/helpers.py", line 333, in url_for
"Application was not able to create a URL adapter for request"
RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.
From what I see in the url_for, I am getting None on the appctx.url_adapter which I don't know when it is set.
Thanks!
Upvotes: 7
Views: 8526
Reputation: 5578
As per this blog post, you could try this pattern, which gives you both an app context and a temporary request context:
def test_url(self):
with app.app_context(), app.test_request_context():
self.assertEqual('/', url_for('root.home'))
Upvotes: 15