Skip to content

Commit cf54518

Browse files
Merge pull request #6 from agile-learning-institute/improve-logging
Improved logging, Better container testing, Updates related to collec…
2 parents 9c5fb13 + c4be4ec commit cf54518

File tree

14 files changed

+166
-172
lines changed

14 files changed

+166
-172
lines changed

CONTRIBUTING.md

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ pipenv install --dev
6161
# Run Unit Tests and generate coverage report
6262
pipenv run test
6363

64+
# Run a backing mongo database
65+
pipenv run database
66+
6467
# Change the testing database name
6568
export MONGO_DB_NAME=test_database
6669
# NOTE: Must be test_database for db-compare to work
@@ -105,8 +108,10 @@ pipenv run stepci-large
105108

106109
# Combine DB actions with StepCI testing
107110
export INPUT_FOLDER=./tests/test_cases/large_sample
111+
pipenv run local
112+
# Then in a different window
108113
pipenv run db-drop-silent
109-
pipenv run stepci_large
114+
pipenv run stepci-large
110115
pipenv run db-compare
111116

112117
# Build the API Docker Image
@@ -160,31 +165,31 @@ If you need a new set of test data to validate features you are adding, feel fre
160165

161166
```bash
162167
# Get Configuration
163-
curl -X GET http://localhost:8582/api/config
168+
curl -X GET http://localhost:8081/api/config
164169

165170
# Health Check
166-
curl -X GET http://localhost:8582/health
171+
curl -X GET http://localhost:8081/health
167172

168173
# List Collections
169-
curl -X GET http://localhost:8582/api/collections/
174+
curl -X GET http://localhost:8081/api/collections/
170175

171176
# Get a Collection Config
172-
curl -X GET http://localhost:8582/api/collections/{collection_name}
177+
curl -X GET http://localhost:8081/api/collections/{collection_name}
173178

174179
# Process All Collections
175-
curl -X POST http://localhost:8582/api/collections/
180+
curl -X POST http://localhost:8081/api/collections/
176181

177182
# Process Specific Collection
178-
curl -X POST http://localhost:8582/api/collections/{collection_name}
183+
curl -X POST http://localhost:8081/api/collections/{collection_name}
179184

180185
# Render BSON Schema
181-
curl -X GET http://localhost:8582/api/render/bson_schema/{version_name}
186+
curl -X GET http://localhost:8081/api/render/bson_schema/{version_name}
182187

183188
# Render JSON Schema
184-
curl -X GET http://localhost:8582/api/render/json_schema/{version_name}
189+
curl -X GET http://localhost:8081/api/render/json_schema/{version_name}
185190

186191
# Render OpenAPI Specification
187-
curl -X GET http://localhost:8582/api/render/openapi/{version_name}
192+
curl -X GET http://localhost:8081/api/render/openapi/{version_name}
188193

189194
```
190195

Dockerfile

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,10 @@ RUN pip install -e .
3131
RUN pip install gunicorn
3232

3333
# Expose the port the app will run on
34-
EXPOSE 8582
34+
EXPOSE 8081
3535

3636
# Set Environment Variables
3737
ENV PYTHONPATH=/opt/stage0_mongodb_api/stage0_mongodb_api
3838

3939
# Command to run the application using Gunicorn
40-
CMD exec gunicorn --bind 0.0.0.0:8582 --timeout 120 --preload stage0_mongodb_api.server:app
41-
#CMD exec gunicorn --bind 0.0.0.0:8582 --workers 1 --timeout 120 --preload stage0_mongodb_api.server:app
40+
CMD exec gunicorn --bind 0.0.0.0:8081 --timeout 120 --preload stage0_mongodb_api.server:app

Pipfile

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ db-drop-silent = "python tests/db_util.py drop --passphrase DROP_DROWSSAP_YEK"
1616
db-compare = "python tests/db_util.py compare"
1717
db-harvest = "python tests/db_util.py harvest"
1818
build = "docker build --tag ghcr.io/agile-learning-institute/stage0_mongodb_api:latest ."
19-
container = "docker compose up --detach"
20-
down = "docker compose down"
19+
database = "docker compose --profile mongodb up --detach"
20+
container = "docker compose --profile all up --detach"
21+
down = "docker compose down stage0_mongodb_api mongodb"
2122

2223
[packages]
2324
python-dotenv = "*"

Pipfile.lock

Lines changed: 102 additions & 114 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

REFERENCE.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ The API is configured through environment variables.
7676

7777
| Variable | Description | Default |
7878
|----------|-------------|---------|
79-
| `MONGODB_API_PORT` | API Port number | `8582` |
79+
| `MONGODB_API_PORT` | API Port number | `8081` |
8080
| `MONGO_DB_NAME` | MongoDB database name | `stage0` |
8181
| `MONGO_CONNECTION_STRING` | MongoDB connection string | `mongodb://root:example@localhost:27017/?tls=false&directConnection=true` |
8282
| `VERSION_COLLECTION_NAME`| MongoDB Version Collection name | `CollectionVersions` |

docker-compose.yaml

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,38 @@
11
# docker-compose.yaml for stage0_mongodb_api testing
22

33
services:
4-
mongodb-server:
4+
mongodb:
55
image: mongo:7.0.5
6-
environment:
7-
MONGO_INITDB_ROOT_USERNAME: root
8-
MONGO_INITDB_ROOT_PASSWORD: example
96
ports:
10-
- "27017:27017"
7+
- 27017:27017
8+
extra_hosts:
9+
- "mongodb:127.0.0.1"
1110
healthcheck:
12-
test: ["CMD", "mongosh", "-u", "root", "-p", "example", "--authenticationDatabase", "admin", "--eval", "db.adminCommand('ping')"]
13-
interval: 2s
14-
timeout: 2s
15-
retries: 15
11+
test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet
12+
interval: 5s
13+
timeout: 30s
14+
start_period: 0s
15+
retries: 30
16+
command: ["--replSet", "rs0", "--bind_ip_all", "--port", "27017"]
17+
profiles:
18+
- mongodb
19+
- all
1620

1721
stage0_mongodb_api:
1822
image: ghcr.io/agile-learning-institute/stage0_mongodb_api:latest
1923
restart: no
2024
ports:
21-
- "8582:8582"
25+
- "8081:8081"
2226
volumes:
2327
- ./tests/test_cases/large_sample:/input
2428
environment:
25-
MONGO_CONNECTION_STRING: mongodb://root:example@mongodb-server:27017
29+
MONGO_CONNECTION_STRING: mongodb://mongodb:27017/?replicaSet=rs0
2630
MONGO_DB_NAME: test_database
27-
MONGODB_API_PORT: 8582
31+
MONGODB_API_PORT: 8081
2832
AUTO_PROCESS: True
2933
LOAD_TEST_DATA: True
3034
depends_on:
31-
mongodb-server:
35+
mongodb:
3236
condition: service_healthy
37+
profiles:
38+
- all

stage0_mongodb_api/server.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ def handle_exit(signum, frame):
3030
signal.signal(signal.SIGTERM, handle_exit)
3131
signal.signal(signal.SIGINT, handle_exit)
3232

33+
# Initialize Flask App
34+
app = Flask(__name__)
35+
app.json = MongoJSONEncoder(app)
36+
3337
# Auto-processing logic - runs when module is imported (including by Gunicorn)
3438
if config.AUTO_PROCESS:
3539
logger.info(f"============= Auto Processing is Enabled ===============")
@@ -48,17 +52,13 @@ def handle_exit(signum, frame):
4852

4953
# Process all collections
5054
processing_output = config_manager.process_all_collections()
51-
logger.info(f"Processing Output: {json.dumps(processing_output, indent=4)}")
55+
logger.info(f"Processing Output: {app.json.dumps(processing_output)}")
5256
logger.info(f"============= Auto Processing is Completed ===============")
5357

5458
if config.EXIT_AFTER_PROCESSING:
5559
logger.info(f"============= Exiting After Processing ===============")
5660
sys.exit(0)
5761

58-
# Initialize Flask App
59-
app = Flask(__name__)
60-
app.json = MongoJSONEncoder(app)
61-
6262
# Apply Prometheus monitoring middleware
6363
metrics = PrometheusMetrics(app, path='/api/health')
6464
metrics.info('app_info', 'Application info', version=config.BUILT_AT)

tests/db_util.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,20 @@ def _compare_collection_with_file(self, collection_name: str, json_file: Path) -
192192
# Convert ObjectIds to strings for comparison
193193
actual_data = json.loads(json_util.dumps(actual_data))
194194

195+
# Remove _id fields from both expected and actual data
196+
expected_data_no_id = []
197+
for doc in expected_data:
198+
doc_copy = {k: v for k, v in doc.items() if k != '_id'}
199+
expected_data_no_id.append(doc_copy)
200+
201+
actual_data_no_id = []
202+
for doc in actual_data:
203+
doc_copy = {k: v for k, v in doc.items() if k != '_id'}
204+
actual_data_no_id.append(doc_copy)
205+
195206
# Compare document counts
196-
expected_count = len(expected_data)
197-
actual_count = len(actual_data)
207+
expected_count = len(expected_data_no_id)
208+
actual_count = len(actual_data_no_id)
198209

199210
if expected_count != actual_count:
200211
return {
@@ -210,8 +221,8 @@ def _compare_collection_with_file(self, collection_name: str, json_file: Path) -
210221
matches = 0
211222
mismatches = []
212223

213-
for i, (expected, actual) in enumerate(zip(expected_data, actual_data)):
214-
if self._documents_match(expected, actual):
224+
for i, (expected, actual) in enumerate(zip(expected_data_no_id, actual_data_no_id)):
225+
if expected == actual:
215226
matches += 1
216227
else:
217228
mismatches.append({
@@ -249,22 +260,6 @@ def _compare_collection_with_file(self, collection_name: str, json_file: Path) -
249260
"message": f"Error comparing collection: {str(e)}"
250261
}
251262

252-
def _documents_match(self, expected: Dict, actual: Dict) -> bool:
253-
"""Compare two documents for equality.
254-
255-
Args:
256-
expected: Expected document
257-
actual: Actual document
258-
259-
Returns:
260-
True if documents match, False otherwise
261-
"""
262-
# Remove _id field for comparison (it's auto-generated)
263-
expected_copy = {k: v for k, v in expected.items() if k != '_id'}
264-
actual_copy = {k: v for k, v in actual.items() if k != '_id'}
265-
266-
return expected_copy == actual_copy
267-
268263
def harvest_database(self, output_path: Optional[str] = None) -> Dict[str, Any]:
269264
"""Harvest all database contents to JSON files.
270265

tests/stepci/large_sample.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name: mongodb_api_large_sample
22
version: "1.0"
33
env:
4-
host: localhost:8582
4+
host: localhost:8081
55

66
tests:
77
collections:

tests/stepci/observability.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name: mongodb_api_observability
22
version: "1.0"
33
env:
4-
host: localhost:8582
4+
host: localhost:8081
55

66
tests:
77
observable:

0 commit comments

Comments
 (0)