0

When testing my Flask application with Pytest I run into connection problems with the database since it is not running. I read that mongomock is often used to mock requests to the database but I am having trouble implementing it to the existing test environment.

For reference my database.py file looks like this:

from flask_pymongo import PyMongo

mongo = PyMongo()

My app.py which is responsible for creating the Flask server looks like this:

from flask import Flask, send_from_directory

def create_app(config_class=BaseConfig):
    app = Flask(__name__)
    app.config.from_object(config_class)

    from .database import mongo

    mongo.init_app(app)
    return app


app = create_app()

Testing different REST endpoints works fine but as soon as a connection to the database needs to be established it times out which makes sense. How do I integrate mocking into my test file?

import json
import pytest

from src.app import app
from src.database import mongo

MIMETYPE = 'application/json'
headers = {
    "Content-Type": MIMETYPE
}

@pytest.fixture
def client():
    app.testing = True
    yield app.test_client()


def test_get_customers(client):
    response = client.get('/api/v1/customers')
    assert response.status_code == 200
    assert response.mimetype == MIMETYPE
    for item in response.json:
        assert item["_id"]
        assert item["name"]
jndr
  • 3
  • 3
  • the db should be passed in to the `create_app` function as opposed to being started inside, that makes testing difficult. rewrite that function then it should be easier to test. – gold_cy May 27 '23 at 14:56

0 Answers0