3

I'm trying to implement unit tests for a Flask application using pytest-flask. The output of my queries is dependent on the current time.

For consistent unit tests, I'm trying to freeze the time. I'm used to freezegun so here is what I tried:

# Session for scope, otherwise server is reloaded everytime
@pytest.fixture(scope="session")
@freeze_time("2018-04-15")
def app():

    os.environ["FLASK_ENV"] = "development"

    app = create_app()

    # http://flask.pocoo.org/docs/1.0/api/#flask.Flask.test_client
    app.testing = True

    return app

@pytest.mark.usefixtures("live_server")
class TestLiveServer:

    # Freeze time to get consistent output.
    @freeze_time("2018-04-15")
    def test_export(self):

        q = "Chocapic"

        r = requests.post(
            url_for("query_direct", _external=True), json={"query": q}
        )
        print(r.text)

        export_path = os.path.join("tests", "fake_responses", q)

        with open(export_path, "w") as outfile:
            json.dump(r.json(), outfile, indent=4)

        with open(export_path, "r") as infile:
            data = json.load(infile)

        assert r.json() == data

I can see in the logs that my app is started with the proper frozen time. But when the tests run, I can see that querying the endpoint is done with the real current time. It seems that the fixture live_server resets the current time.

Have you ever encountered this issue?

JPFrancoia
  • 4,866
  • 10
  • 43
  • 73

1 Answers1

0

According the documentation the liver_server fixture runs the application in a separate process. Probably, Freezegun cannot do its trick in other processes, only in the current process.

Do you really need the live server? I run all my tests without the live server.

Perhaps you can split your tests in two groups? Use Freezegun to get reproducible responses without the live server and use the live server only to test whatever you need the live server for (Javascript? Selenium?).

gogognome
  • 727
  • 8
  • 24