Reputation: 2125
I've built the flask app that designed to run inside docker container. It will
accept POST HTTP Methods and return appropriate JSON response if the header key matched with the key that I put inside docker-compose environment
.
...
environment:
- SECRET_KEY=fakekey123
...
The problem is: when it comes to testing. The app
or the client
fixture of
flask (pytest) of course can't find the docker-compose environment
. Cause the app didn't start from docker-compose but from pytest.
secret_key = os.environ.get("SECRET_KEY")
# ^^ the key loaded to OS env by docker-compose
post_key = headers.get("X-Secret-Key")
...
if post_key == secret_key:
RETURN APPROPRIATE RESPONSE
.....
What is the (best/recommended) approach to this problem?
I find some plugins one, two, three to do this. But I asked here if there is any more "simple"/"common" approach. Cause I also want to automate this test using CI/CD tools.
Upvotes: 6
Views: 4909
Reputation: 2125
My current solution is to mock the function that read the OS environment. OS ENV is loaded if the app started using docker. In order to make it easy for the test, I just mock that function.
def fake_secret_key(self):
return "ffakefake11"
def test_app(self, client):
app.secret_key = self.fake_secret_key
# ^^ real func ^^ fake func
Or another alternative is using pytest-env as @bufh suggested in comment.
Create pytest.ini
file, then put:
[pytest]
env =
APP_KEY=ffakefake11
Upvotes: 0
Reputation: 927
You most likely need to run py.test
from inside of your container. If you are running locally, then there's going to be a conflict between what your host machine is seeing and what your container is seeing.
So option #1 would be to using docker exec
:
$ docker exec -it $containerid py.test
Then option #2 would be to create a script or task in your setup.py
so that you can run a simpler command like:
$ python setup.py test
Upvotes: 5