Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
18afa2e
Move test files for scripts to tests/scripts/
codesungrape Aug 11, 2025
10d2553
Refactor test_create_books.py to use `with` blocks for mocks
codesungrape Aug 11, 2025
1b15b3f
Remove runpy test and helper to fix mock leak
codesungrape Aug 11, 2025
2053060
Add TDD failing test for seed_users function
codesungrape Aug 12, 2025
b0b7fc0
Add scripts/test_data/sample_user_data.json + empty scripts/seed_user.py
codesungrape Aug 12, 2025
657441f
Fix context manager and typo in test
codesungrape Aug 12, 2025
d056d40
Merge branch 'Add-DB-seeding-script-for-JWT-protected-route-testing' …
codesungrape Aug 12, 2025
04f06e3
Add test to check skipping if exiting user functionality
codesungrape Aug 12, 2025
4460f2a
Add logic seed_users; TDD tests pass
codesungrape Aug 12, 2025
911289d
Refactor: move script execution to main(); fix pylint
codesungrape Aug 12, 2025
56a45bb
Add tests for main() happy path + failure modes; 100% converage
codesungrape Aug 12, 2025
5bc79e2
Run formatting
codesungrape Aug 12, 2025
9de860a
Fix to use abs path from the script location
codesungrape Aug 12, 2025
c9b2cbe
Update Makefile with seed-users command
codesungrape Aug 12, 2025
540d8b0
Update Makefile and README.md to reflect adding seed_users()
codesungrape Aug 12, 2025
70a45d2
Update tests/scripts/test_seed_users.py
codesungrape Aug 12, 2025
78b1d4c
Update tests/scripts/test_seed_users.py
codesungrape Aug 12, 2025
69e2edc
Update scripts/seed_users.py
codesungrape Aug 12, 2025
2163184
Update README.md
codesungrape Aug 12, 2025
b459c00
Update Makefile
codesungrape Aug 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ PIP = $(VENV_DIR)/bin/pip
.DEFAULT_GOAL := help

# Phony Targets
.PHONY: run clean test help lint db-seed db-clean db-setup
.PHONY: run clean test help lint db-seed db-clean db-setup seed-users

# ==============================================================================
# CORE COMMANDS - For everyday development
Expand All @@ -30,6 +30,7 @@ help: ## Show help
@echo " make db-setup Reset the database to a clean, seeded state. (Runs db-clean then db-seed)"
@echo " make db-seed Populate the database with initial data."
@echo " make db-clean Delete all book data from the database."
@echo " make seed-users Populate the database with initial user data."

install: $(PIP)

Expand Down Expand Up @@ -86,3 +87,8 @@ db-seed: install
db-clean: install
@echo "--> ⚠️ Deleting all books from the database..."
PATH=$(VENV_DIR)/bin:$$PATH PYTHONPATH=. $(PYTHON) -m scripts.delete_books


seed-users: install
@echo "--- Seeding the database with user data ---"
PATH=$(VENV_DIR)/bin:$$PATH PYTHONPATH=. $(PYTHON) -m scripts.seed_users
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,9 @@ To use the API, you first need to populate the database with some initial data.
| Command | Description |
|----------------|-----------------------------------------------------------------------------|
| `make db-setup`| **(Recommended)** Resets the database. Runs `db-clean` and then `db-seed`. |
| `make db-seed` | Populates the database with the contents of `scripts/books.json`. |
| `make db-seed` | Populates the database with the contents of `scripts/test_data/books.json`. |
| `make db-clean`| Deletes all documents from the 'books' collection. Useful for starting fresh. |
| `make seed-users`| *** THIS IS WIP right now: The user data is required for the JWT authentication system. *** Populates the database with initial user data for authentication from `scripts/test_data/sample_user_data.json`. |

To perform a full database reset, run:
```bash
Expand Down
85 changes: 85 additions & 0 deletions scripts/seed_users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""Seeding user_data script"""

import os
import json

import bcrypt

from app import create_app
from app.extensions import mongo


def seed_users(users_to_seed: list) -> str:
"""
Processes a list of user data, hashes their passwords,
and inserts them into the database. Skips existing users.

This function MUST be run within an active Flask application context.

Args:
users_to_seed: A list of dicts, each with 'email' and 'password'.

Returns:
A string summarizing the result.
"""
count = 0

for user_data in users_to_seed:
email = user_data["email"]

# Check if data already exists
if mongo.db.users.find_one({"email": email}):
print(f"Skipping existing user: {email}")
continue

# hash the password
hashed_password = bcrypt.hashpw(
user_data["password"].encode("utf-8"), bcrypt.gensalt()
)

# insert to new user
mongo.db.users.insert_one(
{"email": email, "password_hash": hashed_password.decode("utf-8")}
)
count += 1
print(f"Created user: {email}")

return f"Successfully seeded {count} users"


def main():
"""
Main execution function to run the seeding process.
handles app context, data loading, and calls the core seeding logic.
"""
# Create the DEVELOPMENT app when run from the command line
app = create_app()
with app.app_context():

# 1. Get the directory where THIS script (seed_users.py) lives.
script_dir = os.path.dirname(__file__)

# 2. Build the full, absolute path to the JSON file.
user_data_path = os.path.join(script_dir, "test_data/sample_user_data.json")

try:
# You can define your default users here or import from another file
with open(user_data_path, "r", encoding="utf-8") as user_file:
default_users = json.load(user_file)

print("--- Starting user seeding ---")

message = seed_users(default_users)
print(f"--- {message} ---")
print("--- Seeding complete ---")

except FileNotFoundError:
print(f"Error: Data file not found at '{user_data_path}'.")
except json.JSONDecodeError:
print(
f"Error: Could not decode JSON from '{user_data_path}'. Check for syntax errors."
)


if __name__ == "__main__":
main()
5 changes: 5 additions & 0 deletions scripts/test_data/sample_user_data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[
{"email": "test.admin@example.com", "password": "AdminPassword123"},
{"email": "test.user@example.com", "password": "UserPassword456"},
{"email": "miss.s.rai@outlook.com", "password": "DAYSend1991"}
]
Loading