From 971a5a8f628543d1473b3468c129884d9a437854 Mon Sep 17 00:00:00 2001 From: TemiTope Date: Sun, 29 Dec 2024 14:26:25 +0000 Subject: [PATCH] Added tests for backend --- backend/backend/__init__.py | 0 backend/backend/asgi.py | 16 +++ backend/backend/settings.py | 123 ++++++++++++++++ backend/backend/urls.py | 22 +++ backend/backend/wsgi.py | 16 +++ backend/manage.py | 22 +++ backend/settings.py | 156 ++++++++++++++++++++ django_react_jollof/backend.py | 2 +- django_react_jollof/tests/test_backend.py | 166 ++++++++++++++++++++++ requirements.txt | 12 +- 10 files changed, 527 insertions(+), 8 deletions(-) create mode 100644 backend/backend/__init__.py create mode 100644 backend/backend/asgi.py create mode 100644 backend/backend/settings.py create mode 100644 backend/backend/urls.py create mode 100644 backend/backend/wsgi.py create mode 100755 backend/manage.py create mode 100644 backend/settings.py create mode 100644 django_react_jollof/tests/test_backend.py diff --git a/backend/backend/__init__.py b/backend/backend/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/backend/asgi.py b/backend/backend/asgi.py new file mode 100644 index 0000000..20e4b44 --- /dev/null +++ b/backend/backend/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for backend project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") + +application = get_asgi_application() diff --git a/backend/backend/settings.py b/backend/backend/settings.py new file mode 100644 index 0000000..8631dfa --- /dev/null +++ b/backend/backend/settings.py @@ -0,0 +1,123 @@ +""" +Django settings for backend project. + +Generated by 'django-admin startproject' using Django 5.1.4. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.1/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "django-insecure-s&2&k709$!(p0)=^v&b!np+w!c(bok9q-ky_7pvo4rydvz$u!=" + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", +] + +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 = "backend.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 = "backend.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/5.1/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.1/topics/i18n/ + +LANGUAGE_CODE = "en-us" + +TIME_ZONE = "UTC" + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.1/howto/static-files/ + +STATIC_URL = "static/" + +# Default primary key field type +# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/backend/backend/urls.py b/backend/backend/urls.py new file mode 100644 index 0000000..4e3770f --- /dev/null +++ b/backend/backend/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for backend project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path("admin/", admin.site.urls), +] diff --git a/backend/backend/wsgi.py b/backend/backend/wsgi.py new file mode 100644 index 0000000..ae9503c --- /dev/null +++ b/backend/backend/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for backend project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") + +application = get_wsgi_application() diff --git a/backend/manage.py b/backend/manage.py new file mode 100755 index 0000000..1917e46 --- /dev/null +++ b/backend/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/backend/settings.py b/backend/settings.py new file mode 100644 index 0000000..74479b0 --- /dev/null +++ b/backend/settings.py @@ -0,0 +1,156 @@ + +# Set by django-react-jollof + +import os + +INSTALLED_APPS += [ + "corsheaders", + "rest_framework", + "allauth", + "allauth.account", + "allauth.socialaccount", +] + +AUTHENTICATION_BACKENDS = [ + "allauth.account.auth_backends.AuthenticationBackend", +] + +SITE_ID = 1 + +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_USERNAME_REQUIRED = False +ACCOUNT_AUTHENTICATION_METHOD = "email" +ACCOUNT_EMAIL_VERIFICATION = "none" + +MIDDLEWARE.insert(0, "corsheaders.middleware.CorsMiddleware") +MIDDLEWARE.append("allauth.account.middleware.AccountMiddleware") + +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": [ + "rest_framework_simplejwt.authentication.JWTAuthentication", + ], + "DEFAULT_PERMISSION_CLASSES": [ + "rest_framework.permissions.IsAuthenticated", + ], +} + +CORS_ALLOWED_ORIGINS = [ + "http://localhost:5173", # React frontend +] + +# Set by django-react-jollof + +import os + +INSTALLED_APPS += [ + "corsheaders", + "rest_framework", + "allauth", + "allauth.account", + "allauth.socialaccount", +] + +AUTHENTICATION_BACKENDS = [ + "allauth.account.auth_backends.AuthenticationBackend", +] + +SITE_ID = 1 + +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_USERNAME_REQUIRED = False +ACCOUNT_AUTHENTICATION_METHOD = "email" +ACCOUNT_EMAIL_VERIFICATION = "none" + +MIDDLEWARE.insert(0, "corsheaders.middleware.CorsMiddleware") +MIDDLEWARE.append("allauth.account.middleware.AccountMiddleware") + +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": [ + "rest_framework_simplejwt.authentication.JWTAuthentication", + ], + "DEFAULT_PERMISSION_CLASSES": [ + "rest_framework.permissions.IsAuthenticated", + ], +} + +CORS_ALLOWED_ORIGINS = [ + "http://localhost:5173", # React frontend +] + +# Set by django-react-jollof + +import os + +INSTALLED_APPS += [ + "corsheaders", + "rest_framework", + "allauth", + "allauth.account", + "allauth.socialaccount", +] + +AUTHENTICATION_BACKENDS = [ + "allauth.account.auth_backends.AuthenticationBackend", +] + +SITE_ID = 1 + +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_USERNAME_REQUIRED = False +ACCOUNT_AUTHENTICATION_METHOD = "email" +ACCOUNT_EMAIL_VERIFICATION = "none" + +MIDDLEWARE.insert(0, "corsheaders.middleware.CorsMiddleware") +MIDDLEWARE.append("allauth.account.middleware.AccountMiddleware") + +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": [ + "rest_framework_simplejwt.authentication.JWTAuthentication", + ], + "DEFAULT_PERMISSION_CLASSES": [ + "rest_framework.permissions.IsAuthenticated", + ], +} + +CORS_ALLOWED_ORIGINS = [ + "http://localhost:5173", # React frontend +] + +# Set by django-react-jollof + +import os + +INSTALLED_APPS += [ + "corsheaders", + "rest_framework", + "allauth", + "allauth.account", + "allauth.socialaccount", +] + +AUTHENTICATION_BACKENDS = [ + "allauth.account.auth_backends.AuthenticationBackend", +] + +SITE_ID = 1 + +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_USERNAME_REQUIRED = False +ACCOUNT_AUTHENTICATION_METHOD = "email" +ACCOUNT_EMAIL_VERIFICATION = "none" + +MIDDLEWARE.insert(0, "corsheaders.middleware.CorsMiddleware") +MIDDLEWARE.append("allauth.account.middleware.AccountMiddleware") + +REST_FRAMEWORK = { + "DEFAULT_AUTHENTICATION_CLASSES": [ + "rest_framework_simplejwt.authentication.JWTAuthentication", + ], + "DEFAULT_PERMISSION_CLASSES": [ + "rest_framework.permissions.IsAuthenticated", + ], +} + +CORS_ALLOWED_ORIGINS = [ + "http://localhost:5173", # React frontend +] diff --git a/django_react_jollof/backend.py b/django_react_jollof/backend.py index fce70cd..e6e658b 100644 --- a/django_react_jollof/backend.py +++ b/django_react_jollof/backend.py @@ -252,7 +252,7 @@ def scaffold_backend(template_dir: str, social_login: str) -> Optional[Dict[str, click.secho("Migrations applied successfully.", fg="green") except subprocess.CalledProcessError as e: - click.secho(f"Failed to apply migrations.\nError: {e.stderr.strip()}", fg="red") + click.secho(f"Failed to apply migrations.\nError: {e.stderr}", fg="red") sys.exit(1) try: diff --git a/django_react_jollof/tests/test_backend.py b/django_react_jollof/tests/test_backend.py new file mode 100644 index 0000000..67b3b18 --- /dev/null +++ b/django_react_jollof/tests/test_backend.py @@ -0,0 +1,166 @@ +import unittest +from unittest.mock import patch, mock_open, MagicMock, call +import subprocess +import sys +import os +import click +from django_react_jollof.backend import ( + run_subprocess_command, + modify_urls_py, + update_settings, + scaffold_backend, +) + + +class TestBackendFunctions(unittest.TestCase): + + def setUp(self): + self.test_command = ["test", "command"] + self.success_msg = "Success" + self.error_msg = "Error" + + def test_run_subprocess_command_success(self): + """Test successful subprocess command execution""" + mock_result = MagicMock() + mock_result.stdout = "Command output" + + with patch("subprocess.run", return_value=mock_result) as mock_run: + with patch("click.echo") as mock_echo: + run_subprocess_command( + self.test_command, self.success_msg, self.error_msg + ) + + mock_run.assert_called_once_with( + self.test_command, check=True, text=True, capture_output=True + ) + mock_echo.assert_has_calls( + [call(self.success_msg), call("Command output")] + ) + + def test_run_subprocess_command_failure(self): + """Test subprocess command failure""" + mock_error = subprocess.CalledProcessError(1, self.test_command) + mock_error.stderr = "Error output" + + with patch("subprocess.run", side_effect=mock_error) as mock_run: + with patch("click.echo") as mock_echo: + with patch("sys.exit") as mock_exit: + run_subprocess_command( + self.test_command, self.success_msg, self.error_msg + ) + + mock_echo.assert_called_once_with(f"{self.error_msg}: Error output") + mock_exit.assert_called_once_with(1) + + @patch("os.path.join", return_value="mocked_path/urls.py") + @patch("builtins.open", new_callable=mock_open) + def test_modify_urls_py_success(self, mock_open, mock_path_join): + """Test successful modification of urls.py""" + # Existing content in urls.py + mock_content = "Original content" + + # Expected content to be written + expected_content = [ + "from django.contrib import admin\n", + "from django.urls import path, include\n", + "\n", + "urlpatterns = [\n", + ' path("admin/", admin.site.urls),\n', + ' path("api/", include("users.urls")), # Added by django-react-jollof\n', + "]\n", + ] + + # Mock the file read to return existing content + mock_open.return_value.read.return_value = mock_content + mock_open.return_value.readlines.return_value = mock_content.splitlines() + + # Call the function + modify_urls_py("test_project") + + # Verify open was called correctly + mock_open.assert_any_call("mocked_path/urls.py", "r") # Reading the file + mock_open.assert_any_call("mocked_path/urls.py", "w") # Writing the file + + # Get the file handle for write operations + file_handle = mock_open() + + # Verify write calls + file_handle.writelines.assert_called_once_with(expected_content) + + def test_modify_urls_py_error(self): + """Test error handling in modify_urls_py""" + with patch("builtins.open", side_effect=Exception("Test error")): + with patch("click.echo") as mock_echo: + with self.assertRaises(Exception): + modify_urls_py("test_dir") + mock_echo.assert_called_with("Error modifying urls.py: Test error") + + def test_update_settings_no_social_login(self): + """Test settings update without social login""" + with patch("os.path.isfile", return_value=True): + with patch("builtins.open", mock_open()) as mock_file: + with patch("click.echo") as mock_echo: + update_settings("none") + + # Verify file was opened in append mode + mock_file.assert_called_once_with("backend/settings.py", "a") + + # Verify content written + handle = mock_file() + self.assertTrue(handle.write.called) + # Verify required content is in the writes + written_content = "".join( + call_args[0][0] for call_args in handle.write.call_args_list + ) + self.assertIn("INSTALLED_APPS", written_content) + self.assertNotIn("SOCIALACCOUNT_PROVIDERS", written_content) + + @patch("os.chdir") + @patch("subprocess.run") + @patch("click.echo") + @patch("django_react_jollof.backend.run_subprocess_command") + @patch("django_react_jollof.backend.copy_templates") + @patch("django_react_jollof.backend.get_client_secrets") + @patch("django_react_jollof.backend.modify_urls_py") + @patch("django_react_jollof.backend.update_settings") + def test_scaffold_backend_success( + self, + mock_update_settings, + mock_modify_urls, + mock_get_secrets, + mock_copy_templates, + mock_run_command, + mock_echo, + mock_subprocess_run, + mock_chdir, + ): + """Test successful backend scaffolding""" + # Setup subprocess.run mock to handle migrations + mock_subprocess_run.return_value = MagicMock(returncode=0) + mock_get_secrets.return_value = {"GOOGLE_CLIENT_ID": "test_id"} + + result = scaffold_backend("template_dir", "google") + + # Verify steps were called in correct order + mock_run_command.assert_called() + mock_chdir.assert_has_calls([call("backend"), call("..")]) + mock_modify_urls.assert_called_once() + mock_copy_templates.assert_called_once() + self.assertEqual(result, {"GOOGLE_CLIENT_ID": "test_id"}) + + @patch("os.chdir") + @patch("click.echo") + @patch("sys.exit") + def test_scaffold_backend_directory_error(self, mock_exit, mock_echo, mock_chdir): + """Test backend scaffolding with directory error""" + mock_chdir.side_effect = FileNotFoundError() + + scaffold_backend("template_dir", "none") + + mock_echo.assert_called_with( + "Template directory 'template_dir/backend' does not exist." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/requirements.txt b/requirements.txt index 3c9fb98..3502776 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,5 @@ -click>=8.0 -requests>=2.0 -python-decouple>=3.6 -djangorestframework>=3.13 -djangorestframework-simplejwt>=5.2 -django-cors-headers>=3.13 -django-allauth>=0.53 +djangorestframework +djangorestframework-simplejwt +django-cors-headers +django-allauth +python-decouple \ No newline at end of file