Using pytest and mongoengine, data is created in the main database instead of a test one
I've installed these packages:
python -m pip install pytest pytest-django
And created a fixture:
# core/services/tests/fixtures/checkout.py
import pytest
from bson import ObjectId
from datetime import datetime
from core.models.src.checkout import Checkout
@pytest.fixture(scope="session")
def checkout(mongo_db):
checkout = Checkout(
user_id=59,
amount=35_641,
)
checkout.save()
return checkout
and imported it in the conftest.py
in the same directory:
# core/service/tests/conftest.py
from core.service.tests.fixtures.checkout import *
Here's how I connect to the test database:
# conftest.py
import pytest
from mongoengine import connect, disconnect, connection
@pytest.fixture(scope="session", autouse=True)
def mongo_db():
connect(
db="db",
name="testdb",
alias="test_db",
host="mongodb://localhost:27017/",
serverSelectionTimeoutMS=5000,
)
connection._connections.clear()
yield
disconnect()
And this is my actual test:
import json
import pytest
from core.service.checkout import a_function
def test_a_function(checkout):
assert checkout.value is False
response = a_function(id=checkout.id, value=True)
assert response.status_code == 200
response_data = json.loads(response.content.decode("UTF-8"))
assert response_data.get("success", None) is True
checkout.reload()
assert checkout.value is True
But every time I run pytest
, a new record is created in the main database. How can I fix this to use a test database?