From 032c58a668d846a336dac97aa9800e8bc1ddc47b Mon Sep 17 00:00:00 2001 From: Steven Adler Date: Mon, 19 Aug 2024 23:04:16 -0600 Subject: [PATCH] linting --- app/__init__.py | 32 ++-- app/models/encounter.py | 7 +- app/models/item.py | 6 +- app/models/rollable.py | 4 +- app/models/rolltable.py | 13 +- app/models/room.py | 5 +- app/models/user.py | 15 +- app/utils/auth_utils.py | 49 ++++--- app/utils/crud_helpers.py | 28 ++-- app/views/auth.py | 49 ++++--- app/views/encounter.py | 26 ++-- app/views/item.py | 26 ++-- app/views/roll.py | 36 +++-- app/views/rolltable.py | 46 +++--- app/views/room.py | 26 ++-- app/views/session.py | 6 +- app/views/user.py | 67 +++++---- config/settings.py | 11 +- tests/client_test.py | 26 ++-- tests/models/test_models.py | 73 ++++++++-- tests/views/test_auth.py | 78 ++++++---- tests/views/test_encounter.py | 67 ++++++--- tests/views/test_item.py | 62 +++++--- tests/views/test_roll.py | 118 +++++++++------ tests/views/test_rolltable.py | 143 +++++++++++------- tests/views/test_room.py | 50 ++++--- tests/views/test_session.py | 75 ++++++---- tests/views/test_user.py | 267 ++++++++++++++++++++-------------- tests/views/test_view_base.py | 22 +-- 29 files changed, 873 insertions(+), 560 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index c1e454f..435da15 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -27,41 +27,35 @@ def create_app(): socketio.init_app(flask_app) - connect(host=settings.MONGO_URI, uuidRepresentation='standard') + connect(host=settings.MONGO_URI, uuidRepresentation="standard") - flask_app.register_blueprint(session_bp, url_prefix='/session') + flask_app.register_blueprint(session_bp, url_prefix="/session") - flask_app.register_blueprint(auth_bp, url_prefix='/auth') - flask_app.register_blueprint(user_bp, url_prefix='/users') - flask_app.register_blueprint(rolltable_bp, url_prefix='/rolltables') - flask_app.register_blueprint(room_bp, url_prefix='/rooms') - flask_app.register_blueprint(encounter_bp, url_prefix='/encounters') - flask_app.register_blueprint(roll_bp, url_prefix='/rolls') - flask_app.register_blueprint(item_bp, url_prefix='/items') + flask_app.register_blueprint(auth_bp, url_prefix="/auth") + flask_app.register_blueprint(user_bp, url_prefix="/users") + flask_app.register_blueprint(rolltable_bp, url_prefix="/rolltables") + flask_app.register_blueprint(room_bp, url_prefix="/rooms") + flask_app.register_blueprint(encounter_bp, url_prefix="/encounters") + flask_app.register_blueprint(roll_bp, url_prefix="/rolls") + flask_app.register_blueprint(item_bp, url_prefix="/items") @flask_app.errorhandler(HTTPException) def handle_http_exception(e): logging.warning(f"HTTP error occurred: {e}") - response = { - "error": e.name, - "message": e.description - } + response = {"error": e.name, "message": e.description} return jsonify(response), e.code @flask_app.errorhandler(Exception) def handle_exception(e): logging.error(f"An error occurred: {e}") - response = { - "error": "Internal Server Error", - "message": str(e) - } + response = {"error": "Internal Server Error", "message": str(e)} return jsonify(response), 500 @flask_app.errorhandler(404) def handle_404_error(e): response = { "error": "Not Found", - "message": "The requested resource could not be found" + "message": "The requested resource could not be found", } return jsonify(response), 404 @@ -69,7 +63,7 @@ def handle_404_error(e): def handle_400_error(e): response = { "error": "Bad Request", - "message": "The request could not be understood or was missing required parameters" + "message": "The request could not be understood or was missing required parameters", } return jsonify(response), 400 diff --git a/app/models/encounter.py b/app/models/encounter.py index 889bb15..e182bf1 100644 --- a/app/models/encounter.py +++ b/app/models/encounter.py @@ -1,4 +1,5 @@ -from mongoengine import StringField, IntField +from mongoengine import IntField, StringField + from app.models.rollable import Rollable @@ -7,6 +8,4 @@ class Encounter(Rollable): min_players = IntField(required=True) max_players = IntField(required=True) - meta = { - 'collection': 'rollable_encounters' - } + meta = {"collection": "rollable_encounters"} diff --git a/app/models/item.py b/app/models/item.py index 11d16e5..07372e3 100644 --- a/app/models/item.py +++ b/app/models/item.py @@ -1,4 +1,4 @@ -from mongoengine import StringField, BooleanField +from mongoengine import BooleanField, StringField from app.models.rollable import Rollable @@ -10,6 +10,4 @@ class Item(Rollable): has_been_rolled = BooleanField(default=False, required=True) available = BooleanField(default=True) # for current round of rolling image_file_location = StringField() - meta = { - 'collection': 'rollable_items' - } + meta = {"collection": "rollable_items"} diff --git a/app/models/rollable.py b/app/models/rollable.py index a55f54b..418af9d 100644 --- a/app/models/rollable.py +++ b/app/models/rollable.py @@ -1,8 +1,8 @@ -from mongoengine import Document, StringField, IntField +from mongoengine import Document, IntField, StringField class Rollable(Document): - meta = {'abstract': True} + meta = {"abstract": True} name = StringField(required=True) description = StringField(require=True) diff --git a/app/models/rolltable.py b/app/models/rolltable.py index 3d545de..1800f25 100644 --- a/app/models/rolltable.py +++ b/app/models/rolltable.py @@ -7,12 +7,15 @@ class RollTable(Rollable): - tier = StringField(required=True, choices=["Platinum", "Gold", "Silver", "Bronze"]) - table_type = StringField(required=True, choices=["Magic Items", "Weapons", "Encounters", "Rooms"]) + tier = StringField( + required=True, choices=["Platinum", "Gold", "Silver", "Bronze"] + ) + table_type = StringField( + required=True, + choices=["Magic Items", "Weapons", "Encounters", "Rooms"], + ) items = ListField(ReferenceField(Item)) encounters = ListField(ReferenceField(Encounter)) rooms = ListField(ReferenceField(Room)) - meta = { - 'collection': 'rolltables' - } + meta = {"collection": "rolltables"} diff --git a/app/models/room.py b/app/models/room.py index f5fce11..c9ee1b7 100644 --- a/app/models/room.py +++ b/app/models/room.py @@ -1,10 +1,9 @@ from mongoengine import StringField + from app.models.rollable import Rollable class Room(Rollable): type = StringField(default="Room") reward_tier = StringField(choices=["Bronze", "Silver", "Gold", "Platinum"]) - meta = { - 'collection': 'rollable_rooms' - } + meta = {"collection": "rollable_rooms"} diff --git a/app/models/user.py b/app/models/user.py index aef3f6e..3c11506 100644 --- a/app/models/user.py +++ b/app/models/user.py @@ -1,5 +1,12 @@ -from mongoengine import StringField, BooleanField, ListField, EmailField, Document, ReferenceField -from werkzeug.security import generate_password_hash, check_password_hash +from mongoengine import ( + BooleanField, + Document, + EmailField, + ListField, + ReferenceField, + StringField, +) +from werkzeug.security import check_password_hash, generate_password_hash from app.models.item import Item @@ -12,9 +19,7 @@ class User(Document): is_active = BooleanField(default=False) is_dm = BooleanField(default=False, required=True) items = ListField(ReferenceField(Item)) - meta = { - 'collection': 'users' - } + meta = {"collection": "users"} def set_password(self, password): self.password_hash = generate_password_hash(password) diff --git a/app/utils/auth_utils.py b/app/utils/auth_utils.py index 299e92f..2c7de97 100644 --- a/app/utils/auth_utils.py +++ b/app/utils/auth_utils.py @@ -4,7 +4,7 @@ import jwt from bson import ObjectId -from flask import current_app, request, abort +from flask import abort, current_app, request from app.models.user import User @@ -16,15 +16,13 @@ def encode_auth_token(user_id, is_dm): try: payload = { - 'exp': datetime.now(timezone.utc) + timedelta(days=1), - 'iat': datetime.now(timezone.utc), - 'sub': str(user_id), - 'is_dm': is_dm + "exp": datetime.now(timezone.utc) + timedelta(days=1), + "iat": datetime.now(timezone.utc), + "sub": str(user_id), + "is_dm": is_dm, } return jwt.encode( - payload, - current_app.config.get('SECRET_KEY'), - algorithm='HS256' + payload, current_app.config.get("SECRET_KEY"), algorithm="HS256" ) except Exception: logger.exception("Failed to encode auth token") @@ -33,51 +31,58 @@ def encode_auth_token(user_id, is_dm): def decode_auth_token(auth_token): try: - payload = jwt.decode(auth_token, current_app.config.get('SECRET_KEY'), algorithms=['HS256']) + payload = jwt.decode( + auth_token, + current_app.config.get("SECRET_KEY"), + algorithms=["HS256"], + ) return payload except jwt.ExpiredSignatureError: logger.warning("Token expired") - abort(403, description='Signature expired. Please log in again.') + abort(403, description="Signature expired. Please log in again.") except jwt.InvalidTokenError: logger.warning("Invalid token") - abort(403, description='Invalid token. Please log in again.') + abort(403, description="Invalid token. Please log in again.") def token_required(dm_required=False): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): - auth_header = request.headers.get('Authorization', None) + auth_header = request.headers.get("Authorization", None) if auth_header is None: logger.warning("Authorization header is missing") - abort(403, description='Authorization header is missing!') + abort(403, description="Authorization header is missing!") try: auth_type, token = auth_header.split() - if auth_type.lower() != 'bearer': + if auth_type.lower() != "bearer": logger.warning("Invalid token type: %s", auth_type) - abort(403, description='Invalid token type. Expected Bearer token') + abort( + 403, + description="Invalid token type. Expected Bearer token", + ) except ValueError: logger.warning("Invalid Authorization header format") - abort(403, description='Invalid Authorization header format') + abort(403, description="Invalid Authorization header format") if not token: logger.warning("Token is missing") - abort(403, description='Token is missing!') + abort(403, description="Token is missing!") try: payload = decode_auth_token(token) - user_id = payload['sub'] + user_id = payload["sub"] current_user = User.objects(id=ObjectId(user_id)).first() - kwargs['current_user'] = current_user + kwargs["current_user"] = current_user if current_user is None: logger.warning("User not found") - abort(403, description='User not found!') + abort(403, description="User not found!") - if dm_required and not payload.get('is_dm', False): + if dm_required and not payload.get("is_dm", False): logger.warning("DM required but not provided in token") - abort(403, description='DM required!') + abort(403, description="DM required!") except Exception as e: logger.exception("Token validation error") diff --git a/app/utils/crud_helpers.py b/app/utils/crud_helpers.py index 7f9f10a..c1af07c 100644 --- a/app/utils/crud_helpers.py +++ b/app/utils/crud_helpers.py @@ -6,10 +6,13 @@ def get_document(document_class, doc_id): try: document = document_class.objects(id=ObjectId(doc_id)).first() if not document: - return jsonify({'message': f'{document_class.__name__} not found!'}), 404 + return ( + jsonify({"message": f"{document_class.__name__} not found!"}), + 404, + ) return jsonify(document.to_mongo().to_dict()), 200 except Exception as e: - return jsonify({'message': str(e)}), 400 + return jsonify({"message": str(e)}), 400 def create_document(document_class, data): @@ -18,19 +21,19 @@ def create_document(document_class, data): document.save() return jsonify(document.to_mongo().to_dict()), 201 except Exception as e: - return jsonify({'message': str(e)}), 400 + return jsonify({"message": str(e)}), 400 def update_document(document, data): try: - for key in ['items', 'rooms', 'encounters']: + for key in ["items", "rooms", "encounters"]: if key in data.keys(): data.pop(key) document.update(**data) document.reload() # Reload to get updated document return jsonify(document.to_mongo().to_dict()), 200 except Exception as e: - return jsonify({'message': str(e)}), 400 + return jsonify({"message": str(e)}), 400 def modify_document(document, data): @@ -39,15 +42,22 @@ def modify_document(document, data): document.reload() return jsonify(document.to_mongo().to_dict()), 200 except Exception as e: - return jsonify({'message': str(e)}), 400 + return jsonify({"message": str(e)}), 400 def delete_document(document): try: document.delete() - return jsonify({'message': f'{document.__class__.__name__} deleted successfully!'}), 200 + return ( + jsonify( + { + "message": f"{document.__class__.__name__} deleted successfully!" + } + ), + 200, + ) except Exception as e: - return jsonify({'message': str(e)}), 400 + return jsonify({"message": str(e)}), 400 def get_all_documents(document_class): @@ -55,4 +65,4 @@ def get_all_documents(document_class): documents = document_class.objects() return jsonify([doc.to_mongo().to_dict() for doc in documents]), 200 except Exception as e: - return jsonify({'message': str(e)}), 400 + return jsonify({"message": str(e)}), 400 diff --git a/app/views/auth.py b/app/views/auth.py index e555ff6..256623b 100644 --- a/app/views/auth.py +++ b/app/views/auth.py @@ -1,48 +1,53 @@ -from flask import Blueprint, request, jsonify +import base64 + +from flask import Blueprint, jsonify, request + from app.models.user import User from app.utils.auth_utils import encode_auth_token -import base64 -auth_bp = Blueprint('auth_bp', __name__) +auth_bp = Blueprint("auth_bp", __name__) -@auth_bp.route('/register', methods=['POST']) +@auth_bp.route("/register", methods=["POST"]) def register(): data = request.get_json() - if User.objects(username=data['username']).first(): - return jsonify({'message': 'Username already exists'}), 400 - if User.objects(email=data['email']).first(): - return jsonify({'message': 'Email already exists'}), 400 + if User.objects(username=data["username"]).first(): + return jsonify({"message": "Username already exists"}), 400 + if User.objects(email=data["email"]).first(): + return jsonify({"message": "Email already exists"}), 400 user = User( - username=data['username'], - email=data['email'], - is_dm=data['is_dm'] + username=data["username"], email=data["email"], is_dm=data["is_dm"] ) - user.set_password(data['password']) + user.set_password(data["password"]) user.save() - return jsonify({'message': 'User registered successfully'}), 201 + return jsonify({"message": "User registered successfully"}), 201 -@auth_bp.route('/login', methods=['POST']) +@auth_bp.route("/login", methods=["POST"]) def login(): - auth_header = request.headers.get('Authorization') + auth_header = request.headers.get("Authorization") - if not auth_header or not auth_header.startswith('Basic '): - return jsonify({'message': 'Authorization header is missing or invalid'}), 401 + if not auth_header or not auth_header.startswith("Basic "): + return ( + jsonify({"message": "Authorization header is missing or invalid"}), + 401, + ) # Decode the Basic Auth header try: - auth_decoded = base64.b64decode(auth_header.split(' ')[1]).decode('utf-8') - username, password = auth_decoded.split(':') + auth_decoded = base64.b64decode(auth_header.split(" ")[1]).decode( + "utf-8" + ) + username, password = auth_decoded.split(":") except (TypeError, ValueError, IndexError): - return jsonify({'message': 'Invalid Authorization header format'}), 401 + return jsonify({"message": "Invalid Authorization header format"}), 401 # Authenticate the user user = User.objects(username=username).first() if user and user.check_password(password): auth_token = encode_auth_token(user.id, user.is_dm) if auth_token: - return jsonify({'token': auth_token}), 200 + return jsonify({"token": auth_token}), 200 - return jsonify({'message': 'Invalid credentials'}), 401 + return jsonify({"message": "Invalid credentials"}), 401 diff --git a/app/views/encounter.py b/app/views/encounter.py index 7ad8640..6e7fb7b 100644 --- a/app/views/encounter.py +++ b/app/views/encounter.py @@ -1,14 +1,20 @@ -from flask import Blueprint, request, jsonify +from flask import Blueprint, jsonify, request from app.models.encounter import Encounter from app.utils.auth_utils import token_required -from app.utils.crud_helpers import get_document, create_document, update_document, delete_document, get_all_documents +from app.utils.crud_helpers import ( + create_document, + delete_document, + get_all_documents, + get_document, + update_document, +) -encounter_bp = Blueprint('encounter_bp', __name__) +encounter_bp = Blueprint("encounter_bp", __name__) -@encounter_bp.route('/', defaults={'encounter_id': None}) -@encounter_bp.route('/', methods=['GET']) +@encounter_bp.route("/", defaults={"encounter_id": None}) +@encounter_bp.route("/", methods=["GET"]) @token_required(dm_required=True) def get_encounters(encounter_id, **kwargs): if encounter_id: @@ -16,27 +22,27 @@ def get_encounters(encounter_id, **kwargs): return get_all_documents(Encounter) -@encounter_bp.route('/', methods=['POST']) +@encounter_bp.route("/", methods=["POST"]) @token_required(dm_required=True) def create_encounter(**kwargs): data = request.get_json() return create_document(Encounter, data) -@encounter_bp.route('/', methods=['PATCH']) +@encounter_bp.route("/", methods=["PATCH"]) @token_required(dm_required=True) def update_encounter(encounter_id, **kwargs): data = request.get_json() encounter = Encounter.objects(id=encounter_id).first() if not encounter: - return jsonify({'message': 'Encounter not found!'}), 404 + return jsonify({"message": "Encounter not found!"}), 404 return update_document(encounter, data) -@encounter_bp.route('/', methods=['DELETE']) +@encounter_bp.route("/", methods=["DELETE"]) @token_required(dm_required=True) def delete_encounter(encounter_id, **kwargs): encounter = Encounter.objects(id=encounter_id).first() if not encounter: - return jsonify({'message': 'Encounter not found!'}), 404 + return jsonify({"message": "Encounter not found!"}), 404 return delete_document(encounter) diff --git a/app/views/item.py b/app/views/item.py index e9f7cda..ccd51b0 100644 --- a/app/views/item.py +++ b/app/views/item.py @@ -1,14 +1,20 @@ -from flask import Blueprint, request, jsonify +from flask import Blueprint, jsonify, request from app.models.item import Item from app.utils.auth_utils import token_required -from app.utils.crud_helpers import get_document, create_document, update_document, delete_document, get_all_documents +from app.utils.crud_helpers import ( + create_document, + delete_document, + get_all_documents, + get_document, + update_document, +) -item_bp = Blueprint('item_bp', __name__) +item_bp = Blueprint("item_bp", __name__) -@item_bp.route('/', defaults={'item_id': None}) -@item_bp.route('/', methods=['GET']) +@item_bp.route("/", defaults={"item_id": None}) +@item_bp.route("/", methods=["GET"]) @token_required(dm_required=True) def get_items(item_id, **kwargs): if item_id: @@ -16,27 +22,27 @@ def get_items(item_id, **kwargs): return get_all_documents(Item) -@item_bp.route('/', methods=['POST']) +@item_bp.route("/", methods=["POST"]) @token_required(dm_required=True) def create_item(**kwargs): data = request.get_json() return create_document(Item, data) -@item_bp.route('/', methods=['PATCH']) +@item_bp.route("/", methods=["PATCH"]) @token_required(dm_required=True) def update_item(item_id, **kwargs): data = request.get_json() item = Item.objects(id=item_id).first() if not item: - return jsonify({'message': 'Item not found!'}), 404 + return jsonify({"message": "Item not found!"}), 404 return update_document(item, data) -@item_bp.route('/', methods=['DELETE']) +@item_bp.route("/", methods=["DELETE"]) @token_required(dm_required=True) def delete_item(item_id, **kwargs): item = Item.objects(id=item_id).first() if not item: - return jsonify({'message': 'Item not found!'}), 404 + return jsonify({"message": "Item not found!"}), 404 return delete_document(item) diff --git a/app/views/roll.py b/app/views/roll.py index 13c158b..71355c0 100644 --- a/app/views/roll.py +++ b/app/views/roll.py @@ -2,17 +2,17 @@ from random import sample from bson import ObjectId -from flask import Blueprint, request, jsonify +from flask import Blueprint, jsonify, request from app.models.encounter import Encounter from app.models.item import Item from app.models.rolltable import RollTable from app.models.room import Room -roll_bp = Blueprint('roll_bp', __name__) +roll_bp = Blueprint("roll_bp", __name__) -@roll_bp.route('/', methods=['POST']) +@roll_bp.route("/", methods=["POST"]) def perform_roll(**kwargs): """ Roll from a specified table and return unique results. @@ -24,9 +24,9 @@ def perform_roll(**kwargs): } """ data = request.get_json() - rolltable_id = data.get('rolltable_id') - num_results = data.get('num_results') - constraints = data.get('constraints', {}) + rolltable_id = data.get("rolltable_id") + num_results = data.get("num_results") + constraints = data.get("constraints", {}) max_retries = 3 retry_delay = 0.1 # 100 milliseconds @@ -34,7 +34,7 @@ def perform_roll(**kwargs): try: rolltable = RollTable.objects(id=ObjectId(rolltable_id)).first() if not rolltable: - return jsonify({'message': 'RollTable not found!'}), 404 + return jsonify({"message": "RollTable not found!"}), 404 if rolltable.items: entry_model = Item @@ -46,16 +46,16 @@ def perform_roll(**kwargs): entry_model = Room entry_ids = rolltable.rooms else: - return '', 204 + return "", 204 filter_criteria = {k: v for k, v in constraints.items()} - filter_criteria['_id'] = {'$in': [entry.id for entry in entry_ids]} + filter_criteria["_id"] = {"$in": [entry.id for entry in entry_ids]} if entry_model == Item: - filter_criteria['available'] = True + filter_criteria["available"] = True filtered_entries = list(entry_model.objects(__raw__=filter_criteria)) if not filtered_entries: - return '', 204 + return "", 204 min(num_results, len(filtered_entries)) @@ -70,7 +70,9 @@ def perform_roll(**kwargs): for entry in selected_entries: if entry_model == Item: - updated_entry = Item.objects(id=entry.id, available=True).modify(set__available=False) + updated_entry = Item.objects( + id=entry.id, available=True + ).modify(set__available=False) if updated_entry: selected_results.append(updated_entry) filtered_entries.remove(entry) @@ -84,10 +86,12 @@ def perform_roll(**kwargs): # If we can't get enough available items, return what we have if selected_results: - results = [result.to_mongo().to_dict() for result in selected_results] - return jsonify({'results': results}), 200 + results = [ + result.to_mongo().to_dict() for result in selected_results + ] + return jsonify({"results": results}), 200 else: - return '', 204 # No items were successfully acquired + return "", 204 # No items were successfully acquired except Exception as e: - return jsonify({'message': str(e)}), 500 + return jsonify({"message": str(e)}), 500 diff --git a/app/views/rolltable.py b/app/views/rolltable.py index bf62570..a38b396 100644 --- a/app/views/rolltable.py +++ b/app/views/rolltable.py @@ -1,16 +1,22 @@ from bson import ObjectId -from flask import Blueprint, request, jsonify +from flask import Blueprint, jsonify, request from app.models.rolltable import RollTable from app.utils.auth_utils import token_required -from app.utils.crud_helpers import get_document, create_document, update_document, delete_document, get_all_documents, \ - modify_document +from app.utils.crud_helpers import ( + create_document, + delete_document, + get_all_documents, + get_document, + modify_document, + update_document, +) -rolltable_bp = Blueprint('rolltable_bp', __name__) +rolltable_bp = Blueprint("rolltable_bp", __name__) -@rolltable_bp.route('/', defaults={'rolltable_id': None}) -@rolltable_bp.route('/', methods=['GET']) +@rolltable_bp.route("/", defaults={"rolltable_id": None}) +@rolltable_bp.route("/", methods=["GET"]) @token_required(dm_required=True) def get_rolltables(rolltable_id, **kwargs): if rolltable_id: @@ -18,48 +24,48 @@ def get_rolltables(rolltable_id, **kwargs): return get_all_documents(RollTable) -@rolltable_bp.route('/', methods=['POST']) +@rolltable_bp.route("/", methods=["POST"]) @token_required(dm_required=True) def create_rolltable(**kwargs): data = request.get_json() return create_document(RollTable, data) -@rolltable_bp.route('/', methods=['PATCH']) +@rolltable_bp.route("/", methods=["PATCH"]) @token_required(dm_required=True) def update_rolltable(rolltable_id, **kwargs): data = request.get_json() rolltable = RollTable.objects(id=rolltable_id).first() if not rolltable: - return jsonify({'message': 'RollTable not found!'}), 404 + return jsonify({"message": "RollTable not found!"}), 404 return update_document(rolltable, data) -@rolltable_bp.route('//add', methods=['POST']) +@rolltable_bp.route("//add", methods=["POST"]) @token_required(dm_required=True) def add_to_rolltable(rolltable_id, **kwargs): data = request.get_json() rolltable = RollTable.objects(id=ObjectId(rolltable_id)).first() if not rolltable: - return jsonify({'message': 'RollTable not found!'}), 404 + return jsonify({"message": "RollTable not found!"}), 404 update_data = {} - if 'items' in data.keys(): - update_data['add_to_set__items'] = data['items'] - elif 'encounters' in data.keys(): - update_data['add_to_set__encounters'] = data['encounters'] - elif 'rooms' in data.keys(): - update_data['add_to_set__rooms'] = data['rooms'] + if "items" in data.keys(): + update_data["add_to_set__items"] = data["items"] + elif "encounters" in data.keys(): + update_data["add_to_set__encounters"] = data["encounters"] + elif "rooms" in data.keys(): + update_data["add_to_set__rooms"] = data["rooms"] else: - return jsonify({'message': 'No valid fields to update!'}), 400 + return jsonify({"message": "No valid fields to update!"}), 400 return modify_document(rolltable, update_data) -@rolltable_bp.route('/', methods=['DELETE']) +@rolltable_bp.route("/", methods=["DELETE"]) @token_required(dm_required=True) def delete_rolltable(rolltable_id, **kwargs): rolltable = RollTable.objects(id=rolltable_id).first() if not rolltable: - return jsonify({'message': 'RollTable not found!'}), 404 + return jsonify({"message": "RollTable not found!"}), 404 return delete_document(rolltable) diff --git a/app/views/room.py b/app/views/room.py index 26ab432..e8a8469 100644 --- a/app/views/room.py +++ b/app/views/room.py @@ -1,14 +1,20 @@ -from flask import Blueprint, request, jsonify +from flask import Blueprint, jsonify, request from app.models.room import Room from app.utils.auth_utils import token_required -from app.utils.crud_helpers import get_document, create_document, update_document, delete_document, get_all_documents +from app.utils.crud_helpers import ( + create_document, + delete_document, + get_all_documents, + get_document, + update_document, +) -room_bp = Blueprint('room_bp', __name__) +room_bp = Blueprint("room_bp", __name__) -@room_bp.route('/', defaults={'room_id': None}) -@room_bp.route('/', methods=['GET']) +@room_bp.route("/", defaults={"room_id": None}) +@room_bp.route("/", methods=["GET"]) @token_required(dm_required=True) def get_rooms(room_id, **kwargs): if room_id: @@ -16,27 +22,27 @@ def get_rooms(room_id, **kwargs): return get_all_documents(Room) -@room_bp.route('/', methods=['POST']) +@room_bp.route("/", methods=["POST"]) @token_required(dm_required=True) def create_room(**kwargs): data = request.get_json() return create_document(Room, data) -@room_bp.route('/', methods=['PATCH']) +@room_bp.route("/", methods=["PATCH"]) @token_required(dm_required=True) def update_room(room_id, **kwargs): data = request.get_json() room = Room.objects(id=room_id).first() if not room: - return jsonify({'message': 'Room not found!'}), 404 + return jsonify({"message": "Room not found!"}), 404 return update_document(room, data) -@room_bp.route('/', methods=['DELETE']) +@room_bp.route("/", methods=["DELETE"]) @token_required(dm_required=True) def delete_room(room_id, **kwargs): room = Room.objects(id=room_id).first() if not room: - return jsonify({'message': 'Room not found!'}), 404 + return jsonify({"message": "Room not found!"}), 404 return delete_document(room) diff --git a/app/views/session.py b/app/views/session.py index 5a57f9b..2aaa068 100644 --- a/app/views/session.py +++ b/app/views/session.py @@ -4,10 +4,10 @@ from app.models.user import User from app.utils.auth_utils import token_required -session_bp = Blueprint('session_bp', __name__) +session_bp = Blueprint("session_bp", __name__) -@session_bp.route('/clear', methods=['POST']) +@session_bp.route("/clear", methods=["POST"]) @token_required(dm_required=True) def clear_session(**kwargs): for user in User.objects().all(): @@ -17,4 +17,4 @@ def clear_session(**kwargs): item.available = True item.claimed = False item.save() - return '', 204 + return "", 204 diff --git a/app/views/user.py b/app/views/user.py index 4bce96a..b6f02fb 100644 --- a/app/views/user.py +++ b/app/views/user.py @@ -5,44 +5,46 @@ from app.utils.auth_utils import token_required from app.utils.crud_helpers import modify_document -user_bp = Blueprint('user_bp', __name__) +user_bp = Blueprint("user_bp", __name__) -@user_bp.route('/', methods=['GET']) +@user_bp.route("/", methods=["GET"]) @token_required(dm_required=True) def get_users(**kwargs): users = User.objects().all() users_list = [] for user in users: - users_list.append({ - 'id': str(user.id), - 'username': user.username, - 'email': user.email, - 'is_active': user.is_active, - 'is_dm': user.is_dm - }) + users_list.append( + { + "id": str(user.id), + "username": user.username, + "email": user.email, + "is_active": user.is_active, + "is_dm": user.is_dm, + } + ) return jsonify(users_list), 200 -@user_bp.route('//add', methods=['POST']) +@user_bp.route("//add", methods=["POST"]) @token_required(dm_required=True) def add_to_rolltable(user_id, **kwargs): data = request.get_json() user = User.objects(id=ObjectId(user_id)).first() if not user: - return jsonify({'message': 'User not found!'}), 404 + return jsonify({"message": "User not found!"}), 404 update_data = {} - if 'items' in data.keys(): - update_data['add_to_set__items'] = data['items'] + if "items" in data.keys(): + update_data["add_to_set__items"] = data["items"] else: - return jsonify({'message': 'No valid fields to update!'}), 400 + return jsonify({"message": "No valid fields to update!"}), 400 return modify_document(user, update_data) -@user_bp.route('/items', methods=['GET']) +@user_bp.route("/items", methods=["GET"]) @token_required() def get_items(*args, **kwargs): """ @@ -52,43 +54,46 @@ def get_items(*args, **kwargs): - If neither is provided, return the current user's items. """ try: - user_id = request.args.get('user_id') - all_users = request.args.get('all', '').lower() == 'true' + user_id = request.args.get("user_id") + all_users = request.args.get("all", "").lower() == "true" def format_item(item): return { - 'id': str(item.id), - 'name': item.name, - 'description': item.description, - 'image': item.image_file_location, - 'unique': item.unique + "id": str(item.id), + "name": item.name, + "description": item.description, + "image": item.image_file_location, + "unique": item.unique, } def format_user(user): return { - 'user_id': str(user.id), - 'username': user.username, - 'email': user.email, - 'items': [format_item(item) for item in user.items] + "user_id": str(user.id), + "username": user.username, + "email": user.email, + "items": [format_item(item) for item in user.items], } if all_users: exclude_user_id = ObjectId(user_id) if user_id else None users = User.objects() users_data = [ - format_user(user) for user in users + format_user(user) + for user in users if not exclude_user_id or user.id != exclude_user_id ] - return jsonify({'users': users_data}), 200 + return jsonify({"users": users_data}), 200 else: - target_user_id = ObjectId(user_id) if user_id else kwargs['current_user'].id + target_user_id = ( + ObjectId(user_id) if user_id else kwargs["current_user"].id + ) user = User.objects(id=target_user_id).first() if not user: - return jsonify({'message': 'User not found!'}), 404 + return jsonify({"message": "User not found!"}), 404 return jsonify(format_user(user)), 200 except Exception as e: - return jsonify({'message': str(e)}), 500 + return jsonify({"message": str(e)}), 500 diff --git a/config/settings.py b/config/settings.py index e6f8a23..fc1c87c 100644 --- a/config/settings.py +++ b/config/settings.py @@ -1,13 +1,16 @@ -from dotenv import load_dotenv import os +from dotenv import load_dotenv + load_dotenv() class Config: - MONGO_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017/my_dnd_backend') - FLASK_ENV = os.getenv('FLASK_ENV', 'production') - SECRET_KEY = os.getenv('SECRET_KET', 'shhh-top-secret') + MONGO_URI = os.getenv( + "MONGODB_URI", "mongodb://localhost:27017/my_dnd_backend" + ) + FLASK_ENV = os.getenv("FLASK_ENV", "production") + SECRET_KEY = os.getenv("SECRET_KET", "shhh-top-secret") settings = Config() diff --git a/tests/client_test.py b/tests/client_test.py index 99e0f86..b079493 100644 --- a/tests/client_test.py +++ b/tests/client_test.py @@ -5,36 +5,42 @@ @sio.event def connect(): - print('Connection established') - sio.emit('send_message', {'recipient': 'user2', 'message': 'Hello from user1!'}) + print("Connection established") + sio.emit( + "send_message", {"recipient": "user2", "message": "Hello from user1!"} + ) @sio.event def disconnect(): - print('Disconnected from server') + print("Disconnected from server") -@sio.on('user_connected') +@sio.on("user_connected") def on_user_connected(data): print(f"User connected: {data['username']}") -@sio.on('user_disconnected') +@sio.on("user_disconnected") def on_user_disconnected(data): print(f"User disconnected: {data['username']}") -@sio.on('update_user_list') +@sio.on("update_user_list") def on_update_user_list(data): print(f"Connected users: {', '.join(data)}") -@sio.on('receive_message') +@sio.on("receive_message") def on_receive_message(data): print(f"Received message from {data['sender']}: {data['message']}") -if __name__ == '__main__': - username = 'user2' # Change this for different clients - sio.connect('http://localhost:5000', transports='websocket', headers={'username': username}) +if __name__ == "__main__": + username = "user2" # Change this for different clients + sio.connect( + "http://localhost:5000", + transports="websocket", + headers={"username": username}, + ) sio.wait() diff --git a/tests/models/test_models.py b/tests/models/test_models.py index 7b5d5a3..38381aa 100644 --- a/tests/models/test_models.py +++ b/tests/models/test_models.py @@ -20,7 +20,7 @@ def setUpClass(cls): @classmethod def tearDownClass(cls): # Disconnect from the test database - disconnect(alias='default') + disconnect(alias="default") def setUp(self): # Clear the database before each test @@ -31,15 +31,26 @@ def setUp(self): User.drop_collection() def test_encounter_creation(self): - encounter = Encounter(name="Test Encounter", description="An encounter", min_players=1, max_players=4) + encounter = Encounter( + name="Test Encounter", + description="An encounter", + min_players=1, + max_players=4, + ) encounter.save() self.assertEqual(encounter.type, "Encounter") self.assertEqual(encounter.min_players, 1) self.assertEqual(encounter.max_players, 4) def test_item_creation(self): - item = Item(name="Test Item", description="An item", unique=True, claimed=False, has_been_rolled=False, - available=True) + item = Item( + name="Test Item", + description="An item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) item.save() self.assertEqual(item.type, "Item") self.assertTrue(item.unique) @@ -48,21 +59,33 @@ def test_item_creation(self): self.assertTrue(item.available) def test_rolltable_creation(self): - rolltable = RollTable(name="Test RollTable", description="A rolltable", weight=5, tier="Gold", - table_type="Magic Items") + rolltable = RollTable( + name="Test RollTable", + description="A rolltable", + weight=5, + tier="Gold", + table_type="Magic Items", + ) rolltable.save() self.assertEqual(rolltable.tier, "Gold") self.assertEqual(rolltable.table_type, "Magic Items") def test_room_creation(self): - room = Room(name="Test Room", description="A room", reward_tier="Silver") + room = Room( + name="Test Room", description="A room", reward_tier="Silver" + ) room.save() self.assertEqual(room.type, "Room") self.assertEqual(room.reward_tier, "Silver") def test_user_creation(self): - user = User(username="testuser", email="testuser@example.com", password_hash="password_hash", is_active=True, - is_dm=True) + user = User( + username="testuser", + email="testuser@example.com", + password_hash="password_hash", + is_active=True, + is_dm=True, + ) user.set_password("password") user.save() self.assertEqual(user.username, "testuser") @@ -72,12 +95,30 @@ def test_user_creation(self): self.assertTrue(user.check_password("password")) def test_rolltable_with_items(self): - item1 = Item(name="Item1", description="First item", unique=True, claimed=False, has_been_rolled=False, - available=True).save() - item2 = Item(name="Item2", description="Second item", unique=True, claimed=False, has_been_rolled=False, - available=True).save() - rolltable = RollTable(name="Item RollTable", description="Table of items", weight=1, tier="Bronze", - table_type="Magic Items", items=[item1, item2]) + item1 = Item( + name="Item1", + description="First item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ).save() + item2 = Item( + name="Item2", + description="Second item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ).save() + rolltable = RollTable( + name="Item RollTable", + description="Table of items", + weight=1, + tier="Bronze", + table_type="Magic Items", + items=[item1, item2], + ) rolltable.save() retrieved_rolltable = RollTable.objects(id=rolltable.id).first() self.assertEqual(len(retrieved_rolltable.items), 2) @@ -85,5 +126,5 @@ def test_rolltable_with_items(self): self.assertIn(item2, retrieved_rolltable.items) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_auth.py b/tests/views/test_auth.py index edcffc8..48a04ee 100644 --- a/tests/views/test_auth.py +++ b/tests/views/test_auth.py @@ -1,73 +1,87 @@ +import base64 import unittest + +from mongoengine import disconnect + from app import create_app from app.models.user import User -from mongoengine import disconnect -import base64 class AuthControllerTestCase(unittest.TestCase): @classmethod def setUpClass(cls): - disconnect(alias='default') + disconnect(alias="default") cls.app = create_app() - cls.app.config['TESTING'] = True + cls.app.config["TESTING"] = True cls.client = cls.app.test_client() @classmethod def tearDownClass(cls): - disconnect(alias='default') + disconnect(alias="default") def setUp(self): User.drop_collection() def test_register_user(self): - response = self.client.post('/auth/register', json={ - 'username': 'testuser', - 'email': 'testuser@example.com', - 'password': 'password', - 'is_dm': True - }) + response = self.client.post( + "/auth/register", + json={ + "username": "testuser", + "email": "testuser@example.com", + "password": "password", + "is_dm": True, + }, + ) self.assertEqual(response.status_code, 201) - self.assertEqual(response.json['message'], 'User registered successfully') + self.assertEqual( + response.json["message"], "User registered successfully" + ) def test_register_user_existing_username(self): - User(username='testuser', email='test1@example.com', password_hash='hash').save() - response = self.client.post('/auth/register', json={ - 'username': 'testuser', - 'email': 'test2@example.com', - 'password': 'password' - }) + User( + username="testuser", + email="test1@example.com", + password_hash="hash", + ).save() + response = self.client.post( + "/auth/register", + json={ + "username": "testuser", + "email": "test2@example.com", + "password": "password", + }, + ) self.assertEqual(response.status_code, 400) - self.assertEqual(response.json['message'], 'Username already exists') + self.assertEqual(response.json["message"], "Username already exists") def test_login_user(self): # Create the test user in the database - user = User(username='testuser', email='testuser@example.com') - user.set_password('password') + user = User(username="testuser", email="testuser@example.com") + user.set_password("password") user.save() # Encode the credentials in Base64 - credentials = base64.b64encode(b'testuser:password').decode('utf-8') + credentials = base64.b64encode(b"testuser:password").decode("utf-8") # Send the request with the Authorization header - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) self.assertEqual(response.status_code, 200) - self.assertIn('token', response.json) + self.assertIn("token", response.json) def test_login_user_invalid_credentials(self): # Encode incorrect credentials in Base64 - credentials = base64.b64encode(b'wronguser:password').decode('utf-8') + credentials = base64.b64encode(b"wronguser:password").decode("utf-8") # Send the request with the Authorization header - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) self.assertEqual(response.status_code, 401) - self.assertEqual(response.json['message'], 'Invalid credentials') + self.assertEqual(response.json["message"], "Invalid credentials") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_encounter.py b/tests/views/test_encounter.py index ecc9392..09cf846 100644 --- a/tests/views/test_encounter.py +++ b/tests/views/test_encounter.py @@ -1,4 +1,5 @@ import unittest + from app.models.encounter import Encounter from tests.views.test_view_base import ControllerTestBase @@ -7,12 +8,16 @@ class EncounterControllerTestCase(ControllerTestBase): def test_create_encounter(self): content = { - 'name': 'Test Encounter', - 'description': 'An encounter', - 'min_players': 1, - 'max_players': 4 + "name": "Test Encounter", + "description": "An encounter", + "min_players": 1, + "max_players": 4, } - response = self.client.post('/encounters/', json=content, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.post( + "/encounters/", + json=content, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 201) response_data = response.get_json() @@ -22,35 +27,59 @@ def test_create_encounter(self): self.assertEqual(response_data[key], value) def test_get_encounters(self): - encounter = Encounter(name='Test Encounter', description='An encounter', min_players=1, max_players=4) + encounter = Encounter( + name="Test Encounter", + description="An encounter", + min_players=1, + max_players=4, + ) encounter.save() - response = self.client.get('/encounters/', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/encounters/", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() self.assertIsInstance(response_data, list) self.assertGreaterEqual(len(response_data), 1) - self.assertIn('name', response_data[0]) - self.assertEqual(response_data[0]['name'], 'Test Encounter') + self.assertIn("name", response_data[0]) + self.assertEqual(response_data[0]["name"], "Test Encounter") def test_update_encounter(self): - encounter = Encounter(name='Test Encounter', description='An encounter', min_players=1, max_players=4) + encounter = Encounter( + name="Test Encounter", + description="An encounter", + min_players=1, + max_players=4, + ) encounter.save() - response = self.client.patch(f'/encounters/{encounter.id}', json={ - 'description': 'Updated description' - }, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.patch( + f"/encounters/{encounter.id}", + json={"description": "Updated description"}, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(response_data['description'], 'Updated description') + self.assertEqual(response_data["description"], "Updated description") def test_delete_encounter(self): - encounter = Encounter(name='Test Encounter', description='An encounter', min_players=1, max_players=4) + encounter = Encounter( + name="Test Encounter", + description="An encounter", + min_players=1, + max_players=4, + ) encounter.save() - response = self.client.delete(f'/encounters/{encounter.id}', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.delete( + f"/encounters/{encounter.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertIn('message', response_data) - self.assertEqual(response_data['message'], 'Encounter deleted successfully!') + self.assertIn("message", response_data) + self.assertEqual( + response_data["message"], "Encounter deleted successfully!" + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_item.py b/tests/views/test_item.py index b125c22..7e940d5 100644 --- a/tests/views/test_item.py +++ b/tests/views/test_item.py @@ -8,14 +8,18 @@ class ItemControllerTestCase(ControllerTestBase): def test_create_item(self): content = { - 'name': 'Test Item', - 'description': 'An item', - 'unique': True, - 'claimed': False, - 'has_been_rolled': False, - 'available': True + "name": "Test Item", + "description": "An item", + "unique": True, + "claimed": False, + "has_been_rolled": False, + "available": True, } - response = self.client.post('/items/', json=content, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.post( + "/items/", + json=content, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 201) response_data = response.get_json() self.assertIsNotNone(response_data.pop("_id", None)) @@ -24,41 +28,53 @@ def test_create_item(self): self.assertEqual(response_data[k], v) def test_get_items(self): - item = Item(name='Test Item', description='An item', unique=True) + item = Item(name="Test Item", description="An item", unique=True) item.save() - response = self.client.get('/items/', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/items/", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() self.assertIsInstance(response_data, list) self.assertGreaterEqual(len(response_data), 1) - self.assertIn('name', response_data[0]) - self.assertEqual(response_data[0]['name'], 'Test Item') + self.assertIn("name", response_data[0]) + self.assertEqual(response_data[0]["name"], "Test Item") def test_get_item_by_id(self): - item = Item(name='Test Item', description='An item', unique=True) + item = Item(name="Test Item", description="An item", unique=True) item.save() - response = self.client.get(f"/items/{item.id}", headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + f"/items/{item.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) def test_update_item(self): - item = Item(name='Test Item', description='An item', unique=True) + item = Item(name="Test Item", description="An item", unique=True) item.save() - response = self.client.patch(f'/items/{item.id}', json={ - 'description': 'Updated description' - }, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.patch( + f"/items/{item.id}", + json={"description": "Updated description"}, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(response_data['description'], 'Updated description') + self.assertEqual(response_data["description"], "Updated description") def test_delete_item(self): - item = Item(name='Test Item', description='An item', unique=True) + item = Item(name="Test Item", description="An item", unique=True) item.save() - response = self.client.delete(f'/items/{item.id}', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.delete( + f"/items/{item.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertIn('message', response_data) - self.assertEqual(response_data['message'], 'Item deleted successfully!') + self.assertIn("message", response_data) + self.assertEqual( + response_data["message"], "Item deleted successfully!" + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_roll.py b/tests/views/test_roll.py index a6e05da..99ee2b3 100644 --- a/tests/views/test_roll.py +++ b/tests/views/test_roll.py @@ -14,12 +14,12 @@ class RollControllerTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.app = create_app() - cls.app.config['TESTING'] = True + cls.app.config["TESTING"] = True cls.client = cls.app.test_client() @classmethod def tearDownClass(cls): - disconnect(alias='default') + disconnect(alias="default") def setUp(self): RollTable.drop_collection() @@ -27,11 +27,11 @@ def setUp(self): Encounter.drop_collection() Room.drop_collection() self.rolltable = RollTable( - name='Test RollTable', - description='A test rolltable', + name="Test RollTable", + description="A test rolltable", weight=5, - tier='Gold', - table_type='Weapons' + tier="Gold", + table_type="Weapons", ) self.rolltable.save() @@ -42,67 +42,103 @@ def tearDown(self): Room.drop_collection() def test_perform_roll_with_items(self): - item1 = Item(name='Item 1', description='First item', unique=True, claimed=False, has_been_rolled=False, - available=True) - item2 = Item(name='Item 2', description='Second item', unique=True, claimed=False, has_been_rolled=False, - available=True) + item1 = Item( + name="Item 1", + description="First item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) + item2 = Item( + name="Item 2", + description="Second item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) item1.save() item2.save() self.rolltable.items = [item1, item2] self.rolltable.save() - response = self.client.post('/rolls/', json={ - 'rolltable_id': str(self.rolltable.id), - 'num_results': 1, - 'constraints': {} - }) + response = self.client.post( + "/rolls/", + json={ + "rolltable_id": str(self.rolltable.id), + "num_results": 1, + "constraints": {}, + }, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertIn('results', response_data) - self.assertEqual(len(response_data['results']), 1) + self.assertIn("results", response_data) + self.assertEqual(len(response_data["results"]), 1) def test_perform_roll_no_results(self): - response = self.client.post('/rolls/', json={ - 'rolltable_id': str(self.rolltable.id), - 'num_results': 1, - 'constraints': {} - }) + response = self.client.post( + "/rolls/", + json={ + "rolltable_id": str(self.rolltable.id), + "num_results": 1, + "constraints": {}, + }, + ) self.assertEqual(response.status_code, 204) def test_perform_roll_with_constraints(self): - item1 = Item(name='Item 1', description='First item', unique=True, claimed=False, has_been_rolled=False, - available=True) - item2 = Item(name='Item 2', description='Second item', unique=True, claimed=True, has_been_rolled=False, - available=True) + item1 = Item( + name="Item 1", + description="First item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) + item2 = Item( + name="Item 2", + description="Second item", + unique=True, + claimed=True, + has_been_rolled=False, + available=True, + ) item1.save() item2.save() self.rolltable.items = [item1, item2] self.rolltable.save() - response = self.client.post('/rolls/', json={ - 'rolltable_id': str(self.rolltable.id), - 'num_results': 1, - 'constraints': {'claimed': False} - }) + response = self.client.post( + "/rolls/", + json={ + "rolltable_id": str(self.rolltable.id), + "num_results": 1, + "constraints": {"claimed": False}, + }, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertIn('results', response_data) - self.assertEqual(len(response_data['results']), 1) - self.assertEqual(response_data['results'][0]['name'], 'Item 1') + self.assertIn("results", response_data) + self.assertEqual(len(response_data["results"]), 1) + self.assertEqual(response_data["results"][0]["name"], "Item 1") def test_perform_roll_invalid_rolltable(self): - response = self.client.post('/rolls/', json={ - 'rolltable_id': 'aaaaaaaaaaaaaaaaaaaaaaaa', - 'num_results': 1, - 'constraints': {} - }) + response = self.client.post( + "/rolls/", + json={ + "rolltable_id": "aaaaaaaaaaaaaaaaaaaaaaaa", + "num_results": 1, + "constraints": {}, + }, + ) self.assertEqual(response.status_code, 404) response_data = response.get_json() - self.assertEqual(response_data['message'], 'RollTable not found!') + self.assertEqual(response_data["message"], "RollTable not found!") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_rolltable.py b/tests/views/test_rolltable.py index e2b50d4..7349e31 100644 --- a/tests/views/test_rolltable.py +++ b/tests/views/test_rolltable.py @@ -9,19 +9,30 @@ class RollTableControllerTestCase(ControllerTestBase): def setUp(self): super().setUp() - self.rolltable = RollTable(name="Test RollTable", description="A rolltable", weight=5, tier="Gold", - table_type="Magic Items").save() - self.item = Item(name="Sword of Testing", description="A powerful sword", weight=10).save() + self.rolltable = RollTable( + name="Test RollTable", + description="A rolltable", + weight=5, + tier="Gold", + table_type="Magic Items", + ).save() + self.item = Item( + name="Sword of Testing", description="A powerful sword", weight=10 + ).save() def test_create_rolltable(self): content = { - 'name': 'Test RollTable', - 'description': 'A rolltable', - 'weight': 5, - 'tier': 'Gold', - 'table_type': 'Magic Items' + "name": "Test RollTable", + "description": "A rolltable", + "weight": 5, + "tier": "Gold", + "table_type": "Magic Items", } - response = self.client.post('/rolltables/', json=content, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.post( + "/rolltables/", + json=content, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 201) response_data = response.get_json() @@ -33,49 +44,69 @@ def test_create_rolltable(self): self.assertEqual(response_data[key], value) def test_get_rolltables(self): - rolltable = RollTable(name='Test RollTable', - description='A rolltable', - weight=5, tier='Gold', - table_type='Magic Items') + rolltable = RollTable( + name="Test RollTable", + description="A rolltable", + weight=5, + tier="Gold", + table_type="Magic Items", + ) rolltable.save() - response = self.client.get('/rolltables/', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/rolltables/", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() self.assertIsInstance(response_data, list) self.assertGreaterEqual(len(response_data), 1) - self.assertIn('name', response_data[0]) - self.assertEqual(response_data[0]['name'], 'Test RollTable') + self.assertIn("name", response_data[0]) + self.assertEqual(response_data[0]["name"], "Test RollTable") def test_update_rolltable(self): - rolltable = RollTable(name='Test RollTable', - description='A rolltable', - weight=5, tier='Gold', - table_type='Magic Items') + rolltable = RollTable( + name="Test RollTable", + description="A rolltable", + weight=5, + tier="Gold", + table_type="Magic Items", + ) rolltable.save() - response = self.client.patch(f'/rolltables/{rolltable.id}', json={ - 'description': 'Updated description' - }, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.patch( + f"/rolltables/{rolltable.id}", + json={"description": "Updated description"}, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(response_data['description'], 'Updated description') + self.assertEqual(response_data["description"], "Updated description") def test_delete_rolltable(self): - rolltable = RollTable(name='Test RollTable', - description='A rolltable', - weight=5, tier='Gold', - table_type='Magic Items') + rolltable = RollTable( + name="Test RollTable", + description="A rolltable", + weight=5, + tier="Gold", + table_type="Magic Items", + ) rolltable.save() - response = self.client.delete(f'/rolltables/{rolltable.id}', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.delete( + f"/rolltables/{rolltable.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertIn('message', response_data) - self.assertEqual(response_data['message'], 'RollTable deleted successfully!') + self.assertIn("message", response_data) + self.assertEqual( + response_data["message"], "RollTable deleted successfully!" + ) def test_add_item_to_rolltable(self): data = {"items": [str(self.item.id)]} - response = self.client.post(f'/rolltables/{self.rolltable.id}/add', json=data, headers={ - 'Authorization': f'Bearer {self.token}' - }) + response = self.client.post( + f"/rolltables/{self.rolltable.id}/add", + json=data, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) self.assertIn("items", response.json) @@ -83,35 +114,39 @@ def test_add_item_to_rolltable(self): self.assertEqual(response.json["items"][0], str(self.item.id)) def test_add_to_nonexistent_rolltable(self): - data = { - "items": [str(self.item.id)] - } - response = self.client.post('/rolltables/507f1f77bcf86cd799439011/add', json=data, headers={ - 'Authorization': f'Bearer {self.token}' - }) + data = {"items": [str(self.item.id)]} + response = self.client.post( + "/rolltables/507f1f77bcf86cd799439011/add", + json=data, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 404) - self.assertEqual(response.json['message'], 'RollTable not found!') + self.assertEqual(response.json["message"], "RollTable not found!") def test_add_invalid_data_to_rolltable(self): - data = { - "invalid_field": "invalid_value" - } - response = self.client.post(f'/rolltables/{self.rolltable.id}/add', json=data, headers={ - 'Authorization': f'Bearer {self.token}' - }) + data = {"invalid_field": "invalid_value"} + response = self.client.post( + f"/rolltables/{self.rolltable.id}/add", + json=data, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 400) - self.assertEqual(response.json['message'], 'No valid fields to update!') + self.assertEqual( + response.json["message"], "No valid fields to update!" + ) def test_add_without_token(self): - data = { - "items": [str(self.item.id)] - } - response = self.client.post(f'/rolltables/{self.rolltable.id}/add', json=data) + data = {"items": [str(self.item.id)]} + response = self.client.post( + f"/rolltables/{self.rolltable.id}/add", json=data + ) - self.assertEqual(response.status_code, 403) # Expecting Forbidden since no token is provided + self.assertEqual( + response.status_code, 403 + ) # Expecting Forbidden since no token is provided -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_room.py b/tests/views/test_room.py index 0b54754..f5f3f7e 100644 --- a/tests/views/test_room.py +++ b/tests/views/test_room.py @@ -1,4 +1,5 @@ import unittest + from app.models.room import Room from tests.views.test_view_base import ControllerTestBase @@ -7,11 +8,15 @@ class RoomControllerTestCase(ControllerTestBase): def test_create_room(self): content = { - 'name': 'Test Room', - 'description': 'A room', - 'reward_tier': 'Gold' + "name": "Test Room", + "description": "A room", + "reward_tier": "Gold", } - response = self.client.post('/rooms/', json=content, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.post( + "/rooms/", + json=content, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 201) response_data = response.get_json() @@ -23,35 +28,44 @@ def test_create_room(self): self.assertEqual(response_data[key], value) def test_get_rooms(self): - room = Room(name='Test Room', description='A room', reward_tier='Gold') + room = Room(name="Test Room", description="A room", reward_tier="Gold") room.save() - response = self.client.get('/rooms/', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/rooms/", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() self.assertIsInstance(response_data, list) self.assertGreaterEqual(len(response_data), 1) - self.assertIn('name', response_data[0]) - self.assertEqual(response_data[0]['name'], 'Test Room') + self.assertIn("name", response_data[0]) + self.assertEqual(response_data[0]["name"], "Test Room") def test_update_room(self): - room = Room(name='Test Room', description='A room', reward_tier='Gold') + room = Room(name="Test Room", description="A room", reward_tier="Gold") room.save() - response = self.client.patch(f'/rooms/{room.id}', json={ - 'description': 'Updated description' - }, headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.patch( + f"/rooms/{room.id}", + json={"description": "Updated description"}, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(response_data['description'], 'Updated description') + self.assertEqual(response_data["description"], "Updated description") def test_delete_room(self): - room = Room(name='Test Room', description='A room', reward_tier='Gold') + room = Room(name="Test Room", description="A room", reward_tier="Gold") room.save() - response = self.client.delete(f'/rooms/{room.id}', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.delete( + f"/rooms/{room.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertIn('message', response_data) - self.assertEqual(response_data['message'], 'Room deleted successfully!') + self.assertIn("message", response_data) + self.assertEqual( + response_data["message"], "Room deleted successfully!" + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_session.py b/tests/views/test_session.py index ffacab3..1995357 100644 --- a/tests/views/test_session.py +++ b/tests/views/test_session.py @@ -12,14 +12,14 @@ class SessionControllerTestCase(unittest.TestCase): @classmethod def setUpClass(cls): - disconnect(alias='default') + disconnect(alias="default") cls.app = create_app() - cls.app.config['TESTING'] = True + cls.app.config["TESTING"] = True cls.client = cls.app.test_client() @classmethod def tearDownClass(cls): - disconnect(alias='default') + disconnect(alias="default") def setUp(self): # Clean up the database before each test @@ -27,36 +27,52 @@ def setUp(self): Item.drop_collection() # Create a DM user and log in - self.dm_user = User(username='dmuser', email='dmuser@example.com', is_dm=True) - self.dm_user.set_password('password') + self.dm_user = User( + username="dmuser", email="dmuser@example.com", is_dm=True + ) + self.dm_user.set_password("password") self.dm_user.save() # Log in as DM to get a token - credentials = base64.b64encode(b'dmuser:password').decode('utf-8') - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) - self.token = response.json['token'] + credentials = base64.b64encode(b"dmuser:password").decode("utf-8") + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) + self.token = response.json["token"] # Create a regular user - self.regular_user = User(username='regularuser', email='regularuser@example.com', is_dm=False) - self.regular_user.set_password('password') + self.regular_user = User( + username="regularuser", + email="regularuser@example.com", + is_dm=False, + ) + self.regular_user.set_password("password") self.regular_user.items = [] self.regular_user.save() # Create items and assign some to the regular user - self.item1 = Item(name="Sword of Testing", description="A powerful sword", weight=10, available=False, - claimed=True).save() - self.item2 = Item(name="Shield of Testing", description="A sturdy shield", weight=15, available=False, - claimed=True).save() + self.item1 = Item( + name="Sword of Testing", + description="A powerful sword", + weight=10, + available=False, + claimed=True, + ).save() + self.item2 = Item( + name="Shield of Testing", + description="A sturdy shield", + weight=15, + available=False, + claimed=True, + ).save() self.regular_user.items.extend([self.item1, self.item2]) self.regular_user.save() def test_clear_session(self): # Test clearing session as DM - response = self.client.post('/session/clear', headers={ - 'Authorization': f'Bearer {self.token}' - }) + response = self.client.post( + "/session/clear", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 204) @@ -74,25 +90,26 @@ def test_clear_session(self): def test_clear_session_as_non_dm(self): # Log in as a regular user to get a token - credentials = base64.b64encode(b'regularuser:password').decode('utf-8') - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) - non_dm_token = response.json['token'] + credentials = base64.b64encode(b"regularuser:password").decode("utf-8") + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) + non_dm_token = response.json["token"] # Attempt to clear session as a non-DM user - response = self.client.post('/session/clear', headers={ - 'Authorization': f'Bearer {non_dm_token}' - }) + response = self.client.post( + "/session/clear", + headers={"Authorization": f"Bearer {non_dm_token}"}, + ) self.assertEqual(response.status_code, 403) # Expecting Forbidden def test_clear_session_without_token(self): # Attempt to clear session without providing a token - response = self.client.post('/session/clear') + response = self.client.post("/session/clear") self.assertEqual(response.status_code, 403) # Expecting Forbidden -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_user.py b/tests/views/test_user.py index 82f6eef..6be982e 100644 --- a/tests/views/test_user.py +++ b/tests/views/test_user.py @@ -10,157 +10,204 @@ class UserControllerTestCase(ControllerTestBase): def setUp(self): super().setUp() - self.user = User(username='user', email='regular@example.com', is_dm=True) - self.user.set_password('password') + self.user = User( + username="user", email="regular@example.com", is_dm=True + ) + self.user.set_password("password") self.user.save() - self.item = Item(name='Test Item', - description='A test item', - unique=True, claimed=False, - has_been_rolled=False, - available=True).save() + self.item = Item( + name="Test Item", + description="A test item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ).save() def test_get_current_user_items(self): self.dm_user.items.append(self.item) self.dm_user.save() - response = self.client.get('/users/items', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/users/items", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(response_data['username'], 'dmuser') - self.assertEqual(len(response_data['items']), 1) - self.assertEqual(response_data['items'][0]['name'], 'Test Item') + self.assertEqual(response_data["username"], "dmuser") + self.assertEqual(len(response_data["items"]), 1) + self.assertEqual(response_data["items"][0]["name"], "Test Item") def test_get_specific_user_items(self): - other_user = User(username='otheruser', email='otheruser@example.com', is_dm=False) - other_user.set_password('password') + other_user = User( + username="otheruser", email="otheruser@example.com", is_dm=False + ) + other_user.set_password("password") other_user.items.append(self.item) other_user.save() - response = self.client.get(f'/users/items?user_id={other_user.id}', - headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + f"/users/items?user_id={other_user.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(response_data['username'], 'otheruser') - self.assertEqual(len(response_data['items']), 1) - self.assertEqual(response_data['items'][0]['name'], 'Test Item') + self.assertEqual(response_data["username"], "otheruser") + self.assertEqual(len(response_data["items"]), 1) + self.assertEqual(response_data["items"][0]["name"], "Test Item") def test_get_all_users_items(self): - other_user = User(username='otheruser', email='otheruser@example.com', is_dm=False) - other_user.set_password('password') - item1 = Item(name='Test Item 1', - description='First test item', - unique=True, - claimed=False, - has_been_rolled=False, - available=True) - item2 = Item(name='Test Item 2', - description='Second test item', - unique=True, - claimed=False, - has_been_rolled=False, - available=True) + other_user = User( + username="otheruser", email="otheruser@example.com", is_dm=False + ) + other_user.set_password("password") + item1 = Item( + name="Test Item 1", + description="First test item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) + item2 = Item( + name="Test Item 2", + description="Second test item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) item1.save() item2.save() self.dm_user.items.append(item1) other_user.items.append(item2) self.dm_user.save() other_user.save() - response = self.client.get('/users/items?all=true', headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/users/items?all=true", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(len(response_data['users']), 3) - user_data = {user['username']: user for user in response_data['users']} - self.assertEqual(len(user_data['dmuser']['items']), 1) - self.assertEqual(user_data['dmuser']['items'][0]['name'], 'Test Item 1') - self.assertEqual(len(user_data['otheruser']['items']), 1) - self.assertEqual(user_data['otheruser']['items'][0]['name'], 'Test Item 2') + self.assertEqual(len(response_data["users"]), 3) + user_data = {user["username"]: user for user in response_data["users"]} + self.assertEqual(len(user_data["dmuser"]["items"]), 1) + self.assertEqual( + user_data["dmuser"]["items"][0]["name"], "Test Item 1" + ) + self.assertEqual(len(user_data["otheruser"]["items"]), 1) + self.assertEqual( + user_data["otheruser"]["items"][0]["name"], "Test Item 2" + ) def test_get_all_users_items_exclude_user(self): - other_user = User(username='otheruser', email='otheruser@example.com', is_dm=False) - other_user.set_password('password') - item1 = Item(name='Test Item 1', - description='First test item', - unique=True, - claimed=False, - has_been_rolled=False, - available=True) - item2 = Item(name='Test Item 2', - description='Second test item', - unique=True, - claimed=False, - has_been_rolled=False, - available=True) + other_user = User( + username="otheruser", email="otheruser@example.com", is_dm=False + ) + other_user.set_password("password") + item1 = Item( + name="Test Item 1", + description="First test item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) + item2 = Item( + name="Test Item 2", + description="Second test item", + unique=True, + claimed=False, + has_been_rolled=False, + available=True, + ) item1.save() item2.save() self.dm_user.items.append(item1) other_user.items.append(item2) self.dm_user.save() other_user.save() - response = self.client.get(f'/users/items?all=true&user_id={self.dm_user.id}', - headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + f"/users/items?all=true&user_id={self.dm_user.id}", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) response_data = response.get_json() - self.assertEqual(len(response_data['users']), 2) - self.assertEqual(response_data['users'][1]['username'], 'otheruser') - self.assertEqual(len(response_data['users'][1]['items']), 1) - self.assertEqual(response_data['users'][1]['items'][0]['name'], 'Test Item 2') + self.assertEqual(len(response_data["users"]), 2) + self.assertEqual(response_data["users"][1]["username"], "otheruser") + self.assertEqual(len(response_data["users"][1]["items"]), 1) + self.assertEqual( + response_data["users"][1]["items"][0]["name"], "Test Item 2" + ) def test_get_user_items_user_not_found(self): - response = self.client.get('/users/items?user_id=604c6e206c8e4a7f94b2b2a3', - headers={'Authorization': f'Bearer {self.token}'}) + response = self.client.get( + "/users/items?user_id=604c6e206c8e4a7f94b2b2a3", + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 404) response_data = response.get_json() - self.assertEqual(response_data['message'], 'User not found!') + self.assertEqual(response_data["message"], "User not found!") def test_get_users_as_dm(self): - self.regular_user = User(username='regular_user', email='regular@example.com', is_dm=False) - self.regular_user.set_password('password') + self.regular_user = User( + username="regular_user", email="regular@example.com", is_dm=False + ) + self.regular_user.set_password("password") self.regular_user.save() - credentials = base64.b64encode(b'regular_user:password').decode('utf-8') - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) - self.non_admin_token = response.json['token'] + credentials = base64.b64encode(b"regular_user:password").decode( + "utf-8" + ) + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) + self.non_admin_token = response.json["token"] # Test that DM can access the user list - response = self.client.get('/users/', headers={ - 'Authorization': f'Bearer {self.token}' - }) + response = self.client.get( + "/users/", headers={"Authorization": f"Bearer {self.token}"} + ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json), 3) - usernames = [user['username'] for user in response.json] - self.assertIn('dmuser', usernames) - self.assertIn('regular_user', usernames) + usernames = [user["username"] for user in response.json] + self.assertIn("dmuser", usernames) + self.assertIn("regular_user", usernames) def test_get_users_as_non_dm(self): - self.regular_user = User(username='regular_user', email='regular@example.com', is_dm=False) - self.regular_user.set_password('password') + self.regular_user = User( + username="regular_user", email="regular@example.com", is_dm=False + ) + self.regular_user.set_password("password") self.regular_user.save() - credentials = base64.b64encode(b'regular_user:password').decode('utf-8') - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) - self.non_admin_token = response.json['token'] + credentials = base64.b64encode(b"regular_user:password").decode( + "utf-8" + ) + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) + self.non_admin_token = response.json["token"] # Test that a non-DM cannot access the user list - response = self.client.get('/users/', headers={ - 'Authorization': f'Bearer {self.non_admin_token}' - }) + response = self.client.get( + "/users/", + headers={"Authorization": f"Bearer {self.non_admin_token}"}, + ) self.assertEqual(response.status_code, 403) # Forbidden def test_get_users_no_token(self): # Test that no token results in unauthorized access - response = self.client.get('/users/') + response = self.client.get("/users/") print(response.json) self.assertEqual(response.status_code, 403) # Forbidden def test_add_item_to_user(self): data = {"items": [str(self.item.id)]} - response = self.client.post(f'/users/{self.user.id}/add', json=data, headers={ - 'Authorization': f'Bearer {self.token}' - }) + response = self.client.post( + f"/users/{self.user.id}/add", + json=data, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 200) self.assertIn("items", response.json) @@ -168,35 +215,37 @@ def test_add_item_to_user(self): self.assertEqual(response.json["items"][0], str(self.item.id)) def test_add_to_nonexistent_user(self): - data = { - "items": [str(self.item.id)] - } - response = self.client.post('/users/507f1f77bcf86cd799439011/add', json=data, headers={ - 'Authorization': f'Bearer {self.token}' - }) + data = {"items": [str(self.item.id)]} + response = self.client.post( + "/users/507f1f77bcf86cd799439011/add", + json=data, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 404) - self.assertEqual(response.json['message'], 'User not found!') + self.assertEqual(response.json["message"], "User not found!") def test_add_invalid_data_to_user(self): - data = { - "invalid_field": "invalid_value" - } - response = self.client.post(f'/users/{self.user.id}/add', json=data, headers={ - 'Authorization': f'Bearer {self.token}' - }) + data = {"invalid_field": "invalid_value"} + response = self.client.post( + f"/users/{self.user.id}/add", + json=data, + headers={"Authorization": f"Bearer {self.token}"}, + ) self.assertEqual(response.status_code, 400) - self.assertEqual(response.json['message'], 'No valid fields to update!') + self.assertEqual( + response.json["message"], "No valid fields to update!" + ) def test_add_without_token(self): - data = { - "items": [str(self.item.id)] - } - response = self.client.post(f'/users/{self.user.id}/add', json=data) + data = {"items": [str(self.item.id)]} + response = self.client.post(f"/users/{self.user.id}/add", json=data) - self.assertEqual(response.status_code, 403) # Expecting Forbidden since no token is provided + self.assertEqual( + response.status_code, 403 + ) # Expecting Forbidden since no token is provided -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/views/test_view_base.py b/tests/views/test_view_base.py index 8c1ef51..c0fd9e1 100644 --- a/tests/views/test_view_base.py +++ b/tests/views/test_view_base.py @@ -17,23 +17,25 @@ class ControllerTestBase(unittest.TestCase): @classmethod def setUpClass(cls): - disconnect(alias='default') + disconnect(alias="default") cls.app = create_app() - cls.app.config['TESTING'] = True + cls.app.config["TESTING"] = True cls.client = cls.app.test_client() @classmethod def tearDownClass(cls): - disconnect(alias='default') + disconnect(alias="default") def setUp(self): drop_all_collections() - self.dm_user = User(username='dmuser', email='dmuser@example.com', is_dm=True) - self.dm_user.set_password('password') + self.dm_user = User( + username="dmuser", email="dmuser@example.com", is_dm=True + ) + self.dm_user.set_password("password") self.dm_user.save() - credentials = base64.b64encode(b'dmuser:password').decode('utf-8') - response = self.client.post('/auth/login', headers={ - 'Authorization': f'Basic {credentials}' - }) - self.token = response.json['token'] + credentials = base64.b64encode(b"dmuser:password").decode("utf-8") + response = self.client.post( + "/auth/login", headers={"Authorization": f"Basic {credentials}"} + ) + self.token = response.json["token"]