Added the simple RunTestCase test case.

This commit is contained in:
依瑪貓 2022-12-05 17:32:41 +08:00
parent d83a72bb8c
commit 8c3d6fd962
9 changed files with 365 additions and 0 deletions

View File

@ -16,3 +16,5 @@
# limitations under the License. # limitations under the License.
include tests/* include tests/*
include tests/test_site/*
include tests/test_site/*/*

130
tests/test_run.py Normal file
View File

@ -0,0 +1,130 @@
# The accounting application of the Mia project.
# by imacat <imacat@mail.imacat.idv.tw>, 2022/12/5
# Copyright (c) 2022 imacat.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The tests to run the accounting application.
"""
import os
import sys
import unittest
from datetime import datetime
from pathlib import Path
from secrets import token_urlsafe
from django.core.management import call_command
from django.core.wsgi import get_wsgi_application
from django.test import Client
class RunTestCase(unittest.TestCase):
"""The test case to run the accounting application."""
def setUp(self):
"""Sets up the test.
Returns:
None.
"""
test_site_path: str = str(Path(__file__).parent / "test_site")
if test_site_path not in sys.path:
sys.path.append(test_site_path)
self.username: str = "admin"
self.password: str = token_urlsafe(16)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_site.settings")
get_wsgi_application()
call_command("migrate")
os.getlogin()
call_command("createsuperuser", interactive=False,
username=self.username, email="test@example.com")
from django.contrib.auth.models import User
user = User.objects.get(username=self.username)
user.set_password(self.password)
user.save()
call_command("accounting_accounts")
call_command("accounting_sample")
self.client = Client()
def test_run(self):
"""Tests the accounting application.
Returns:
None.
"""
response = self.client.get("/accounting/", follow=True)
self.assertEqual(response.status_code, 404)
response = self.client.post("/admin/login/",
{"username": self.username,
"password": self.password,
"next": "/ok"})
# 200 for errors, 302 for success.
self.assertEqual(response.status_code, 302)
response = self.client.get("/accounting/", follow=True)
self.assertEqual(response.status_code, 200)
response = self.client.get("/accounting/", follow=True)
self.assertEqual(response.status_code, 200)
today: str = datetime.today().strftime("%Y-%m-%d")
response = self.client.post(
"/accounting/transactions/expense/create?r=/ok",
{"date": today,
"debit-2-ord": 6,
"debit-2-summary": "lunch",
"debit-2-amount": 80,
"debit-2-account": "6272",
"debit-8-ord": 4,
"debit-8-summary": "movies",
"debit-8-amount": 320,
"debit-8-account": "6273",
"notes": "yammy"})
self.assertEqual(response.status_code, 302)
response = self.client.post(
"/accounting/transactions/income/create?r=/ok",
{"date": today,
"credit-3-ord": 7,
"credit-3-summary": "withdrawal",
"credit-3-amount": 1000,
"credit-3-account": "1113",
"credit-6-ord": 3,
"credit-6-summary": "payroll",
"credit-6-amount": 10000,
"credit-6-account": "4611",
"notes": "wonderful"})
self.assertEqual(response.status_code, 302)
response = self.client.post(
"/accounting/transactions/transfer/create?r=/ok",
{"date": today,
"debit-2-ord": 6,
"debit-2-summary": "lunch",
"debit-2-amount": 80,
"debit-2-account": "6272",
"debit-8-ord": 4,
"debit-8-summary": "movies",
"debit-8-amount": 320,
"debit-8-account": "6273",
"credit-3-ord": 7,
"credit-3-summary": "withdrawal",
"credit-3-amount": 100,
"credit-3-account": "1113",
"credit-6-ord": 3,
"credit-6-summary": "",
"credit-6-amount": 300,
"credit-6-account": "1111",
"notes": "nothing"})
self.assertEqual(response.status_code, 302)

22
tests/test_site/manage.py Executable file
View File

@ -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', 'test_site.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()

View File

@ -0,0 +1,25 @@
{% load i18n %}
{% load static %}
{% load mia_core %}
{% init_libs %}
{% block settings %}{% endblock %}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" lang="{% get_current_language as language %}{{ language }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% for css in libs.css %}
<link rel="stylesheet" type="text/css" href="{% if css|is_static_url %}{% static css %}{% else %}{{ css }}{% endif %}" />
{% endfor %}
{% for js in libs.js %}
<script src="{% if js|is_static_url %}{% static js %}{% else %}{{ js }}{% endif %}"></script>
{% endfor %}
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
{% block content %}{% endblock %}
</body>

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for test_site 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/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_site.settings')
application = get_asgi_application()

View File

@ -0,0 +1,127 @@
"""
Django settings for test_site project.
Generated by 'django-admin startproject' using Django 3.2.16.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-vc+(5e-2xn%bc29&k#ah_vf17-)usz4af4y)njbp_k09)uev$$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["testserver"]
# Application definition
INSTALLED_APPS = [
'mia_core.apps.MiaCoreConfig',
'accounting.apps.AccountingConfig',
'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 = 'test_site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [(os.path.join(BASE_DIR, 'templates'))],
'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 = 'test_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View File

@ -0,0 +1,27 @@
"""test_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/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 decorator_include import decorator_include
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.urls import include, path
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('accounting/', decorator_include(login_required, 'accounting.urls')),
path('admin/', admin.site.urls),
path('i18n/', include("django.conf.urls.i18n")),
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for test_site 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/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_site.settings')
application = get_wsgi_application()