0

I'm using a application factory pattern, and when I tried to run my test, I get "Attempted to generate a URL without the application context being". I created a fixture to create the application:

@pytest.fixture
def app():
    yield create_app()

but when I run my test

    def test_get_activation_link(self, app):
        user = User()
        user.set_password(self.VALID_PASS)
        generated_link = user.get_activation_link()

I get the above error (from the line of code url = url_for("auth.activate")). I'm also trying to figure out to have the app creation run for every test, without having to import it into every test, but I can't seem to find if that's possible.

Rohit
  • 3,018
  • 2
  • 29
  • 58
  • Have you read https://flask.palletsprojects.com/en/1.1.x/testing/ ? If you get stuck with this doc, I will prepare a complete answer later, or tomorrow morning. – Jürgen Gmach Aug 25 '20 at 18:03
  • @J.G. Yah, I did read through that, which is why I created that simple fixture above. I didn't really get that example, as I didn't do the tutorial and didn't understand how the app is being instantiated. I feel like I'm on the crux of understanding something, but I'm missing a detail. – Rohit Aug 25 '20 at 19:55

1 Answers1

3

This works for my app

import pytest
from xxx import create_app


@pytest.fixture
def client():
    app = create_app()
    app.config['TESTING'] = True

    with app.app_context():
        with app.test_client() as client:
            yield client


def smoke_test_homepage(client):
    """basic tests to make sure test setup works"""
    rv = client.get("/")
    assert b"Login" in rv.data

So, you missed the application context.

At this year's Flaskcon there was an excellent talk about the Flask context - I highly recommend this video.

https://www.youtube.com/watch?v=fq8y-9UHjyk

Jürgen Gmach
  • 5,366
  • 3
  • 20
  • 37
  • Thanks! I'll read up on the context. As the app runs without needing to create a context (manually anyway), I had no idea I needed to do so for the tests. I'll try implementing your example this evening and watch the video as soon as I can. – Rohit Aug 25 '20 at 21:24
  • 1
    Cool, looks like this solved one problem, though now I've hit another one, saying it can't create a URL adapter. I'll post up another question. – Rohit Aug 26 '20 at 02:16
  • Thanks for your feedback! I have not came across this problem, but maybe that question helps... https://stackoverflow.com/questions/31766082 – Jürgen Gmach Aug 26 '20 at 05:55
  • 1
    I actually figured that one out! `SERVER_NAME` ends up giving a full URL, which I didn't want. I found out in tests, you can create a test request, which solves the issue. Weird functionality IMO, but I'm sure it makes sense under the hood. – Rohit Aug 26 '20 at 14:03