Skip to content

Commit

Permalink
added test units to user-service and added volumes to user-service an…
Browse files Browse the repository at this point in the history
…d frontend
  • Loading branch information
mtoof committed Jul 8, 2024
1 parent 0ce939a commit 1ebfb51
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 6 deletions.
4 changes: 2 additions & 2 deletions Backend/user_service/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ENV LANG=C.UTF-8
RUN apk update && apk add --no-cache python3 py3-pip \
postgresql16 postgresql16-client \
bash supervisor curl openssl bash \
build-base libffi-dev python3-dev
build-base libffi-dev python3-dev nano
# Set work directory
RUN mkdir /run/postgresql && \
chown postgres:postgres /run/postgresql && \
Expand Down Expand Up @@ -38,7 +38,7 @@ RUN chown -R postgres:postgres /etc/supervisor && \
chown -R postgres:postgres /app/user_service && \
chmod +x /usr/bin/supervisord

# USER postgres
USER root

HEALTHCHECK --interval=30s --timeout=2s --start-period=5s --retries=3 CMD curl -sSf http://localhost:8001/user/register/ > /dev/null && echo "success" || echo "failure"

Expand Down
4 changes: 3 additions & 1 deletion Backend/user_service/init_database.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ exec postgres -D /var/lib/postgresql/data &
# Wait for PostgreSQL to start (you may need to adjust the sleep time)
sleep 5

# Create a new PostgreSQL user and set the password
# Create a new PostgreSQL user and set the passwordd
psql -c "CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASS}';"
psql -c "GRANT ALL PRIVILEGES ON SCHEMA public TO ${DB_USER};"
psql -c "ALTER USER ${DB_USER} CREATEDB;"
psql -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO ${DB_USER};"
# psql -c "GRANT ALL PRIVILEGES ON DATABASE test_postgres TO ${DB_USER};"

# Stop the PostgreSQL server after setting the password
pg_ctl stop -D /var/lib/postgresql/data
Expand Down
3 changes: 2 additions & 1 deletion Backend/user_service/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ gunicorn==20.1.0; python_version <= '3.12'
django-environ
daphne
pytest
pytest-django
pytest-django
pytest-mock
3 changes: 3 additions & 0 deletions Backend/user_service/user_service/pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[pytest]
DJANGO_SETTINGS_MODULE = user_service.settings
python_files = tests.py test_*.py *_tests.py
7 changes: 6 additions & 1 deletion Backend/user_service/user_service/user_service/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,12 @@
"USER": "root",
"PASSWORD": "root",
"PORT": "5432",
}
"ATOMIC_REQUESTS": True,
"TEST": {
"NAME": "mytestdatabase",
"ATOMIC_REQUESTS": True,
},
},
}


Expand Down
Empty file.
103 changes: 103 additions & 0 deletions Backend/user_service/user_service/user_service/test/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# conftest.py
import os
import django
from django.conf import settings
import pytest
from datetime import timedelta

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'user_service.settings')

if not settings.configured:
settings.configure(
DEBUG=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "postgres",
"USER": "root",
"PASSWORD": "root",
"PORT": "5432",
"HOST": "localhost",
"ATOMIC_REQUESTS": True,
"TEST": {
"NAME": "mytestdatabase",
"ATOMIC_REQUESTS": True,
},
},
},
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'user_app',
],
MIDDLEWARE=[
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
ROOT_URLCONF='user_service.urls',
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
],
WSGI_APPLICATION='user_service.wsgi.application',
SECRET_KEY='django-insecure-woftd2en2**zr(b%#*2vit2v%s@(k54gb^c(ots0abo7(wsmo%',
ALLOWED_HOSTS=['localhost', '127.0.0.1', '[::1]', 'user-session', 'user-session:8004'],
RABBITMQ_HOST='localhost',
RABBITMQ_USER='user',
RABBITMQ_PASS='pass',
RABBITMQ_PORT='5672',
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
},
SIMPLE_JWT={
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_OBTAIN_SERIALIZER': 'user_auth.serializers.CustomTokenObtainPairSerializer',
},
LANGUAGE_CODE='en-us',
TIME_ZONE='UTC',
USE_I18N=True,
USE_L10N=True,
USE_TZ=True,
STATIC_URL='/static/',
DEFAULT_AUTO_FIELD='django.db.models.BigAutoField',
CORS_ORIGIN_ALLOW_ALL=True,
)

django.setup()

@pytest.fixture(scope='session', autouse=True)
def django_db_modify_db_settings():
settings.DATABASES['default'] = settings.DATABASES['default']['TEST']

@pytest.fixture(scope='session')
def db_access(db):
pass
79 changes: 79 additions & 0 deletions Backend/user_service/user_service/user_service/test/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import pytest
import json
from django.urls import reverse
from unittest.mock import patch, MagicMock
from rest_framework_simplejwt.tokens import RefreshToken
from user_app.views import UserViewSet, RegisterViewSet
from rest_framework import status
from user_app.models import User

@pytest.fixture
def api_client():
from rest_framework.test import APIClient
return APIClient()

@pytest.fixture
def user_data():
return {
'id': 1,
'username': 'testuser',
'email': '[email protected]',
'password': 'Test@123'
}

@pytest.mark.django_db
def test_user_register(api_client, user_data):
url = reverse('register-user')
response = api_client.post(url, user_data, format='json')
assert response.status_code == 201
assert response.data['id'] == 1
assert response.data['username'] == 'testuser'
assert response.data['email'] == '[email protected]'


@pytest.fixture
def user(db):
return User.objects.create_user(username='testuser', email='[email protected]', password='Test@123')

@pytest.fixture
def admin_user(db):
return User.objects.create_superuser(username='admin', email='[email protected]', password='Admin@123')

@pytest.fixture
def user_token(user):
refresh = RefreshToken.for_user(user)
return str(refresh.access_token)

@pytest.fixture
def admin_token(admin_user):
refresh = RefreshToken.for_user(admin_user)
return str(refresh.access_token)

@pytest.mark.django_db
def test_users_list(api_client, admin_user, admin_token, user_data):
# Mock the RabbitMQ interactions
user1 = User.objects.create_user(username='testuser1',email='[email protected]',password='Test@123')
user2 = User.objects.create_user(username='testuser2',email='[email protected]',password='Test@123')
with patch('user_app.views.publish_message') as mock_publish, patch('user_app.views.consume_message') as mock_consume:
# Set up the mock for consume_message to simulate a valid token response
def mock_consume_response(queue_name, callback):
response_data = json.dumps({"is_valid": True})
ch_mock = MagicMock()
method = None
properties = None
body = response_data.encode('utf-8')
callback(ch_mock, method, properties, body)

mock_consume.side_effect = mock_consume_response

# Authenticate the request
token = admin_token
api_client.credentials(HTTP_AUTHORIZATION=f'Bearer {token}')

# Call the API endpoint
url = reverse('users-list') # Ensure this matches your URL configuration
response = api_client.get(url)

# Assert the response status and content
print("response data=", response.data)
assert response.status_code == status.HTTP_200_OK
8 changes: 7 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ networks:
transcendence_network:
name: transcendence_network
driver: bridge

volumes:
www_data:
name: www_data
services:
rabbitmq:
container_name: rabbitmq
Expand Down Expand Up @@ -45,6 +47,8 @@ services:
# - 8001:8001
networks:
- transcendence_network
volumes:
- www_data:/www/avatars
depends_on:
- rabbitmq

Expand Down Expand Up @@ -75,6 +79,8 @@ services:
- 3000:443
networks:
- transcendence_network
volumes:
- www_data:/www/avatars
depends_on:
- user-service
- token-service
Expand Down

0 comments on commit 1ebfb51

Please sign in to comment.