Restructured everything.

This commit is contained in:
2019-10-08 14:50:10 +02:00
parent 5336de4959
commit 587c2849b6
46 changed files with 102 additions and 328 deletions

View File

@@ -1,2 +0,0 @@
mkdir -p env/django
django-admin startproject main env/django

1
.buildbot/test/02-setup Normal file
View File

@@ -0,0 +1 @@
python bin/setup.py

View File

@@ -1 +0,0 @@
cat base/console_scripts/django_project_config/additional_settings.py >> env/django/main/settings.py

View File

@@ -1 +1 @@
python env/django/manage.py test
python manage.py test

6
.gitignore vendored
View File

@@ -3,9 +3,9 @@
geckodriver.log
.idea/
django_test.egg-info/
build/
dist/
manage.py
conf/
env/
tmp/
var/

View File

@@ -1,3 +0,0 @@
recursive-include base/console_scripts/django_project_config *.py
recursive-include base/static *
recursive-include base/templates *

View File

@@ -1,95 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse
import os
import pkg_resources
import sys
DJANGO_MAIN_MODULE = 'main'
VERSION = '0.1'
class AdminCommand(object):
@staticmethod
def _setup_argparser():
kwargs = {
'description': 'Tool to manage your test django installation.',
}
parser = argparse.ArgumentParser(**kwargs)
parser.add_argument('-V', '--version', action='version',
version='%(prog)s ' + VERSION)
subparsers = parser.add_subparsers(dest='subcmd', metavar='CMD',
title='subcommands',
description="Use '%(prog)s CMD -h' to show help for a subcommand")
subparser = subparsers.add_parser('setup', help='Setup the installation.')
subparser.add_argument('path', metavar='PATH',
help='A directory, where the project files will be installed.')
return parser
def _parse_args(self, argv=None):
if argv is None:
argv = sys.argv[1:]
if not argv:
argv = ['--help']
return self._argparser.parse_args(argv)
@staticmethod
def _subcmd_setup(cmd_args):
django_main_module = DJANGO_MAIN_MODULE
django_base_dir = cmd_args.path
sys.stdout.write('Setup installation in \'{path}\'...\n'.format(path=django_base_dir))
if os.path.exists(django_base_dir):
if not os.path.isdir(django_base_dir):
sys.stderr.write('{path}: Not a directory.\n'.format(path=django_base_dir))
return os.EX_USAGE
else:
os.makedirs(django_base_dir)
sys.stdout.write('Creating django project...\n')
django_cmd = 'django-admin startproject {name} "{path}"'.format(name=django_main_module,
path=django_base_dir)
exitval = os.system(django_cmd)
if exitval != os.EX_OK:
return exitval
sys.stdout.write('Configure django project...\n')
input_file = os.path.join('django_project_config', 'additional_settings.py')
output_file = os.path.join(django_base_dir, django_main_module, 'settings.py')
with open(output_file, 'ab') as f:
f.write(pkg_resources.resource_string(__package__, input_file))
sys.stdout.write('Creating directories...\n')
dirs = [
os.path.join(django_base_dir, 'var', 'log'),
os.path.join(django_base_dir, 'var', 'www', 'static'),
]
for d in dirs:
sys.stdout.write(' - %s\n' % d)
os.makedirs(d)
return os.EX_OK
def __init__(self):
self._argparser = self._setup_argparser()
def __call__(self, argv=None):
cmd_args = self._parse_args(argv)
subcmd = cmd_args.subcmd
method_name = '_subcmd_{}'.format(subcmd)
method = getattr(self, method_name)
exitval = method(cmd_args)
return exitval
def main():
cmd = AdminCommand()
exitval = cmd()
sys.exit(exitval)

View File

@@ -1,31 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import shutil
from django.test import SimpleTestCase
from ..console_scripts.admin import DJANGO_MAIN_MODULE, AdminCommand
from .utils import mkdtemp
class AdminTestCase(SimpleTestCase):
def setUp(self):
super(AdminTestCase, self).setUp()
self.tmp_dir = mkdtemp(prefix='AdminTestCase')
def tearDown(self):
super(AdminTestCase, self).tearDown()
if os.path.isdir(self.tmp_dir):
shutil.rmtree(self.tmp_dir)
def test_setup(self):
path = self.tmp_dir
cmd = AdminCommand()
argv = ['setup', path]
exitval = cmd(argv)
self.assertEqual(exitval, os.EX_OK)
self.assertTrue(os.path.isfile(os.path.join(path, 'manage.py')))
self.assertTrue(os.path.isfile(os.path.join(path, DJANGO_MAIN_MODULE, 'settings.py')))
self.assertTrue(os.path.isdir(os.path.join(path, 'var', 'log')))
self.assertTrue(os.path.isdir(os.path.join(path, 'var', 'www', 'static')))

90
bin/setup.py Executable file
View File

@@ -0,0 +1,90 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse
import os
import shutil
import sys
class Command(object):
settings_module_name = 'main'
@staticmethod
def _setup_argparser():
kwargs = {
'description': 'Setup and configure the django project.',
}
parser = argparse.ArgumentParser(**kwargs)
parser.add_argument('--force',
action='store_true', dest='force',
help='Overwrite existing django settings')
return parser
def _parse_args(self, argv=None):
if argv is None:
argv = sys.argv[1:]
return self._argparser.parse_args(argv)
def _run(self, force=False):
settings_module_name = self.settings_module_name
settings_file = os.path.join(settings_module_name, 'settings.py')
if os.path.exists(settings_file):
if not force:
sys.stderr.write('Django settings file detected. Abort!\n')
return os.EX_NOPERM
if os.path.exists('manage.py') or \
os.path.exists(settings_module_name):
sys.stdout.write('Replacing django files...\n')
if os.path.exists('manage.py'):
os.unlink('manage.py')
if os.path.exists(settings_module_name):
shutil.rmtree(settings_module_name)
else:
sys.stdout.write('Installing django files...\n')
cmd = 'django-admin startproject {name} .'.format(name=settings_module_name)
exitval = os.system(cmd)
if exitval != os.EX_OK:
return exitval
sys.stdout.write('Configure django...\n')
add_settings_file = os.path.join('etc', 'django', 'additional_settings.py')
with open(settings_file, 'a') as f_out:
with open(add_settings_file) as f_in:
f_out.write(f_in.read())
sys.stdout.write('Creating directories...\n')
dirs = [
os.path.join('var', 'db'),
os.path.join('var', 'log'),
os.path.join('var', 'www', 'static'),
]
for d in dirs:
sys.stdout.write(' - %s\n' % d)
if not os.path.exists(d):
os.makedirs(d)
return os.EX_OK
def __init__(self):
self._argparser = self._setup_argparser()
def __call__(self, argv=None):
cmd_args = self._parse_args(argv)
exitval = self._run(cmd_args.force)
return exitval
def main():
cmd = Command()
exitval = cmd()
sys.exit(exitval)
if __name__ == '__main__':
main()

View File

@@ -9,10 +9,15 @@ LOG_DIR = os.path.join(BASE_VAR_DIR, 'log')
INSTALLED_APPS += [
'django_extensions',
# Our main app
'base',
'apps.base',
]
ROOT_URLCONF = 'base.urls'
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_VAR_DIR, 'db', 'devel.sqlite3'),
}
ROOT_URLCONF = 'apps.base.urls'
STATIC_ROOT = os.path.join(BASE_VAR_DIR, 'www', 'static')
LOGGING = {

117
setup.py
View File

@@ -1,117 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import sys
from setuptools import setup, find_packages
from setuptools import Command
class MyCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
class SetupPythonEnvironment(MyCommand):
description = 'create a (virtual) python environment'
@staticmethod
def run():
python_bin = sys.executable if sys.executable else 'python'
python_ver = sys.version_info.major
if python_ver == 2:
path = os.path.join('env', 'python2')
symlink_path = os.path.join('env', 'python')
venv_module = 'virtualenv'
prompt = '(py2-django) '
elif python_ver == 3:
path = os.path.join('env', 'python3')
symlink_path = os.path.join('env', 'python')
venv_module = 'venv'
prompt = 'py3-django'
else:
sys.stderr.write('Python {} is not supported.\n'.format(python_ver))
sys.exit(os.EX_USAGE)
sys.stdout.write('Creating new python environment in {path}\n'.format(path=path))
cmd = ('{bin} -m {venv_module}'
' --prompt="{prompt}"'
' {path}'.format(bin=python_bin, path=path,
venv_module=venv_module, prompt=prompt))
os.system(cmd)
if symlink_path and not os.path.exists(symlink_path):
symlink_dir = os.path.dirname(symlink_path)
relpath = os.path.relpath(path, symlink_dir)
os.symlink(relpath, symlink_path)
print('')
print('Depending on your operating system or command shell,')
print('you should activate the new environment for this shell session')
print('by running ONE of the following commands:')
print('- Windows: %s' % os.path.join(path, 'Scripts', 'activate'))
print('- C Shell: source %s/bin/activate.csh' % path)
print('- All others: source %s/bin/activate' % path)
class SetupDjangoEnvironment(MyCommand):
description = 'create a typical installation for developing'
@staticmethod
def run():
# python_bin = sys.executable if sys.executable else 'python'
django_project_path = 'env/django'
# mgmt_script = os.path.join(django_project_path, 'manage.py')
sys.stdout.write('Install distribution in development mode...\n')
cmd = 'pip install -e .'
os.system(cmd)
sys.stdout.write('Setup django project in {}...\n'.format(django_project_path))
cmd = 'django-test-admin setup {}'.format(django_project_path)
os.system(cmd)
# sys.stdout.write('Make database migrations...\n')
# cmd = '{bin} {mgmt} makemigrations'.format(bin=python_bin, mgmt=mgmt_script)
# os.system(cmd)
# sys.stdout.write('Create database...\n')
# cmd = '{bin} {mgmt} migrate'.format(bin=python_bin, mgmt=mgmt_script)
# os.system(cmd)
# sys.stdout.write('Create superuser \'root\'...\n')
# cmd = ('{bin} {mgmt} createsuperuser'
# ' --username root').format(bin=python_bin, mgmt=mgmt_script)
# os.system(cmd)
setup(
name='django-test',
version='1.0',
description='An example django based web application.',
url='https://heinzelwelt.de',
maintainer='Jens Kleineheismann',
maintainer_email='heinzel@heinzelwelt.de',
cmdclass={
'mkpyenv': SetupPythonEnvironment,
'mkdjangoenv': SetupDjangoEnvironment,
},
packages=find_packages(exclude=['tests']),
include_package_data=True,
test_suite='tests.test_suite',
entry_points={
'console_scripts': [
'django-test-admin = base.console_scripts.admin:main',
],
},
install_requires=[
'coverage',
'django',
'django-extensions',
],
)

View File

@@ -1,2 +0,0 @@
from .test_suite import TestSuite
test_suite = TestSuite()

View File

@@ -1,71 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import django
import os
import shutil
import sys
from django.test.utils import get_runner
from base.console_scripts.admin import DJANGO_MAIN_MODULE
from base.tests.utils import mkdtemp
class DjangoEnvironment(object):
@staticmethod
def _install_djangoproject(path):
cmd = 'django-test-admin setup "{}"'.format(path)
os.system(cmd)
def __init__(self, path=None, remove_after=True):
self.path = path
self._remove_after = remove_after
self._original_sys_path = None
self._modified_sys_path = None
def __enter__(self):
if self.path is None:
prefix = 'testrun-{datetime}-'.format(
datetime=datetime.datetime.now().strftime('%Y%m%d-%H%M')
)
self.path = mkdtemp(prefix=prefix)
self._install_djangoproject(self.path)
self._original_sys_path = sys.path
sys.path.append(self.path)
self._modified_sys_path = sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = '{}.settings'.format(DJANGO_MAIN_MODULE)
django.setup()
from django.conf import settings
self.settings = settings
return self
def __exit__(self, *args):
if self._modified_sys_path is not None and self._original_sys_path is not None:
if sys.path == self._modified_sys_path:
sys.path = self._original_sys_path
if self._remove_after:
shutil.rmtree(self.path)
class TestSuite(object):
@staticmethod
def run():
tests = ['base']
test_tags = None
exclude_test_tags = None
with DjangoEnvironment() as env:
test_runner_class = get_runner(env.settings)
test_runner = test_runner_class(tags=test_tags, exclude_tags=exclude_test_tags)
failures = test_runner.run_tests(tests)
return bool(failures)
def __call__(self):
sys.exit(self.run())