Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

T36032 User.username should be unique #154

Merged
merged 3 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions api/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ def _get_collection(self, model):
col = self.COLLECTIONS[model]
return self._db[col]

async def create_indexes(self):
"""Create indexes for models"""
for model in self.COLLECTIONS:
col = self._get_collection(model)
model.create_indexes(col)

async def find_all(self, model):
"""Find all objects of a given model"""
col = self._get_collection(model)
Expand Down
12 changes: 12 additions & 0 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
SecurityScopes
)
from bson import ObjectId, errors
from pymongo.errors import DuplicateKeyError
from .auth import Authentication, Token
from .db import Database
from .models import Node, Regression, User, Password, get_model_from_kind
Expand All @@ -35,6 +36,12 @@ async def pubsub_startup():
pubsub = await PubSub.create()


@app.on_event('startup')
async def create_indexes():
"""Startup event handler to create database indexes"""
await db.create_indexes()


async def get_current_user(
security_scopes: SecurityScopes,
token: str = Depends(auth.oauth2_scheme)):
Expand Down Expand Up @@ -86,6 +93,11 @@ async def post_user(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(error)
) from error
except DuplicateKeyError as error:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"{username} is already taken. Try with different username."
) from error
await pubsub.publish_cloudevent('user', {'op': operation,
'id': str(obj.id)})
return obj
Expand Down
11 changes: 10 additions & 1 deletion api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,12 @@ class DatabaseModel(ModelId):
def update(self):
"""Method to update model"""

@classmethod
def create_indexes(cls, collection):
"""Method to create indexes"""


class User(ModelId):
class User(DatabaseModel):
"""API user model"""
username: str
hashed_password: str = Field(description='Hash of the plaintext password')
Expand All @@ -100,6 +104,11 @@ class User(ModelId):
description='True if superuser otherwise False'
)

@classmethod
def create_indexes(cls, collection):
"""Create an index to bind unique constraint to username"""
collection.create_index("username", unique=True)
gctucker marked this conversation as resolved.
Show resolved Hide resolved


class KernelVersion(BaseModel):
"""Linux kernel version model"""
Expand Down
15 changes: 15 additions & 0 deletions test/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""pytest fixtures for KernelCI API"""

from unittest.mock import AsyncMock
import asyncio
import fakeredis.aioredis
from fastapi.testclient import TestClient
import pytest
Expand All @@ -35,6 +36,20 @@ def client():
return TestClient(app)


@pytest.fixture
def event_loop():
"""Create an instance of the default event loop for each test case.
This is a workaround to prevent the default event loop to be closed by
async pubsub tests. It was causing other tests unable to run.
The issue has already been reported here:
https://github.com/pytest-dev/pytest-asyncio/issues/371
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
yield loop
loop.close()


@pytest.fixture
def mock_db_create(mocker):
"""Mocks async call to Database class method used to create object"""
Expand Down