Added logic to create new unittest project

This commit is contained in:
Sven Heidemann 2022-05-26 13:12:35 +02:00
parent 0675105731
commit c1a1849ad2
15 changed files with 555 additions and 24 deletions

View File

@ -6,22 +6,19 @@
"cpl-cli": "src/cpl_cli/cpl-cli.json",
"cpl-query": "src/cpl_query/cpl-query.json",
"set-version": "tools/set_version/set-version.json",
"set-pip-urls": "tools/set_pip_urls/set-pip-urls.json"
"set-pip-urls": "tools/set_pip_urls/set-pip-urls.json",
"unittests": "src/unittests/unittests.json"
},
"Scripts": {
"hello-world": "echo 'Hello World'",
"sv": "cpl set-version",
"set-version": "cpl run set-version $ARGS; echo '';",
"spu": "cpl set-pip-urls",
"set-pip-urls": "cpl run set-pip-urls $ARGS; echo '';",
"docs-build": "echo 'Build Documentation'; cd docs/; sphinx-apidoc -o source/ ../src/cpl_core; sphinx-apidoc -o source/ ../src/cpl_query; make clean; make html; rm source/cpl_query.tests.rst;",
"db": "cpl build-docs",
"docs-open": "xdg-open $PWD/docs/build/html/index.html &",
"do": "cpl docs-open",
"pre-build-all": "cpl sv $ARGS; cpl spu $ARGS;",
"build-all": "cpl build-cli; cpl build-core; cpl build-query; cpl build-set-pip-urls; cpl build-set-version",
"ba": "cpl build-all $ARGS",
@ -30,14 +27,12 @@
"build-query": "echo 'Build cpl-query'; cd ./src/cpl_query; cpl build; cd ../../;",
"build-set-pip-urls": "echo 'Build set-pip-urls'; cd ./tools/set_pip_urls; cpl build; cd ../../;",
"build-set-version": "echo 'Build set-version'; cd ./tools/set_version; cpl build; cd ../../;",
"pre-publish-all": "cpl sv $ARGS; cpl spu $ARGS;",
"publish-all": "cpl publish-cli; cpl publish-core; cpl publish-query;",
"pa": "cpl build-all $ARGS",
"publish-cli": "echo 'Publish cpl-cli'; cd ./src/cpl_cli; cpl publish; cd ../../;",
"publish-core": "echo 'Publish cpl-core'; cd ./src/cpl_core; cpl publish; cd ../../;",
"publish-query": "echo 'Publish cpl_query'; cd ./src/cpl_query; cpl publish; cd ../../;",
"upload-prod-cli": "echo 'PROD Upload cpl-cli'; cpl upl-prod-cli;",
"upl-prod-cli": "twine upload -r pip.sh-edraft.de dist/cpl-cli/publish/setup/*",
"upload-prod-core": "echo 'PROD Upload cpl-core'; cpl upl-prod-core;",
@ -56,21 +51,18 @@
"upl-dev-core": "twine upload -r pip-dev.sh-edraft.de dist/cpl-core/publish/setup/*",
"upload-dev-query": "echo 'DEV Upload cpl_query'; cpl upl-dev-query;",
"upl-dev-query": "twine upload -r pip-dev.sh-edraft.de dist/cpl-query/publish/setup/*",
"pre-deploy-prod": "cpl sv $ARGS; cpl spu --environment=production;",
"deploy-prod": "cpl deploy-prod-cli; cpl deploy-prod-core; cpl deploy-prod-query;",
"dp": "cpl deploy-prod $ARGS",
"deploy-prod-cli": "cpl publish-cli; cpl upload-prod-cli",
"deploy-prod-core": "cpl publish-core; cpl upload-prod-core",
"deploy-prod-query": "cpl publish-query; cpl upload-prod-query",
"pre-deploy-exp": "cpl sv $ARGS; cpl spu --environment=staging;",
"deploy-exp": "cpl deploy-exp-cli; cpl deploy-exp-core; cpl deploy-exp-query;",
"de": "cpl deploy-exp $ARGS",
"deploy-exp-cli": "cpl publish-cli; cpl upload-exp-cli",
"deploy-exp-core": "cpl publish-core; cpl upload-exp-core",
"deploy-exp-query": "cpl publish-query; cpl upload-exp-query",
"pre-deploy-dev": "cpl sv $ARGS; cpl spu --environment=development;",
"deploy-dev": "cpl deploy-dev-cli; cpl deploy-dev-core; cpl deploy-dev-query;",
"dd": "cpl deploy-dev $ARGS",

View File

@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
"""
cpl-cli sh-edraft Common Python library CLI
~~~~~~~~~~~~~~~~~~~
sh-edraft Common Python library Command Line Interface
:copyright: (c) 2020 - 2022 sh-edraft.de
:license: MIT, see LICENSE for more details.
"""
__title__ = 'cpl_cli._templates.new.console'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2022 sh-edraft.de'
__version__ = '2022.6.16.dev2'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2022', minor='6', micro='16.dev2')

View File

@ -0,0 +1,23 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class LicenseTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'LICENSE'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -0,0 +1,23 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ReadmeTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'README.md'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
"""
cpl-cli sh-edraft Common Python library CLI
~~~~~~~~~~~~~~~~~~~
sh-edraft Common Python library Command Line Interface
:copyright: (c) 2020 - 2022 sh-edraft.de
:license: MIT, see LICENSE for more details.
"""
__title__ = 'cpl_cli._templates.new.console.source'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2022 sh-edraft.de'
__version__ = '2022.6.16.dev2'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2022', minor='6', micro='16.dev2')

View File

@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
"""
cpl-cli sh-edraft Common Python library CLI
~~~~~~~~~~~~~~~~~~~
sh-edraft Common Python library Command Line Interface
:copyright: (c) 2020 - 2022 sh-edraft.de
:license: MIT, see LICENSE for more details.
"""
__title__ = 'cpl_cli._templates.new.console.source.name'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2022 sh-edraft.de'
__version__ = '2022.6.16.dev2'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2022', minor='6', micro='16.dev2')

View File

@ -0,0 +1,74 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ApplicationTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'application.py'
self._path = path
self._use_async = use_async
if self._use_async:
self._value = textwrap.dedent("""\
import unittest
from unittest import TestSuite
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from unittests.test_case import TestCase
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
self._suite: TestSuite = unittest.TestSuite()
async def configure(self):
self._suite.addTest(TestCase('test_equal'))
async def main(self):
runner = unittest.TextTestRunner()
runner.run(self._suite)
""")
else:
self._value = textwrap.dedent("""\
import unittest
from unittest import TestSuite
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from unittests.test_case import TestCase
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
self._suite: TestSuite = unittest.TestSuite()
def configure(self):
self._suite.addTest(TestCase('test_equal'))
def main(self):
runner = unittest.TextTestRunner()
runner.run(self._suite)
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -0,0 +1,27 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainInitTemplate(TemplateFileABC):
def __init__(self, name: str, path: str):
TemplateFileABC.__init__(self)
self._name = '__init__.py'
self._path = path
self._value = textwrap.dedent("""\
# imports:
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -0,0 +1,63 @@
import textwrap
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainWithApplicationBaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
name = String.convert_to_snake_case(name)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if use_async:
self._value = textwrap.dedent(f"""\
import asyncio
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
async def main():
app_builder = ApplicationBuilder(Application)
app: Application = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
ml = asyncio.get_event_loop()
ml.run_until_complete(main())
""")
else:
self._value = textwrap.dedent(f"""\
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
def main():
app_builder = ApplicationBuilder(Application)
app_builder.build().run()
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -0,0 +1,52 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class TestCaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'test_case.py'
self._path = path
self._use_async = use_async
if self._use_async:
self._value = textwrap.dedent("""\
import unittest
class TestCase(unittest.TestCase):
async def setUp(self) -> None:
pass
async def test_equal(self):
self.assertEqual(True, True)
""")
else:
self._value = textwrap.dedent("""\
import unittest
class TestCase(unittest.TestCase):
def setUp(self) -> None:
pass
def test_equal(self):
self.assertEqual(True, True)
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -29,6 +29,7 @@ class CLI(ApplicationABC):
try:
result = self._configuration.parse_console_arguments(self._services)
if result:
Console.write_line()
return
if len(self._configuration.additional_arguments) == 0:
@ -37,6 +38,7 @@ class CLI(ApplicationABC):
unexpected_arguments = ', '.join(self._configuration.additional_arguments)
Error.error(f'Unexpected argument(s): {unexpected_arguments}')
Console.write_line()
except KeyboardInterrupt:
Console.write_line()
sys.exit()

View File

@ -6,6 +6,7 @@ from typing import Optional
from packaging import version
import cpl_core
from cpl_cli.source_creator.unittest_builder import UnittestBuilder
from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
@ -163,11 +164,12 @@ class NewService(CommandABC):
return project_path
def _get_project_information(self):
def _get_project_information(self, is_unittest=False):
"""
Gets project information's from user
:return:
"""
if not is_unittest:
result = Console.read('Do you want to use application base? (y/n) ')
if result.lower() == 'y':
self._use_application_api = True
@ -214,6 +216,32 @@ class NewService(CommandABC):
except Exception as e:
Console.error('Could not create project', str(e))
def _unittest(self, args: list[str]):
"""
Generates new unittest project
:param args:
:return:
"""
self._create_project_settings(self._name)
self._create_build_settings()
self._create_project_json()
path = self._get_project_path()
if path is None:
return
self._get_project_information(is_unittest=True)
try:
UnittestBuilder.build(
path,
self._use_application_api,
self._use_async,
self._project.name,
self._project_json,
self._workspace
)
except Exception as e:
Console.error('Could not create project', str(e))
def _library(self, args: list[str]):
"""
Generates new library project
@ -250,16 +278,22 @@ class NewService(CommandABC):
"""
console = self._config.get_configuration(ProjectTypeEnum.console.value)
library = self._config.get_configuration(ProjectTypeEnum.library.value)
if console is not None and library is None:
unittest = self._config.get_configuration(ProjectTypeEnum.unittest.value)
if console is not None and library is None and unittest is None:
self._name = console
self._schematic = ProjectTypeEnum.console.value
self._console(args)
elif console is None and library is not None:
elif console is None and library is not None and unittest is None:
self._name = library
self._schematic = ProjectTypeEnum.library.value
self._library(args)
elif console is None and library is None and unittest is not None:
self._name = unittest
self._schematic = ProjectTypeEnum.unittest.value
self._unittest(args)
else:
self._help('Usage: cpl new <schematic> [options]')
return

View File

@ -5,3 +5,4 @@ class ProjectTypeEnum(Enum):
console = 'console'
library = 'library'
unittest = 'unittest'

View File

@ -0,0 +1,164 @@
import json
import os
from typing import Optional
from cpl_cli._templates.new.unittest.license import LicenseTemplate
from cpl_cli._templates.new.unittest.readme_py import ReadmeTemplate
from cpl_cli._templates.new.unittest.source.name.application import ApplicationTemplate
from cpl_cli._templates.new.unittest.source.name.init import MainInitTemplate
from cpl_cli._templates.new.unittest.source.name.main import MainWithApplicationBaseTemplate
from cpl_cli._templates.new.unittest.source.name.test_case import TestCaseTemplate
from cpl_cli._templates.template_file_abc import TemplateFileABC
from cpl_cli.configuration.workspace_settings import WorkspaceSettings
from cpl_cli.configuration.workspace_settings_name_enum import WorkspaceSettingsNameEnum
from cpl_cli.source_creator.template_builder import TemplateBuilder
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.utils.string import String
class UnittestBuilder:
def __init__(self):
pass
@staticmethod
def _create_file(file_name: str, content: dict):
if not os.path.isabs(file_name):
file_name = os.path.abspath(file_name)
path = os.path.dirname(file_name)
if not os.path.isdir(path):
os.makedirs(path)
with open(file_name, 'w') as project_json:
project_json.write(json.dumps(content, indent=2))
project_json.close()
@classmethod
def _create_workspace(cls, path: str, project_name, projects: dict, scripts: dict):
ws_dict = {
WorkspaceSettings.__name__: {
WorkspaceSettingsNameEnum.default_project.value: project_name,
WorkspaceSettingsNameEnum.projects.value: projects,
WorkspaceSettingsNameEnum.scripts.value: scripts
}
}
Console.spinner(
f'Creating {path}',
cls._create_file,
path,
ws_dict,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
@classmethod
def build(cls, project_path: str, use_application_api: bool,
use_async: bool, project_name: str, project_settings: dict, workspace: Optional[WorkspaceSettings]):
"""
Builds the console project files
:param project_path:
:param use_application_api:
:param use_async:
:param project_name:
:param project_settings:
:param workspace:
:return:
"""
pj_name = project_name
if '/' in pj_name:
pj_name = pj_name.split('/')[len(pj_name.split('/')) - 1]
project_name_snake = String.convert_to_snake_case(pj_name)
if workspace is None:
templates: list[TemplateFileABC] = [
LicenseTemplate(),
ReadmeTemplate(),
MainInitTemplate(project_name, os.path.join('src/', project_name_snake))
]
else:
project_path = os.path.join(
os.path.dirname(project_path),
project_name_snake
)
templates: list[TemplateFileABC] = [
MainInitTemplate('', '')
]
if not os.path.isdir(project_path):
os.makedirs(project_path)
py_src_rel_path = ''
src_name = project_name_snake
if workspace is None:
py_src_rel_path = f'src/{src_name}'
templates.append(ApplicationTemplate(src_name, py_src_rel_path, use_async))
templates.append(MainWithApplicationBaseTemplate(src_name, py_src_rel_path, use_async))
templates.append(TestCaseTemplate(src_name, py_src_rel_path, use_async))
src_rel_path = ''
if '/' in project_name:
old_pj_name = project_name
parts = project_name.split('/')
project_name = parts[len(parts) - 1]
src_rel_path = old_pj_name.split(project_name)[0]
proj_name = project_name
if src_rel_path.endswith('/'):
src_rel_path = src_rel_path[:len(src_rel_path) - 1]
if src_rel_path != '':
proj_name = f'{src_rel_path}/{project_name}'
if workspace is not None:
proj_name = project_name_snake
if src_rel_path != '':
project_file_path = f'{src_rel_path}/{project_name_snake}/{project_name}.json'
else:
project_file_path = f'{project_name_snake}/{project_name}.json'
if workspace is None:
src_path = f'src/{project_name_snake}'
workspace_file_path = f'{proj_name}/cpl-workspace.json'
project_file_rel_path = f'{src_path}/{project_name}.json'
project_file_path = f'{proj_name}/{src_path}/{project_name}.json'
cls._create_workspace(
workspace_file_path,
project_name,
{
project_name: project_file_rel_path
},
{}
)
else:
workspace.projects[project_name] = f'src/{project_file_path}'
cls._create_workspace('cpl-workspace.json', workspace.default_project, workspace.projects, workspace.scripts)
Console.spinner(
f'Creating {project_file_path}',
cls._create_file,
project_file_path if workspace is None else f'src/{project_file_path}',
project_settings,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
for template in templates:
divider = ''
if template.path != '' and not template.path.endswith('/'):
divider = '/'
Console.spinner(
f'Creating {proj_name}/{template.path}{divider}{template.name}',
TemplateBuilder.build,
project_path,
template,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)

View File

@ -84,7 +84,8 @@ class StartupArgumentExtension(StartupExtensionABC):
.add_console_argument(ArgumentTypeEnum.Flag, '--', 'simulate', ['s', 'S'])
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'new', ['n', 'N'], NewService, True) \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'console', ['c', 'C'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'library', ['l', 'L'], ' ')
.add_console_argument(ArgumentTypeEnum.Variable, '', 'library', ['l', 'L'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'unittest', ['ut', 'UT'], ' ')
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'publish', ['p', 'P'], PublishService, True, validators=[ProjectValidator])
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'remove', ['r', 'R'], RemoveService, True, validators=[WorkspaceValidator]) \
.add_console_argument(ArgumentTypeEnum.Flag, '--', 'simulate', ['s', 'S'])