Skip to content
Advertisement

Flask testing with pytest, ENV is set to production?

I have built a flask app and i would like to create a test suite. Reading around it looks like pytest is the way to go; however, I am finding it very difficult to understand how to get going, I have looked at https://flask.palletsprojects.com/en/2.0.x/testing/ but am struggling to relate it to my app.

my project has a run.py at its base:

JavaScript

this is run using flask run and the .flaskenv sets the mode

JavaScript

I have an application factory set up:

JavaScript

Everything works and I can run the app on a production server. I am trying to get started with pytest and have set up conftest.py:

JavaScript

this always runs the app in production mode, how do I get it to run in testing mode so that it uses the correct config from config.py

JavaScript

If there is a good tutorial that I have missed I’d be pleased to hear.

Advertisement

Answer

What is Dotenv

Use Dotenv package

JavaScript
JavaScript

How to use it in youre case

Option 1

You can use this to store an Boolean in .env file and read it to define wich mode you are running. be careful as env variables get read as string. if you wanna use boolean you need to parse them from the string.

Option 2

An other option is to store in env file which config you wanna use and make an if else tree in python script:

JavaScript

Why use Dotenv

The advantage of using environment variables is that you can ignore them in git and every time the server is seetup in linux or docker all settings can be managed from one file. also does the standart server admin know bash script and env files but not necesseraly python.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement