MongoDB Container Testing
Why MongoDB?
β Perfect for document-based data, flexible schema, and modern web applications. Great for chaos testing in CI/CD pipelines.
β Test Cases Implemented
β Test Case 1 β Check MongoDB Version
Verifies the container is running and accessible.
client = mongo.get_connection_client()
db = client.admin
result = db.command("serverStatus")
assert "version" in result
β Test Case 2 β Insert and Query Document
Tests basic document insertion and retrieval.
db = client.test_db
collection = db.users
result = collection.insert_one({"name": "Alice", "age": 30})
assert result.inserted_id is not None
doc = collection.find_one({"name": "Alice"})
assert doc["age"] == 30
β Test Case 3 β Insert Multiple Documents
Inserts multiple documents and confirms count.
collection = db.users
docs = [{"name": "Bob"}, {"name": "Charlie"}]
result = collection.insert_many(docs)
assert len(result.inserted_ids) == 2
count = collection.count_documents({})
assert count == 3
β Test Case 4 β Update Document
Tests document update functionality.
collection = db.users
collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
doc = collection.find_one({"name": "Alice"})
assert doc["age"] == 31
β Test Case 5 β Delete Documents
Removes documents and verifies deletion.
collection = db.users
collection.delete_many({})
count = collection.count_documents({})
assert count == 0
β How to Run the Tests
Run:
pytest -v testcontainers/test_mongodb_container.py
β Expected:
5 passed in X.XXs
β Useful Commands
- Check running containers:
bash
docker ps
- View MongoDB logs:
bash
docker logs <container_id>
π§ͺ Chaos Testing Scenarios
β Scenario 1: Connection Failures
def test_mongodb_connection_failure():
"""Test that our app handles MongoDB connection failures gracefully"""
with MongoDbContainer("mongo:6.0") as mongo:
# Simulate connection failure
mongo.get_docker_client().stop(mongo.get_container_id())
# Verify our app handles the failure
with pytest.raises(Exception):
mongo.get_connection_client()
β Scenario 2: Large Document Handling
def test_mongodb_large_document():
"""Test that our app handles large documents in MongoDB"""
with MongoDbContainer("mongo:6.0") as mongo:
client = mongo.get_connection_client()
db = client.test_db
collection = db.large_docs
# Create large document
large_doc = {"data": "x" * 10000, "id": 1}
# Insert and verify
result = collection.insert_one(large_doc)
assert result.inserted_id is not None
# Retrieve and verify
doc = collection.find_one({"id": 1})
assert len(doc["data"]) == 10000
π Monitoring & Reporting
β Generate HTML Report
pytest testcontainers/test_mongodb_container.py --html=reports/mongodb-test-report.html --self-contained-html
β View Container Logs
# Get container ID
docker ps | grep mongo
# View logs
docker logs <container_id>