From d38ba89bd44b61c7cfc9edbea75b9962d72d0e95 Mon Sep 17 00:00:00 2001 From: Erik Sternerson Date: Thu, 16 Jun 2022 13:11:45 +0200 Subject: [PATCH 01/34] Add precommit --- .pre-commit-config.yaml | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..0453c61 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,46 @@ +--- +repos: + + - repo: meta + hooks: + - id: check-hooks-apply + - id: check-useless-excludes + + - repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + args: + - --line-length=100 + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.4.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + + - repo: https://github.com/pycqa/isort + rev: 5.9.3 + hooks: + - id: isort + files: ".*" + args: [--profile=black, --project=cdevents] + + - repo: https://github.com/adrienverge/yamllint.git + rev: v1.26.0 + hooks: + - id: yamllint + exclude: "tests|benchmarks" + + - repo: https://github.com/pycqa/pydocstyle + rev: 5.1.1 + hooks: + - id: pydocstyle + args: [--convention=google] + exclude: "docs|tests" + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v0.812 + hooks: + - id: mypy + files: ".*/cdevents/.*" From f45a4f8965df3c1a682c0a394b7203224ab22034 Mon Sep 17 00:00:00 2001 From: Erik Sternerson Date: Thu, 16 Jun 2022 13:21:03 +0200 Subject: [PATCH 02/34] Add skeleton project --- .github/ISSUE_TEMPLATE.md | 16 +++++++++ .github/pull_request_template.md | 10 ++++++ .github/workflows/main.yml | 34 ++++++++++++++++++ .github/workflows/pypi-release.yml | 28 +++++++++++++++ .pre-commit-config.yaml | 11 ++---- README.md | 1 + cdevents/__init__.py | 3 ++ pypi_packaging.py | 57 ++++++++++++++++++++++++++++++ requirements/docs.txt | 1 + requirements/publish.txt | 2 ++ requirements/test.txt | 7 ++++ setup.py | 49 +++++++++++++++++++++++++ 12 files changed, 210 insertions(+), 9 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/main.yml create mode 100644 .github/workflows/pypi-release.yml create mode 100644 cdevents/__init__.py create mode 100644 pypi_packaging.py create mode 100644 requirements/docs.txt create mode 100644 requirements/publish.txt create mode 100644 requirements/test.txt create mode 100644 setup.py diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..39e7196 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,16 @@ +## Expected Behavior + + +## Actual Behavior + + +## Steps to Reproduce the Problem + +1. +2. +3. + +## Specifications + +- Platform: +- Python Version: diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..75a0e8f --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ +Fixes # + +## Changes + + +## One line description for the changelog + + +- [ ] Tests pass +- [ ] Appropriate changes to README are included in PR diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..c158df2 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,34 @@ +name: CI + +on: [push, pull_request] + +jobs: + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v1 + with: + python-version: '3.10' + - name: Install tox + run: python -m pip install tox + - name: Run linting + run: python -m tox -e lint + + test: + runs-on: ubuntu-latest + strategy: + matrix: + python: ['3.6', '3.7', '3.8', '3.9', '3.10'] + steps: + - uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python }} + - name: Install tox + run: python -m pip install tox + - name: Run tests + run: python -m tox -e py # Run tox using the version of Python in `PATH` diff --git a/.github/workflows/pypi-release.yml b/.github/workflows/pypi-release.yml new file mode 100644 index 0000000..8ebf355 --- /dev/null +++ b/.github/workflows/pypi-release.yml @@ -0,0 +1,28 @@ +name: PyPI-Release + +on: + push: + branches: + - master + +jobs: + build-and-publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: "3.x" + - name: Install build dependencies + run: pip install -U setuptools wheel build + - name: Build + run: python -m build . + - name: Publish + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.pypi_password }} + - name: Install GitPython and cdevents for pypi_packaging + run: pip install -U -r requirements/publish.txt + - name: Create Tag + run: python pypi_packaging.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0453c61..933eba0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,23 +24,16 @@ repos: hooks: - id: isort files: ".*" - args: [--profile=black, --project=cdevents] - - - repo: https://github.com/adrienverge/yamllint.git - rev: v1.26.0 - hooks: - - id: yamllint - exclude: "tests|benchmarks" + args: [--profile=black, --project=cdevent] - repo: https://github.com/pycqa/pydocstyle rev: 5.1.1 hooks: - id: pydocstyle args: [--convention=google] - exclude: "docs|tests" - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.812 hooks: - id: mypy - files: ".*/cdevents/.*" + files: "cdevents/.*" diff --git a/README.md b/README.md index 65f4727..e8d36c8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # sdk-python + Python SDK for CDEvents diff --git a/cdevents/__init__.py b/cdevents/__init__.py new file mode 100644 index 0000000..f7b521c --- /dev/null +++ b/cdevents/__init__.py @@ -0,0 +1,3 @@ +"""CDEvents Python SDK.""" + +__version__ = "0.0.1" diff --git a/pypi_packaging.py b/pypi_packaging.py new file mode 100644 index 0000000..71dd7d4 --- /dev/null +++ b/pypi_packaging.py @@ -0,0 +1,57 @@ +"""Packaging and release utilities.""" + +import codecs +import os + +import pkg_resources + + +def _read(rel_path): + here = os.path.abspath(os.path.dirname(__file__)) + with codecs.open(os.path.join(here, rel_path), "r") as fp: + return fp.read() + + +def _get_version(rel_path): + for line in _read(rel_path).splitlines(): + if line.startswith("__version__"): + delim = '"' if '"' in line else "'" + return line.split(delim)[1] + else: + raise RuntimeError("Unable to find version string.") + + +# FORMAT: 1.x.x +pypi_config = { + "version_target": _get_version("cdevents/__init__.py"), + "package_name": "cdevents", +} + + +def _createTag(): + from git import Repo + + # Get local pypi cloudevents version + published_pypi_version = pkg_resources.get_distribution(pypi_config["package_name"]).version + + # Ensure pypi and local package versions match + if pypi_config["version_target"] == published_pypi_version: + # Create local git tag + repo = Repo(os.getcwd()) + repo.create_tag(pypi_config["version_target"]) + + # Push git tag to remote master + origin = repo.remote() + origin.push(pypi_config["version_target"]) + + else: + # PyPI publish likely failed + print( + f"Expected {pypi_config['package_name']}=={pypi_config['version_target']} " + f"but found {pypi_config['package_name']}=={published_pypi_version}" + ) + exit(1) + + +if __name__ == "__main__": + _createTag() diff --git a/requirements/docs.txt b/requirements/docs.txt new file mode 100644 index 0000000..2806c16 --- /dev/null +++ b/requirements/docs.txt @@ -0,0 +1 @@ +Sphinx diff --git a/requirements/publish.txt b/requirements/publish.txt new file mode 100644 index 0000000..103a961 --- /dev/null +++ b/requirements/publish.txt @@ -0,0 +1,2 @@ +GitPython +cdevents diff --git a/requirements/test.txt b/requirements/test.txt new file mode 100644 index 0000000..9178c0c --- /dev/null +++ b/requirements/test.txt @@ -0,0 +1,7 @@ +flake8 +pep8-naming +flake8-import-order +flake8-print +flake8-strict +pytest +pytest-cov diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..9b29cf9 --- /dev/null +++ b/setup.py @@ -0,0 +1,49 @@ +# All Rights Reserved. +# +# 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. + +"""Project settings.""" + +import pathlib + +from setuptools import find_packages, setup + +from pypi_packaging import pypi_config + +here = pathlib.Path(__file__).parent.resolve() +long_description = (here / "README.md").read_text(encoding="utf-8") + +setup( + name=pypi_config["package_name"], + summary="CDEvents SDK Python", + long_description_content_type="text/markdown", + long_description=long_description, + author="The CDEvents Contributors", + author_email="TODO", + home_page="https://cdevents.dev", + classifiers=[ + "Intended Audience :: Information Technology", + "Intended Audience :: System Administrators", + "License :: OSI Approved :: Apache Software License", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + ], + packages=find_packages(exclude=["cdevents.tests"]), + version=pypi_config["version_target"], + install_requires=["cloudevents>=1.2.0,<2.0"], +) From 9f52c123b2d66107b99acb1489eab08c3a270b7c Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Thu, 30 Jun 2022 12:42:24 +0200 Subject: [PATCH 03/34] test update --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e8d36c8..31288e0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ # sdk-python Python SDK for CDEvents + +update ... \ No newline at end of file From d01cf12a1b7a5520f30f195cad571996ea0008ef Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Tue, 5 Jul 2022 14:47:28 +0200 Subject: [PATCH 04/34] first commit --- cli/MANIFEST.in | 2 + cli/Makefile | 7 + cli/README.md | 0 cli/cdevents/cli/__init__.py | 3 + cli/cdevents/cli/__main__.py | 67 ++++ cli/cdevents/cli/build copy.py | 376 ++++++++++++++++++ cli/cdevents/cli/build.py | 143 +++++++ cli/cdevents/cli/constants.py | 13 + cli/cdevents/cli/utils.py | 133 +++++++ cli/cdevents/configuration/__init__.py | 1 + cli/cdevents/configuration/configuration.yaml | 17 + .../configuration/logging-configuration.yaml | 26 ++ cli/setup.cfg | 64 +++ cli/setup.py | 10 + 14 files changed, 862 insertions(+) create mode 100644 cli/MANIFEST.in create mode 100644 cli/Makefile create mode 100644 cli/README.md create mode 100644 cli/cdevents/cli/__init__.py create mode 100644 cli/cdevents/cli/__main__.py create mode 100644 cli/cdevents/cli/build copy.py create mode 100644 cli/cdevents/cli/build.py create mode 100644 cli/cdevents/cli/constants.py create mode 100644 cli/cdevents/cli/utils.py create mode 100644 cli/cdevents/configuration/__init__.py create mode 100644 cli/cdevents/configuration/configuration.yaml create mode 100644 cli/cdevents/configuration/logging-configuration.yaml create mode 100644 cli/setup.cfg create mode 100644 cli/setup.py diff --git a/cli/MANIFEST.in b/cli/MANIFEST.in new file mode 100644 index 0000000..d9f77c2 --- /dev/null +++ b/cli/MANIFEST.in @@ -0,0 +1,2 @@ +include cdevents/configuration/configuration.yaml +include cdevents/configuration/logging-configuration.yaml diff --git a/cli/Makefile b/cli/Makefile new file mode 100644 index 0000000..f473d81 --- /dev/null +++ b/cli/Makefile @@ -0,0 +1,7 @@ +include ../header.mk + +SRC := cdevents/cli + +MAKEFILE_LIST=../targets.mk + +include $(MAKEFILE_LIST) diff --git a/cli/README.md b/cli/README.md new file mode 100644 index 0000000..e69de29 diff --git a/cli/cdevents/cli/__init__.py b/cli/cdevents/cli/__init__.py new file mode 100644 index 0000000..8bc3d2a --- /dev/null +++ b/cli/cdevents/cli/__init__.py @@ -0,0 +1,3 @@ +"""CDEvents CLI provides command-line interaction with Cd-Event client functionality.""" + +__version__ = "0.0.1" diff --git a/cli/cdevents/cli/__main__.py b/cli/cdevents/cli/__main__.py new file mode 100644 index 0000000..379433a --- /dev/null +++ b/cli/cdevents/cli/__main__.py @@ -0,0 +1,67 @@ +"""Module for main entry point for cdevents.cli.""" +import logging +import logging.config +from pathlib import Path + +import click +import yaml + +from cdevents.cli.constants import LOGGING_CONFIGURATION_FILE +from cdevents.cli.build import finished, queued, started +from cdevents.cli.utils import add_disclaimer_text + +def configure_logging(): + """Configures logging from file.""" + config_file = Path(LOGGING_CONFIGURATION_FILE) + logging_config = yaml.safe_load(config_file.read_text(encoding="utf8")) + logging.config.dictConfig(logging_config) + + +@click.group(help=add_disclaimer_text("""Commands Build related CloudEvent.""")) +def build(): + """Click group for command 'build'.""" + +build.add_command(finished) +build.add_command(queued) +build.add_command(started) + + +# @click.group(help=add_disclaimer_text("""Commands with no interaction with hostlog.""")) +# def offline(): +# """Function for command group offline.""" + + +# offline.add_command(pcap_to_hdf5) +# TODO: activate line when command is implemented +# offline.add_command(visualize) +# offline.add_command(create_dissector) +# offline.add_command(convert_to_xviz) +# offline.add_command(topic_configuration) + + +# @click.group(help=add_disclaimer_text("Commands for local web UI.")) +# def web(): +# """Click group for command 'web'.""" + + +# web.add_command(web_start) + + +@click.group( + help=add_disclaimer_text( + """Main entry point for cdevents client cli. + Select command group from Commands. + Add '--help' to see more information about each subcommand, option and argument.""" + ) +) +def cli(): + """Main method for cli.""" + configure_logging() + + +cli.add_command(build) +# cli.add_command(offline) +# cli.add_command(web) + +if __name__ == "__main__": + cli() diff --git a/cli/cdevents/cli/build copy.py b/cli/cdevents/cli/build copy.py new file mode 100644 index 0000000..3dff37b --- /dev/null +++ b/cli/cdevents/cli/build copy.py @@ -0,0 +1,376 @@ +"""Module for cli build commands.""" +from __future__ import annotations + +from ast import literal_eval +from pathlib import Path +from typing import List, Tuple, Union + +import click +# from click_option_group import MutuallyExclusiveOptionGroup, optgroup + +# from hostlog.cli.cached_settings import CachedSettingsHandler +# from hostlog.cli.configuration_handler import new_configuration_handler_with_override +# from hostlog.cli.configuration_reader import ConfigurationReader +# from cdevents.cli.online_commands import ( +# FetchTdfCommand, +# MaxLogData, +# StartLoggingCommand, +# Topic, +# ) +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, + yaml_files_in_directory, +) + + +# pylint: disable=unused-argument +def common_build_options(function): + """Decorator for common cli options for host connection.""" + function = click.option( + "--output", + "-o", + # FIXME: set to true during integration + required=False, + type=str, + help="Path to output directory. Overrides configuration.", + )(function) + function = function = click.option( + "--port", + "-p", + required=False, + type=int, + help="The host's port. Overrides configuration.", + )(function) + function = click.option( + "--host", + "-h", + required=False, + type=str, + help="IP address of host. Overrides configuration.", + )(function) + function = click.option( + "--to-binary", + "-b", + type=bool, + is_flag=True, + default=False, + help="If set, all received data will be stored in binary format.", + )(function) + function = click.option( + "--no-decode", + type=bool, + is_flag=True, + default=False, + help="If set, no decoding of received data will be done.", + )(function) + function = click.option( + "--dcf-version", + type=int, + required=False, + help="Version of the DCF protocol to use. Overrides configuration.", + )(function) + return function + + +@click.command(help=add_disclaimer_text("Fetch Topic Definition Files from target.")) +@common_build_options +def fetch_tdf( + output: str, + host: str = None, + port: int = None, + dcf_version: int = None, + to_binary: bool = False, + no_decode: bool = False, +): + """Start client, fetch and save TDF files. \ + Storage location is read from configuration file or optional argument.""" + print_function_args() + + # config_handler = new_configuration_handler_with_override(output, host, port, dcf_version) + + # fetch_tdf_command = FetchTdfCommand( + # config_handler=config_handler, to_binary=to_binary, no_decode=no_decode + # ) + # fetch_tdf_command.run() + # # Save tdf output directory to settings file. + # settings_handler = CachedSettingsHandler() + # settings_handler.latest_tdf_directory = fetch_tdf_command.destination_directory + + +@click.command( + help=add_disclaimer_text( + "Subscribe to one or more hostlog/DCF topics and start receiving and decoding messages." + ) +) +@common_build_options +@click.option( + "--topics", + "-t", + type=str, + required=False, + default="", + help=( + "Topic subscriptions as a comma separated string ':'." + + " E.g. '1:0,1:2,2:0,2:1'" + + " (Selected topics must be described in TDFs)." + + " Optional. If not provided, all topics in given TDFs will be subscribed to." + ), +) +# @click.option( +# "--visualize", +# type=bool, +# is_flag=True, +# default=False, +# help="If set, then visualization will start at the same time as logging", +# ) +# FIXME: Add more help text regarding configuration of dissector. +# @click.option( +# "--create-dissector", +# type=str, +# help="If set, a Wireshark dissector is created based on configuration TBD.", +# ) +@click.option( + "--to-hdf5", + type=bool, + is_flag=True, + default=False, + help="If set, decoded data will be saved to HDF5 file in the output directory.", +) +@click.option( + "--to-text", + type=bool, + is_flag=True, + default=False, + help="If set, decoded data will be saved to text file in the output directory.", +) +@click.option( + "--definitions", + "-d", + type=str, + required=False, + help=( + "Path to Topic Definition File(s) describing all topics that can be subscribed to." + + " If path is a directory then all its *.yaml files will be loaded." + + " Optional: If no argument is given," + + " the most recently fetched TDF directory will be used." + ), +) +@click.option( + "--config", + "-c", + type=str, + required=False, + default="", + help=( + "Path to configuration file generated by frontend UI." + + " N.B. This configuration will override arguments '--config' and '--topics'" + ), +) +@click.option( + "--max-messages", + type=int, + required=False, + help=("Maximum number of messages to log."), +) +# @optgroup.group( +# "Maximum logging time.", +# cls=MutuallyExclusiveOptionGroup, +# help="Mutually exclusive parameters for maximum logging time.", +# ) +# @optgroup.option( +# "--max-time-s", +# type=int, +# help=("Maximum logging time in seconds."), +# ) +# @optgroup.option( +# "--max-time-m", +# type=float, +# help=("Maximum logging time in minutes."), +# ) +# @optgroup.option( +# "--max-time-h", +# type=float, +# help=("Maximum logging time in hours."), +# ) +# @optgroup.group( +# "Maximum amount of logged data.", +# cls=MutuallyExclusiveOptionGroup, +# help="Mutually exclusive parameters group for maximum amount of logged data.", +# ) +# @optgroup.option( +# "--max-kbytes", +# type=float, +# help=("Maximum number of kilobytes to log."), +# ) +# @optgroup.option( +# "--max-mbytes", +# type=float, +# help=("Maximum number of megabytes to log."), +# ) +# @optgroup.option( +# "--max-gbytes", +# type=float, +# help=("Maximum number of gigabytes to log."), +# ) +# TODO: keep or not to keep "--enable-multiprocessing" +# @click.option( +# "--enable-multiprocessing", +# type=bool, +# is_flag=True, +# default=False, +# help="If set, multiprocessing decoding will be disabled.", +# ) +def start_logging( + output: str, + definitions: Union[str, Path], + topics: str = "", + visualize: bool = False, + create_dissector: str = None, + host: str = None, + port: int = None, + dcf_version: int = None, + to_hdf5: bool = False, + to_binary: bool = False, + no_decode: bool = False, + to_text: bool = False, + config: str = "", + max_messages: int = None, + max_time_s: int = None, + max_time_m: int = None, + max_time_h: int = None, + max_kbytes: int = None, + max_mbytes: int = None, + max_gbytes: int = None, + enable_multiprocessing: bool = None, +): + """Method for cli command to start streaming host logging.""" + print_function_args() + + # config_handler = new_configuration_handler_with_override( + # output, + # host, + # port, + # dcf_version, + # enable_multiprocessing, + # ) + + # ###### frontend configuration file + # _topics = [] + # if config: + # # override '--topics' and '--definitions' + # frontend_config_handler = FrontendConfigHandler(config) + # definitions = frontend_config_handler.topic_collection + # if not Path(definitions).is_absolute(): + # definitions = Path(config_handler.output.directory).joinpath("tdf", definitions) + # _topics = frontend_config_handler.selected_topics + # elif topics != "": + # # Only true if topics are used and no UI config file. + # _topics = TopicsArgParser.topic_arg_to_topics(topics) + # # If no-decode true then configuration files are not necessary. + # if no_decode: + # hostlog_configuration_files = [] + # else: + # ######## If '--config' and '--contend_config' are not set, use latest fetched tdfs #### + # if not (definitions or config): + # definitions = CachedSettingsHandler.get_cached_configuration_path() + + # ####### Fetch all tdf configuration files. ########## + # hostlog_configuration_files = yaml_files_in_directory(Path(definitions)) + + # ####### Max data to log. ####### + # max_log_data = MaxLogData.new_instance( + # max_time_s=max_time_s, + # max_time_m=max_time_m, + # max_time_h=max_time_h, + # max_messages=max_messages, + # max_kbytes=max_kbytes, + # max_mbytes=max_mbytes, + # max_gbytes=max_gbytes, + # ) + + # start_logging_command = StartLoggingCommand( + # config_handler=config_handler, + # hostlog_config_files=hostlog_configuration_files, + # topics=_topics, + # to_binary=to_binary, + # no_decode=no_decode, + # to_hdf5=to_hdf5, + # to_text=to_text, + # max_log_data=max_log_data, + # ) + # start_logging_command.run() + + +# class TopicsArgParser: +# """Class handling parsing selected topics argument string.""" + +# @staticmethod +# def topic_arg_to_topics(topics_str: str) -> List[Topic]: +# """Parse arg string to list of Topics. + +# Expected arg string format: ',1:2,2:3,.....' + +# Returns: +# List[Topic]: A sorted list of topics. +# """ +# return TopicsArgParser._to_topics(TopicsArgParser._parse_topics_arg(topics_str)) + +# @staticmethod +# def _parse_topics_arg(topics_str: str) -> List[Tuple]: +# topics = [] +# parse_erro_msg = "Error parsing topics argument:" +# for tuple_str in topics_str.split(","): +# topic_tuple = literal_eval(tuple_str.strip().replace(":", ",")) +# if not isinstance(topic_tuple, tuple): +# raise ValueError(f"{parse_erro_msg} Expected 'int:int' but found {tuple_str!r}") +# if not len(topic_tuple) == 2: +# raise ValueError( +# ( +# f"{parse_erro_msg} Expected 2 elements but found {len(topic_tuple)!r}" +# + f" when parsing {tuple_str!r}." +# ) +# ) +# if not all(isinstance(element, int) for element in topic_tuple): +# raise ValueError(f"{parse_erro_msg} Expected int but found {topic_tuple!r}") +# topics.append(topic_tuple) +# # Remove duplicates +# return sorted(list(set(topics))) + +# @staticmethod +# def _to_topics(topics: List[Tuple]) -> List[Topic]: +# return [Topic(*i) for i in topics] + + +# class FrontendConfigHandler: +# """Class providing configuration from file generated by the frontend.""" + +# def __init__(self, config_file: str): +# """Initialize object. + +# Args: +# config_file (str): Path to configuration file generated by the selected topics UI. +# """ +# self._config: dict = self._read(Path(config_file)) + +# @staticmethod +# def _read(config_file: Path) -> dict: +# config_reader = ConfigurationReader() +# config_reader.read_configuration(config_file) +# return config_reader.configuration + +# @property +# def selected_topics(self) -> List[Topic]: +# """Return selected topics from configuration file.""" +# result = [] +# _selected_topics = self._config["selected_topics"] +# for channel_topic in _selected_topics: +# channel_id = channel_topic["channel"] +# for _topic in channel_topic["topics"]: +# result.append(Topic(channel_id=int(channel_id), topic_id=int(_topic))) +# return result + +# @property +# def topic_collection(self) -> Path: +# """Return topic collection.""" +# return Path(self._config["topic_collection"]) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py new file mode 100644 index 0000000..2a62f15 --- /dev/null +++ b/cli/cdevents/cli/build.py @@ -0,0 +1,143 @@ +"""Module for cli build commands.""" +from __future__ import annotations +import os + +from ast import literal_eval +from pathlib import Path +from typing import List, Tuple, Union + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, + yaml_files_in_directory, +) + + +# pylint: disable=unused-argument +def common_build_options(function): + """Decorator for common cli options for build.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Build Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Build Name.", + )(function) + function = click.option( + "--artifact", + "-a", + required=False, + type=str, + help="Build's Artifact Id.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + #type=click.Tuple([str, str]), + type=(str,str), + multiple=True, + help="Build Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("Build Started CloudEvent.")) +@common_build_options +def started( + cde_sink: str, + id: str, + name: str = None, + artifact: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.build.started.v1", + "source": "cde-cli", + "extensions": { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, + }, + } + #TODO: add "datacontenttype" + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + + +@click.command(help=add_disclaimer_text("Build Finished CloudEvent.")) +@common_build_options +def finished( + cde_sink: str, + id: str, + name: str = None, + artifact: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.build.finished.v1", + "source": "cde-cli", + "extensions": { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, + }, + } + #TODO: add "datacontenttype" + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) +@common_build_options +def queued( + cde_sink: str, + id: str, + name: str = None, + artifact: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.build.queued.v1", + "source": "cde-cli", + "extensions": { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, + }, + } + #TODO: add "datacontenttype" + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) diff --git a/cli/cdevents/cli/constants.py b/cli/cdevents/cli/constants.py new file mode 100644 index 0000000..6f04189 --- /dev/null +++ b/cli/cdevents/cli/constants.py @@ -0,0 +1,13 @@ +"""Constants for cdevents cli.""" +from pathlib import Path + +# configuration/configuration.yaml +_CLI_CDEVENTS_DIR = Path(__file__).parent.parent +DEAFULT_CONFIGURATION_FILE = str(Path(_CLI_CDEVENTS_DIR, "configuration", "configuration.yaml")) +LOGGING_CONFIGURATION_FILE = str( + Path(_CLI_CDEVENTS_DIR, "configuration", "logging-configuration.yaml") +) + +BYTES_IN_KILOBYTES = 1024 +BYTES_IN_MEGABYTES = BYTES_IN_KILOBYTES * BYTES_IN_KILOBYTES +BYTES_IN_GIGABYTES = BYTES_IN_MEGABYTES * BYTES_IN_KILOBYTES diff --git a/cli/cdevents/cli/utils.py b/cli/cdevents/cli/utils.py new file mode 100644 index 0000000..7a7df6e --- /dev/null +++ b/cli/cdevents/cli/utils.py @@ -0,0 +1,133 @@ +"""Only used for unit test.""" +from __future__ import annotations + +import datetime +import inspect +import os +from pathlib import Path + + +def print_function_args(): + """Prints name. parameter names and values of calling function. + + Mainly for test purpose. + """ + frame = inspect.stack()[1].frame + args, _, _, values = inspect.getargvalues(frame) + func_info_list = [f"func={inspect.stack()[1].function}"] + for arg in args: + func_info_list.append(f"{arg}={values.get(arg)}") + print(", ".join(func_info_list)) + + +def time_stamp(separator: str = "_", utc: bool = True) -> str: + """Returns a time stamp. + + format "YYYYmmddHHMMSSsss" + Args: + separator (str, optional):Separator char. Defaults to "_". + + Returns: + str: _description_ + """ + if utc: + return _utcnow().strftime(f"%Y%m%d{separator}%H%M%S%f")[:-3] + else: + return _now().strftime(f"%Y%m%d{separator}%H%M%S%f")[:-3] + + +def _utcnow() -> datetime.datetime: + return datetime.datetime.utcnow() + + +def _now() -> datetime.datetime: + return datetime.datetime.now() + + +class DictUtils: + """Utility class for dictionary related methods.""" + + @staticmethod + def merge_dicts(source: dict, destination: dict): + """Merges source with destination dict. + + If corresponding key exist in both source and destination, destination will not be + overwritten, unless the value is a list, then source list will be appended to exsting + distination list. + + Args: + source (dict): dict to be merge. + destination (dict): dict to be merged into. + """ + # pylint: disable=invalid-name + for k, v in source.items(): + if ( + k in destination + and isinstance(destination[k], dict) + and isinstance(source[k], dict) + ): + DictUtils.merge_dicts(source[k], destination[k]) + # Only update destination if key does not exist + elif k in destination and isinstance(destination[k], list): + destination[k].extend(v) + elif k not in destination: + destination[k] = v + + +def yaml_files_in_directory(config: Path) -> list[str]: + """List all yaml files in directory. + + Args: + config (Path): the directory. + + Raises: + FileNotFoundError: raised if source directory does not exist. + + Returns: + list[str]: list of yaml files. + """ + config_files = [] + if not os.path.exists(config): + raise FileNotFoundError(f"Path {config!r} does not exist.") + if os.path.isdir(config): + yaml_files = [ + str(Path(config, file)) + for file in os.listdir(config) + if file.endswith((".yaml", ".yml")) + ] + config_files.extend(yaml_files) + else: + config_files.append(str(config)) + return config_files + + +def is_windows() -> bool: + """True if the host system is Windows. + + Returns: + bool: the result. + """ + return _os_name() == "nt" + + +def _os_name() -> str: + return os.name + +#TODO: Update disclaimer text +DISCLAIMER_TEXT = """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + N.B. Due to data privacy regulations, all locally generated cdevents data files + ,such as hdf5 etc, must be deleted after a logging session is finished. + Exluded are log files generated by Vigem on the way to be stored in Oden + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!""" + + +def add_disclaimer_text(help_text: str) -> str: + """Return disclaimer text + help text. + + Returns: + str: Disclaimer + help_text. + """ + return f"""{DISCLAIMER_TEXT} + + {help_text} + """ diff --git a/cli/cdevents/configuration/__init__.py b/cli/cdevents/configuration/__init__.py new file mode 100644 index 0000000..8ca75fa --- /dev/null +++ b/cli/cdevents/configuration/__init__.py @@ -0,0 +1 @@ +"""Package only to enable access to config files after package install or build.""" diff --git a/cli/cdevents/configuration/configuration.yaml b/cli/cdevents/configuration/configuration.yaml new file mode 100644 index 0000000..a7acaef --- /dev/null +++ b/cli/cdevents/configuration/configuration.yaml @@ -0,0 +1,17 @@ +--- +configuration: + output: + directory: ${HOME}/cdevents_client + utc_timestamps: false + trace_logging: false # Warning: Trace logging is VERY slow!! + client: + host: 127.0.0.1 + port: 30700 + dcf_version: 4 + timeout_seconds: 5 + max_retries: 3 + process_handling: + enable_multiprocessing: false + enable_worker_logging: false # Warning: logging is VERY slow!! + number_of_workers: -1 # Default is -1. Auto selects number of processes + # after number of physical cores of the host. diff --git a/cli/cdevents/configuration/logging-configuration.yaml b/cli/cdevents/configuration/logging-configuration.yaml new file mode 100644 index 0000000..537698c --- /dev/null +++ b/cli/cdevents/configuration/logging-configuration.yaml @@ -0,0 +1,26 @@ +--- +version: 1 +disable_existing_loggers: false +formatters: + simple: + format: "%(asctime)s.%(msecs)03d [%(threadName)s] %(levelname)-s - %(message)-s - %(name)s:%(lineno)d" # yamllint disable-line + datefmt: "%Y-%m-%dT%H:%M:%S" +handlers: + console: + class: logging.StreamHandler + formatter: simple + stream: ext://sys.stdout + file: + class: logging.handlers.RotatingFileHandler + formatter: simple + filename: cdevents-client.log + maxBytes: 10485760 # 10MB + backupCount: 20 + encoding: utf8 +loggers: + logger-1: + handlers: [console, file] + propagate: true +root: + level: INFO + handlers: [console, file] diff --git a/cli/setup.cfg b/cli/setup.cfg new file mode 100644 index 0000000..882c407 --- /dev/null +++ b/cli/setup.cfg @@ -0,0 +1,64 @@ +[bumpversion] +current_version = 0.0.1 + +[bumpversion:file:./cdevents/cli/__init__.py] + +[metadata] +name = cdevents.cli +description = CDEvents CLI +long_description = file: README.md +version = attr: cdevents.cli.__version__ +author = doWhile +author_email = info@dowhile.com +keywords = cdevents, cli +url = todo +classifiers = + Development Status :: 3 - Alpha + Intended Audience :: Developers + License :: Other/Proprietary License + Natural Language :: English + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.9 + Topic :: Software Development :: Libraries :: Python Modules + +[options] +packages = find_namespace: +zip_safe = False +include_package_data = True +install_requires = + click>=8.0.4 + pyyaml>=6.0 + click-option-group + requests + cloudevents + +[options.extras_require] +dev = + black + bump2version + isort + mypy + pre-commit + pydocstyle + pytest + pytest_mock + yamllint + pylint + +build = + wheel + +[options.packages.find] +include = + cdevents.* + +[bdist_wheel] +universal = 0 + +[options.entry_points] +console_scripts = + cdevents = cdevents.cli.__main__:cli diff --git a/cli/setup.py b/cli/setup.py new file mode 100644 index 0000000..f3d9343 --- /dev/null +++ b/cli/setup.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""The setup script.""" + +__requires__ = "setuptools >= 44.0.0" + +from setuptools import setup + +setup() From 5a5f59d7fb8e58c96b1c03346ee3bd34320430ae Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Tue, 5 Jul 2022 14:53:39 +0200 Subject: [PATCH 05/34] add deployment files --- Dockerfile | 24 +++++++++++++++++ Makefile | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ header.mk | 27 ++++++++++++++++++++ targets.mk | 69 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 195 insertions(+) create mode 100644 Dockerfile create mode 100644 Makefile create mode 100644 header.mk create mode 100644 targets.mk diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ac1888b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# syntax=docker/dockerfile:1 + +FROM python:3.8 + +# Setup environment +RUN apt-get update && apt-get install -y \ + python3-distutils \ + build-essential + +# Copy requirements +COPY ./requirements ./requirements + +# Installing requirements +RUN pip install -r ./requirements + +# Copy needed files (see .dockerignore for what will be included) +COPY . /cdevents-client + +WORKDIR /cdevents-client + +# Build +RUN /bin/bash -c "make package-install" + +WORKDIR /cdevents-client diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..95c6411 --- /dev/null +++ b/Makefile @@ -0,0 +1,75 @@ +include header.mk + +PACKAGES = template core web cli +export ABS_ROOT_PATH=$(shell pwd) + +.PHONY: packages $(PACKAGES) + +packages: $(PACKAGES) + +$(PACKAGES): + $(MAKE) -C $@ + +# the sets of directories to do various things in +INITPACKAGES = $(PACKAGES:%=init-%) +INSTALLPACKAGES = $(PACKAGES:%=package-install-%) +CLEANPACKAGES = $(PACKAGES:%=clean-%) +TESTPACKAGES = $(PACKAGES:%=test-%) +LINTPACKAGES = $(PACKAGES:%=lint-%) +FORMATPACKAGES = $(PACKAGES:%=format-%) +BUMPVERSIONPACKAGES = $(PACKAGES:%=bumpversion-%) + +help: ## Prints this help text + @python -c "$$PRINT_HELP_PYSCRIPT" < Makefile + +init: $(INITPACKAGES) ## Installs all packages in editable mode including dev dependencies +$(INITPACKAGES): + $(MAKE) -C $(@:init-%=%) init + +package-install: $(INSTALLPACKAGES) ## Installs all packages without dev dependencies +$(INSTALLPACKAGES): + $(MAKE) -C $(@:package-install-%=%) package-install + +test: $(TESTPACKAGES) ## Run tests on all packages +$(TESTPACKAGES): + $(MAKE) -C $(@:test-%=%) test + +clean: $(CLEANPACKAGES) ## Remove all build, test, coverage and Python artifacts +$(CLEANPACKAGES): + $(MAKE) -C $(@:clean-%=%) clean + +bumpversion: ${BUMPVERSIONPACKAGES} ## Bumps the (default: patch) version of all release packages. To bump minor or major, add bump=minor or bump=major to the make call. +$(BUMPVERSIONPACKAGES): + $(MAKE) -C $(@:bumpversion-%=%) bumpversion + +lint: $(LINTPACKAGES) +$(LINTPACKAGES): + $(MAKE) -C $(@:lint-%=%) lint + +format: $(FORMATPACKAGES) +$(FORMATPACKAGES): + $(MAKE) -C $(@:format-%=%) format + +install: ## Installs dependencies from requirements.txt + pip install -r ./requirements + pre-commit install + +internal-install: ## Installs VCC-internal dependencies from vcc-requirements.txt + pip install --extra-index-url https://TODO -r vccinternal-requirements.txt + +check: ## Runs pre-commit hooks on all files + pre-commit run --all-files + +docker-build: ## Build and package Docker container + docker build -t cdevents-client -f Dockerfile . + +docker-shell: ## Opens a shell + docker run --add-host=host.docker.internal:host-gateway --volume /"$(shell pwd)"/output/:/root/cdevents-client/ -it cdevents-client bash + +.PHONY: packages $(PACKAGES) +.PHONY: packages $(INITPACKAGES) +.PHONY: packages $(INSTALLPACKAGES) +.PHONY: packages $(TESTPACKAGES) +.PHONY: packages $(CLEANPACKAGES) +.PHONY: packages $(BUMPVERSIONPACKAGES) +.PHONY: init test clean bumpversion install internal-install check docker-build docker-shell diff --git a/header.mk b/header.mk new file mode 100644 index 0000000..0adf6dd --- /dev/null +++ b/header.mk @@ -0,0 +1,27 @@ +.PHONY: clean clean-test clean-pyc clean-build help +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +try: + from urllib import pathname2url +except: + from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" diff --git a/targets.mk b/targets.mk new file mode 100644 index 0000000..0e3df07 --- /dev/null +++ b/targets.mk @@ -0,0 +1,69 @@ +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +init: clean ## install the package in editable mode including dev dependencies + pip install -e .[dev] + pre-commit install + +package-install: ## install the package without dev dependencies + pip install . + +test: ## run tests quickly with the default Python + python -m pytest -m unit + +dist: clean ## builds source and wheel package + python setup.py sdist + python setup.py bdist_wheel + ls -l dist + +format: ## format all Python code using black + python -m black --line-length=100 . + +.ONESHELL: +lint: ## run pylint + python -m pylint $(SRC) --rcfile=$(ABS_ROOT_PATH)/.pylintrc + exit_code=$$? + python -m pylint \ + --disable duplicate-code \ + --disable missing-module-docstring \ + --disable missing-function-docstring \ + tests --rcfile=$(ABS_ROOT_PATH)/.pylintrc + exit_code=`expr $${exit_code} + $$?` + if [ "$${exit_code}" != 0 ]; then + exit "$${exit_code}" + fi + +clean: clean-build clean-pyc clean-test clean-mypy ## remove all build, test, coverage and Python artifacts + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + # N.B. line below removes editable intallation of package in venv + # find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -f .coverage + rm -fr htmlcov/ + rm -fr .pytest_cache + +clean-mypy: ## remove MyPy cache files + rm -fr .mypy_cache/ + +bump = patch +bumpversion: ## Bumps the (default: patch) version of this package. To bump minor or major, add bump=minor or bump=major to the make call. + bumpversion --allow-dirty $(bump) + - pre-commit run trailing-whitespace --file setup.cfg + - pre-commit run remove-tabs --file setup.cfg + + +.ONESHELL: +pre-commit: + pre-commit run --all-files From cb285b9a5197ba36b02c45740de47d85ce58fbfc Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 6 Jul 2022 15:00:48 +0200 Subject: [PATCH 06/34] add command files --- cli/cdevents/cli/__main__.py | 80 +++++-- cli/cdevents/cli/artifact.py | 110 ++++++++++ cli/cdevents/cli/branch.py | 112 ++++++++++ cli/cdevents/cli/build copy.py | 376 -------------------------------- cli/cdevents/cli/build.py | 8 +- cli/cdevents/cli/env.py | 137 ++++++++++++ cli/cdevents/cli/pipelinerun.py | 161 ++++++++++++++ cli/cdevents/cli/service.py | 160 ++++++++++++++ cli/cdevents/cli/taskrun.py | 110 ++++++++++ 9 files changed, 855 insertions(+), 399 deletions(-) create mode 100644 cli/cdevents/cli/artifact.py create mode 100644 cli/cdevents/cli/branch.py delete mode 100644 cli/cdevents/cli/build copy.py create mode 100644 cli/cdevents/cli/env.py create mode 100644 cli/cdevents/cli/pipelinerun.py create mode 100644 cli/cdevents/cli/service.py create mode 100644 cli/cdevents/cli/taskrun.py diff --git a/cli/cdevents/cli/__main__.py b/cli/cdevents/cli/__main__.py index 379433a..3db94e7 100644 --- a/cli/cdevents/cli/__main__.py +++ b/cli/cdevents/cli/__main__.py @@ -7,9 +7,17 @@ import yaml from cdevents.cli.constants import LOGGING_CONFIGURATION_FILE -from cdevents.cli.build import finished, queued, started from cdevents.cli.utils import add_disclaimer_text +from cdevents.cli.build import finished, queued, started +from cdevents.cli.artifact import packaged, published +from cdevents.cli.branch import created as branch_created, deleted as branch_deleted +from cdevents.cli.env import created as env_created, deleted as env_deleted, modified as env_modified +from cdevents.cli.pipelinerun import started as pipe_started, finished as pipe_finished, queued as pipe_queued +from cdevents.cli.service import deployed as service_deployed, upgraded as service_upgraded, removed as service_removed, rolledback as service_rolledback +from cdevents.cli.taskrun import started as taskrun_started, finished as taskrun_finished + + def configure_logging(): """Configures logging from file.""" config_file = Path(LOGGING_CONFIGURATION_FILE) @@ -26,25 +34,61 @@ def build(): build.add_command(started) -# @click.group(help=add_disclaimer_text("""Commands with no interaction with hostlog.""")) -# def offline(): -# """Function for command group offline.""" +@click.group(help=add_disclaimer_text("""Commands Artifact related CloudEvent.""")) +def artifact(): + """Click group for command 'artifact'.""" + +artifact.add_command(packaged) +artifact.add_command(published) + + +@click.group(help=add_disclaimer_text("""Commands Branch related CloudEvent.""")) +def branch(): + """Click group for command 'branch'.""" + +branch.add_command(branch_created) +branch.add_command(branch_deleted) + + +@click.group(help=add_disclaimer_text("""Commands Environment related CloudEvent.""")) +def env(): + """Click group for command 'environment'.""" + +env.add_command(env_created) +env.add_command(env_deleted) +env.add_command(env_modified) + + + + +@click.group(help=add_disclaimer_text("""Commands PipelineRun related CloudEvent.""")) +def pipelinerun(): + """Click group for command 'environment'.""" + +pipelinerun.add_command(pipe_started) +pipelinerun.add_command(pipe_finished) +pipelinerun.add_command(pipe_queued) + + + +@click.group(help=add_disclaimer_text("""Commands Service related CloudEvent.""")) +def service(): + """Click group for command 'service'.""" +service.add_command(service_deployed) +service.add_command(service_upgraded) +service.add_command(service_removed) +service.add_command(service_rolledback) -# offline.add_command(pcap_to_hdf5) -# TODO: activate line when command is implemented -# offline.add_command(visualize) -# offline.add_command(create_dissector) -# offline.add_command(convert_to_xviz) -# offline.add_command(topic_configuration) +@click.group(help=add_disclaimer_text("""Commands TaskRun related CloudEvent.""")) +def taskrun(): + """Click group for command 'taskrun'.""" -# @click.group(help=add_disclaimer_text("Commands for local web UI.")) -# def web(): -# """Click group for command 'web'.""" +taskrun.add_command(taskrun_started) +taskrun.add_command(taskrun_finished) -# web.add_command(web_start) @click.group( @@ -60,8 +104,12 @@ def cli(): cli.add_command(build) -# cli.add_command(offline) -# cli.add_command(web) +cli.add_command(artifact) +cli.add_command(branch) +cli.add_command(env) +cli.add_command(pipelinerun) +cli.add_command(service) +cli.add_command(taskrun) if __name__ == "__main__": cli() diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py new file mode 100644 index 0000000..439f208 --- /dev/null +++ b/cli/cdevents/cli/artifact.py @@ -0,0 +1,110 @@ +"""Module for cli artifact commands.""" +from __future__ import annotations +import os + +from typing import List + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, +) + + +# pylint: disable=unused-argument +def common_artifact_options(function): + """Decorator for common cli options for artifact.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Artifact Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Artifact Name.", + )(function) + function = click.option( + "--version", + "-v", + required=False, + type=str, + help="Artifact Version.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str,str), + multiple=True, + help="Artifact Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("Artifact Packaged CloudEvent.")) +@common_artifact_options +def packaged( + cde_sink: str, + id: str, + name: str = None, + version: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.artifact.packaged.v1", + "source": "cde-cli", + "extensions": { + "artifactid": id, + "artifactname": name, + "artifactversion": version, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("Artifact Published CloudEvent.")) +@common_artifact_options +def published( + cde_sink: str, + id: str, + name: str = None, + version: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.artifact.published.v1", + "source": "cde-cli", + "extensions": { + "artifactid": id, + "artifactname": name, + "artifactversion": version, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) \ No newline at end of file diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py new file mode 100644 index 0000000..b623b89 --- /dev/null +++ b/cli/cdevents/cli/branch.py @@ -0,0 +1,112 @@ +"""Module for cli branch commands.""" +from __future__ import annotations +import os + +from typing import List + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, +) + + +# pylint: disable=unused-argument +def common_branch_options(function): + """Decorator for common cli options for branch.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Branch Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Branch Name.", + )(function) + function = click.option( + "--repoid", + "-v", + required=False, + type=str, + help="Branch Repository Id.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str,str), + multiple=True, + help="Branch Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("Branch Created CloudEvent.")) +@common_branch_options +def created( + cde_sink: str, + id: str, + name: str = None, + repoid: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.repository.branch.created.v1", + "source": "cde-cli", + "extensions": { + "branchid": id, + "branchname": name, + "branchrepositoryid": repoid, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + + +@click.command(help=add_disclaimer_text("Branch Deleted CloudEvent.")) +@common_branch_options +def deleted( + cde_sink: str, + id: str, + name: str = None, + repoid: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.repository.branch.deleted.v1", + "source": "cde-cli", + "extensions": { + "branchid": id, + "branchname": name, + "branchrepositoryid": repoid, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + diff --git a/cli/cdevents/cli/build copy.py b/cli/cdevents/cli/build copy.py deleted file mode 100644 index 3dff37b..0000000 --- a/cli/cdevents/cli/build copy.py +++ /dev/null @@ -1,376 +0,0 @@ -"""Module for cli build commands.""" -from __future__ import annotations - -from ast import literal_eval -from pathlib import Path -from typing import List, Tuple, Union - -import click -# from click_option_group import MutuallyExclusiveOptionGroup, optgroup - -# from hostlog.cli.cached_settings import CachedSettingsHandler -# from hostlog.cli.configuration_handler import new_configuration_handler_with_override -# from hostlog.cli.configuration_reader import ConfigurationReader -# from cdevents.cli.online_commands import ( -# FetchTdfCommand, -# MaxLogData, -# StartLoggingCommand, -# Topic, -# ) -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, - yaml_files_in_directory, -) - - -# pylint: disable=unused-argument -def common_build_options(function): - """Decorator for common cli options for host connection.""" - function = click.option( - "--output", - "-o", - # FIXME: set to true during integration - required=False, - type=str, - help="Path to output directory. Overrides configuration.", - )(function) - function = function = click.option( - "--port", - "-p", - required=False, - type=int, - help="The host's port. Overrides configuration.", - )(function) - function = click.option( - "--host", - "-h", - required=False, - type=str, - help="IP address of host. Overrides configuration.", - )(function) - function = click.option( - "--to-binary", - "-b", - type=bool, - is_flag=True, - default=False, - help="If set, all received data will be stored in binary format.", - )(function) - function = click.option( - "--no-decode", - type=bool, - is_flag=True, - default=False, - help="If set, no decoding of received data will be done.", - )(function) - function = click.option( - "--dcf-version", - type=int, - required=False, - help="Version of the DCF protocol to use. Overrides configuration.", - )(function) - return function - - -@click.command(help=add_disclaimer_text("Fetch Topic Definition Files from target.")) -@common_build_options -def fetch_tdf( - output: str, - host: str = None, - port: int = None, - dcf_version: int = None, - to_binary: bool = False, - no_decode: bool = False, -): - """Start client, fetch and save TDF files. \ - Storage location is read from configuration file or optional argument.""" - print_function_args() - - # config_handler = new_configuration_handler_with_override(output, host, port, dcf_version) - - # fetch_tdf_command = FetchTdfCommand( - # config_handler=config_handler, to_binary=to_binary, no_decode=no_decode - # ) - # fetch_tdf_command.run() - # # Save tdf output directory to settings file. - # settings_handler = CachedSettingsHandler() - # settings_handler.latest_tdf_directory = fetch_tdf_command.destination_directory - - -@click.command( - help=add_disclaimer_text( - "Subscribe to one or more hostlog/DCF topics and start receiving and decoding messages." - ) -) -@common_build_options -@click.option( - "--topics", - "-t", - type=str, - required=False, - default="", - help=( - "Topic subscriptions as a comma separated string ':'." - + " E.g. '1:0,1:2,2:0,2:1'" - + " (Selected topics must be described in TDFs)." - + " Optional. If not provided, all topics in given TDFs will be subscribed to." - ), -) -# @click.option( -# "--visualize", -# type=bool, -# is_flag=True, -# default=False, -# help="If set, then visualization will start at the same time as logging", -# ) -# FIXME: Add more help text regarding configuration of dissector. -# @click.option( -# "--create-dissector", -# type=str, -# help="If set, a Wireshark dissector is created based on configuration TBD.", -# ) -@click.option( - "--to-hdf5", - type=bool, - is_flag=True, - default=False, - help="If set, decoded data will be saved to HDF5 file in the output directory.", -) -@click.option( - "--to-text", - type=bool, - is_flag=True, - default=False, - help="If set, decoded data will be saved to text file in the output directory.", -) -@click.option( - "--definitions", - "-d", - type=str, - required=False, - help=( - "Path to Topic Definition File(s) describing all topics that can be subscribed to." - + " If path is a directory then all its *.yaml files will be loaded." - + " Optional: If no argument is given," - + " the most recently fetched TDF directory will be used." - ), -) -@click.option( - "--config", - "-c", - type=str, - required=False, - default="", - help=( - "Path to configuration file generated by frontend UI." - + " N.B. This configuration will override arguments '--config' and '--topics'" - ), -) -@click.option( - "--max-messages", - type=int, - required=False, - help=("Maximum number of messages to log."), -) -# @optgroup.group( -# "Maximum logging time.", -# cls=MutuallyExclusiveOptionGroup, -# help="Mutually exclusive parameters for maximum logging time.", -# ) -# @optgroup.option( -# "--max-time-s", -# type=int, -# help=("Maximum logging time in seconds."), -# ) -# @optgroup.option( -# "--max-time-m", -# type=float, -# help=("Maximum logging time in minutes."), -# ) -# @optgroup.option( -# "--max-time-h", -# type=float, -# help=("Maximum logging time in hours."), -# ) -# @optgroup.group( -# "Maximum amount of logged data.", -# cls=MutuallyExclusiveOptionGroup, -# help="Mutually exclusive parameters group for maximum amount of logged data.", -# ) -# @optgroup.option( -# "--max-kbytes", -# type=float, -# help=("Maximum number of kilobytes to log."), -# ) -# @optgroup.option( -# "--max-mbytes", -# type=float, -# help=("Maximum number of megabytes to log."), -# ) -# @optgroup.option( -# "--max-gbytes", -# type=float, -# help=("Maximum number of gigabytes to log."), -# ) -# TODO: keep or not to keep "--enable-multiprocessing" -# @click.option( -# "--enable-multiprocessing", -# type=bool, -# is_flag=True, -# default=False, -# help="If set, multiprocessing decoding will be disabled.", -# ) -def start_logging( - output: str, - definitions: Union[str, Path], - topics: str = "", - visualize: bool = False, - create_dissector: str = None, - host: str = None, - port: int = None, - dcf_version: int = None, - to_hdf5: bool = False, - to_binary: bool = False, - no_decode: bool = False, - to_text: bool = False, - config: str = "", - max_messages: int = None, - max_time_s: int = None, - max_time_m: int = None, - max_time_h: int = None, - max_kbytes: int = None, - max_mbytes: int = None, - max_gbytes: int = None, - enable_multiprocessing: bool = None, -): - """Method for cli command to start streaming host logging.""" - print_function_args() - - # config_handler = new_configuration_handler_with_override( - # output, - # host, - # port, - # dcf_version, - # enable_multiprocessing, - # ) - - # ###### frontend configuration file - # _topics = [] - # if config: - # # override '--topics' and '--definitions' - # frontend_config_handler = FrontendConfigHandler(config) - # definitions = frontend_config_handler.topic_collection - # if not Path(definitions).is_absolute(): - # definitions = Path(config_handler.output.directory).joinpath("tdf", definitions) - # _topics = frontend_config_handler.selected_topics - # elif topics != "": - # # Only true if topics are used and no UI config file. - # _topics = TopicsArgParser.topic_arg_to_topics(topics) - # # If no-decode true then configuration files are not necessary. - # if no_decode: - # hostlog_configuration_files = [] - # else: - # ######## If '--config' and '--contend_config' are not set, use latest fetched tdfs #### - # if not (definitions or config): - # definitions = CachedSettingsHandler.get_cached_configuration_path() - - # ####### Fetch all tdf configuration files. ########## - # hostlog_configuration_files = yaml_files_in_directory(Path(definitions)) - - # ####### Max data to log. ####### - # max_log_data = MaxLogData.new_instance( - # max_time_s=max_time_s, - # max_time_m=max_time_m, - # max_time_h=max_time_h, - # max_messages=max_messages, - # max_kbytes=max_kbytes, - # max_mbytes=max_mbytes, - # max_gbytes=max_gbytes, - # ) - - # start_logging_command = StartLoggingCommand( - # config_handler=config_handler, - # hostlog_config_files=hostlog_configuration_files, - # topics=_topics, - # to_binary=to_binary, - # no_decode=no_decode, - # to_hdf5=to_hdf5, - # to_text=to_text, - # max_log_data=max_log_data, - # ) - # start_logging_command.run() - - -# class TopicsArgParser: -# """Class handling parsing selected topics argument string.""" - -# @staticmethod -# def topic_arg_to_topics(topics_str: str) -> List[Topic]: -# """Parse arg string to list of Topics. - -# Expected arg string format: ',1:2,2:3,.....' - -# Returns: -# List[Topic]: A sorted list of topics. -# """ -# return TopicsArgParser._to_topics(TopicsArgParser._parse_topics_arg(topics_str)) - -# @staticmethod -# def _parse_topics_arg(topics_str: str) -> List[Tuple]: -# topics = [] -# parse_erro_msg = "Error parsing topics argument:" -# for tuple_str in topics_str.split(","): -# topic_tuple = literal_eval(tuple_str.strip().replace(":", ",")) -# if not isinstance(topic_tuple, tuple): -# raise ValueError(f"{parse_erro_msg} Expected 'int:int' but found {tuple_str!r}") -# if not len(topic_tuple) == 2: -# raise ValueError( -# ( -# f"{parse_erro_msg} Expected 2 elements but found {len(topic_tuple)!r}" -# + f" when parsing {tuple_str!r}." -# ) -# ) -# if not all(isinstance(element, int) for element in topic_tuple): -# raise ValueError(f"{parse_erro_msg} Expected int but found {topic_tuple!r}") -# topics.append(topic_tuple) -# # Remove duplicates -# return sorted(list(set(topics))) - -# @staticmethod -# def _to_topics(topics: List[Tuple]) -> List[Topic]: -# return [Topic(*i) for i in topics] - - -# class FrontendConfigHandler: -# """Class providing configuration from file generated by the frontend.""" - -# def __init__(self, config_file: str): -# """Initialize object. - -# Args: -# config_file (str): Path to configuration file generated by the selected topics UI. -# """ -# self._config: dict = self._read(Path(config_file)) - -# @staticmethod -# def _read(config_file: Path) -> dict: -# config_reader = ConfigurationReader() -# config_reader.read_configuration(config_file) -# return config_reader.configuration - -# @property -# def selected_topics(self) -> List[Topic]: -# """Return selected topics from configuration file.""" -# result = [] -# _selected_topics = self._config["selected_topics"] -# for channel_topic in _selected_topics: -# channel_id = channel_topic["channel"] -# for _topic in channel_topic["topics"]: -# result.append(Topic(channel_id=int(channel_id), topic_id=int(_topic))) -# return result - -# @property -# def topic_collection(self) -> Path: -# """Return topic collection.""" -# return Path(self._config["topic_collection"]) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 2a62f15..377d22c 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -2,9 +2,7 @@ from __future__ import annotations import os -from ast import literal_eval -from pathlib import Path -from typing import List, Tuple, Union +from typing import List import click import requests @@ -14,7 +12,6 @@ from cdevents.cli.utils import ( add_disclaimer_text, print_function_args, - yaml_files_in_directory, ) @@ -82,7 +79,6 @@ def started( "buildartifactid": artifact, }, } - #TODO: add "datacontenttype" event = CloudEvent(attributes, dict(data)) headers, body = to_structured(event) @@ -109,7 +105,6 @@ def finished( "buildartifactid": artifact, }, } - #TODO: add "datacontenttype" event = CloudEvent(attributes, dict(data)) headers, body = to_structured(event) @@ -135,7 +130,6 @@ def queued( "buildartifactid": artifact, }, } - #TODO: add "datacontenttype" event = CloudEvent(attributes, dict(data)) headers, body = to_structured(event) diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py new file mode 100644 index 0000000..a676626 --- /dev/null +++ b/cli/cdevents/cli/env.py @@ -0,0 +1,137 @@ +"""Module for cli environment commands.""" +from __future__ import annotations +import os + +from typing import List + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, +) + + +# pylint: disable=unused-argument +def common_env_options(function): + """Decorator for common cli options for environment.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Environment's Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Environment's Name.", + )(function) + function = click.option( + "--repo", + "-r", + required=False, + type=str, + help="Environment's RepoUrl.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str,str), + multiple=True, + help="Environment's Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("Environment Created CloudEvent.")) +@common_env_options +def created( + cde_sink: str, + id: str, + name: str = None, + repo: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.environment.created.v1", + "source": "cde-cli", + "extensions": { + "envId": id, + "envname": name, + "envrepourl": repo, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) +@common_env_options +def deleted( + cde_sink: str, + id: str, + name: str = None, + repo: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.environment.deleted.v1", + "source": "cde-cli", + "extensions": { + "envId": id, + "envname": name, + "envrepourl": repo, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + + +@click.command(help=add_disclaimer_text("Environment Modified CloudEvent.")) +@common_env_options +def modified( + cde_sink: str, + id: str, + name: str = None, + repo: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.environment.modified.v1", + "source": "cde-cli", + "extensions": { + "envId": id, + "envname": name, + "envrepourl": repo, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py new file mode 100644 index 0000000..c7deadc --- /dev/null +++ b/cli/cdevents/cli/pipelinerun.py @@ -0,0 +1,161 @@ +"""Module for cli pipelinerun commands.""" +from __future__ import annotations +import os + +from typing import List + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, +) + + +# pylint: disable=unused-argument +def common_pipelinerun_options(function): + """Decorator for common cli options for pipelinerun.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Pipeline Run Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Pipeline Run's Name.", + )(function) + function = click.option( + "--status", + "-s", + required=False, + type=str, + help="Pipeline Run's Status.", + )(function) + function = click.option( + "--url", + "-u", + required=False, + type=str, + help="Pipeline Run's URL.", + )(function) + function = click.option( + "--errors", + "-e", + required=False, + type=str, + help="Pipeline Run's Errors.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str,str), + multiple=True, + help="Pipeline Run's Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("PipelineRun Started CloudEvent.")) +@common_pipelinerun_options +def started( + cde_sink: str, + id: str, + name: str = None, + status: str = None, + url: str = None, + errors: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.pipelinerun.started.v1", + "source": "cde-cli", + "extensions": { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("PipelineRun Finished CloudEvent.")) +@common_pipelinerun_options +def finished( + cde_sink: str, + id: str, + name: str = None, + status: str = None, + url: str = None, + errors: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.pipelinerun.finished.v1", + "source": "cde-cli", + "extensions": { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) +@common_pipelinerun_options +def queued( + cde_sink: str, + id: str, + name: str = None, + status: str = None, + url: str = None, + errors: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.pipelinerun.queued.v1", + "source": "cde-cli", + "extensions": { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py new file mode 100644 index 0000000..aee4596 --- /dev/null +++ b/cli/cdevents/cli/service.py @@ -0,0 +1,160 @@ +"""Module for cli service commands.""" +from __future__ import annotations +import os + +from typing import List + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, +) + + +# pylint: disable=unused-argument +def common_service_options(function): + """Decorator for common cli options for service.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--envid", + "-e", + required=False, + type=str, + help="Environment Id where the Service is running.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Service's Name.", + )(function) + function = click.option( + "--version", + "-v", + required=False, + type=str, + help="Service's Version.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str,str), + multiple=True, + help="Service's Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("Service Deployed CloudEvent.")) +@common_service_options +def deployed( + cde_sink: str, + envid: str, + name: str = None, + version: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.service.deployed.v1", + "source": "cde-cli", + "extensions": { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("Service Upgraded CloudEvent.")) +@common_service_options +def upgraded( + cde_sink: str, + envid: str, + name: str = None, + version: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.service.upgraded.v1", + "source": "cde-cli", + "extensions": { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) +@common_service_options +def removed( + cde_sink: str, + envid: str, + name: str = None, + version: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.service.removed.v1", + "source": "cde-cli", + "extensions": { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) +@common_service_options +def rolledback( + cde_sink: str, + envid: str, + name: str = None, + version: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.service.rolledback.v1", + "source": "cde-cli", + "extensions": { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py new file mode 100644 index 0000000..d671d88 --- /dev/null +++ b/cli/cdevents/cli/taskrun.py @@ -0,0 +1,110 @@ +"""Module for cli taskrun commands.""" +from __future__ import annotations +import os + +from typing import List + +import click +import requests + +from cloudevents.http import CloudEvent, to_structured + +from cdevents.cli.utils import ( + add_disclaimer_text, + print_function_args, +) + + +# pylint: disable=unused-argument +def common_taskrun_options(function): + """Decorator for common cli options for taskrun.""" + function = click.option( + "--cde_sink", + "-c", + required=False, + type=str, + default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), + help="CDE_SINK", + )(function) + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Task Run Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Task Run's Name.", + )(function) + function = click.option( + "--pipelineid", + "-p", + required=False, + type=str, + help="Task Run's Pipeline Id.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str,str), + multiple=True, + help="Task Run's Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("TaskRun Started CloudEvent.")) +@common_taskrun_options +def started( + cde_sink: str, + id: str, + name: str = None, + pipelineid: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.taskrun.started.v1", + "source": "cde-cli", + "extensions": { + "taskrunid": id, + "taskrunname": name, + "taskrunpipelineid": pipelineid, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) + +@click.command(help=add_disclaimer_text("TaskRun Finished CloudEvent.")) +@common_taskrun_options +def finished( + cde_sink: str, + id: str, + name: str = None, + pipelineid: str = None, + data :List[str] = None, +): + print_function_args() + attributes = { + "type": "cd.taskrun.finished.v1", + "source": "cde-cli", + "extensions": { + "taskrunid": id, + "taskrunname": name, + "taskrunpipelineid": pipelineid, + }, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + + # send and print event + requests.post(cde_sink, headers=headers, data=body) From 432ef85a46c6441056bcec2b93bb0af764971721 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Mon, 11 Jul 2022 14:15:18 +0200 Subject: [PATCH 07/34] Update Makefile --- .pylintrc | 570 ++++++++++++++++++++++++++++++++ Makefile | 9 +- README.md | 2 +- cli/cdevents/cli/__main__.py | 36 +- cli/cdevents/cli/artifact.py | 17 +- cli/cdevents/cli/branch.py | 15 +- cli/cdevents/cli/build.py | 19 +- cli/cdevents/cli/env.py | 18 +- cli/cdevents/cli/pipelinerun.py | 18 +- cli/cdevents/cli/service.py | 21 +- cli/cdevents/cli/taskrun.py | 15 +- cli/cdevents/cli/utils.py | 3 +- cli/setup.cfg | 59 ++-- requirements/test.txt | 5 +- targets.mk | 49 +-- 15 files changed, 705 insertions(+), 151 deletions(-) create mode 100644 .pylintrc diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..2f23bcf --- /dev/null +++ b/.pylintrc @@ -0,0 +1,570 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=10.0 + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against paths and can be in Posix or Windows format. +ignore-paths= + +# Files or directories matching the regex patterns are skipped. The regex +# matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.9 + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + fixme, + todo, + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'error', 'warning', 'refactor', and 'convention' +# which contain the number of messages in each category, as well as 'statement' +# which is the total number of statements analyzed. This score is used by the +# global evaluation report (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +#notes-rgx= + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear and the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# class is considered mixin if its name matches the mixin-class-rgx option. +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins ignore-mixin- +# members is set to 'yes' +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=no + +# Signatures are removed from the similarity computation +ignore-signatures=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/Makefile b/Makefile index 95c6411..4b104dd 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ include header.mk -PACKAGES = template core web cli +PACKAGES = cli export ABS_ROOT_PATH=$(shell pwd) .PHONY: packages $(PACKAGES) @@ -50,13 +50,6 @@ format: $(FORMATPACKAGES) $(FORMATPACKAGES): $(MAKE) -C $(@:format-%=%) format -install: ## Installs dependencies from requirements.txt - pip install -r ./requirements - pre-commit install - -internal-install: ## Installs VCC-internal dependencies from vcc-requirements.txt - pip install --extra-index-url https://TODO -r vccinternal-requirements.txt - check: ## Runs pre-commit hooks on all files pre-commit run --all-files diff --git a/README.md b/README.md index 31288e0..eb5e4b7 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,4 @@ Python SDK for CDEvents -update ... \ No newline at end of file +update ... diff --git a/cli/cdevents/cli/__main__.py b/cli/cdevents/cli/__main__.py index 3db94e7..da1aa75 100644 --- a/cli/cdevents/cli/__main__.py +++ b/cli/cdevents/cli/__main__.py @@ -6,17 +6,25 @@ import click import yaml +from cdevents.cli.artifact import packaged, published +from cdevents.cli.branch import created as branch_created +from cdevents.cli.branch import deleted as branch_deleted +from cdevents.cli.build import finished, queued, started from cdevents.cli.constants import LOGGING_CONFIGURATION_FILE +from cdevents.cli.env import created as env_created +from cdevents.cli.env import deleted as env_deleted +from cdevents.cli.env import modified as env_modified +from cdevents.cli.pipelinerun import finished as pipe_finished +from cdevents.cli.pipelinerun import queued as pipe_queued +from cdevents.cli.pipelinerun import started as pipe_started +from cdevents.cli.service import deployed as service_deployed +from cdevents.cli.service import removed as service_removed +from cdevents.cli.service import rolledback as service_rolledback +from cdevents.cli.service import upgraded as service_upgraded +from cdevents.cli.taskrun import finished as taskrun_finished +from cdevents.cli.taskrun import started as taskrun_started from cdevents.cli.utils import add_disclaimer_text -from cdevents.cli.build import finished, queued, started -from cdevents.cli.artifact import packaged, published -from cdevents.cli.branch import created as branch_created, deleted as branch_deleted -from cdevents.cli.env import created as env_created, deleted as env_deleted, modified as env_modified -from cdevents.cli.pipelinerun import started as pipe_started, finished as pipe_finished, queued as pipe_queued -from cdevents.cli.service import deployed as service_deployed, upgraded as service_upgraded, removed as service_removed, rolledback as service_rolledback -from cdevents.cli.taskrun import started as taskrun_started, finished as taskrun_finished - def configure_logging(): """Configures logging from file.""" @@ -29,6 +37,7 @@ def configure_logging(): def build(): """Click group for command 'build'.""" + build.add_command(finished) build.add_command(queued) build.add_command(started) @@ -38,6 +47,7 @@ def build(): def artifact(): """Click group for command 'artifact'.""" + artifact.add_command(packaged) artifact.add_command(published) @@ -46,6 +56,7 @@ def artifact(): def branch(): """Click group for command 'branch'.""" + branch.add_command(branch_created) branch.add_command(branch_deleted) @@ -54,27 +65,27 @@ def branch(): def env(): """Click group for command 'environment'.""" + env.add_command(env_created) env.add_command(env_deleted) env.add_command(env_modified) - - @click.group(help=add_disclaimer_text("""Commands PipelineRun related CloudEvent.""")) def pipelinerun(): """Click group for command 'environment'.""" + pipelinerun.add_command(pipe_started) pipelinerun.add_command(pipe_finished) pipelinerun.add_command(pipe_queued) - @click.group(help=add_disclaimer_text("""Commands Service related CloudEvent.""")) def service(): """Click group for command 'service'.""" + service.add_command(service_deployed) service.add_command(service_upgraded) service.add_command(service_removed) @@ -85,12 +96,11 @@ def service(): def taskrun(): """Click group for command 'taskrun'.""" + taskrun.add_command(taskrun_started) taskrun.add_command(taskrun_finished) - - @click.group( help=add_disclaimer_text( """Main entry point for cdevents client cli. diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 439f208..596c8cc 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -1,18 +1,14 @@ """Module for cli artifact commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -51,7 +47,7 @@ def common_artifact_options(function): "--data", "-d", required=False, - type=(str,str), + type=(str, str), multiple=True, help="Artifact Data.", )(function) @@ -66,7 +62,7 @@ def packaged( id: str, name: str = None, version: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -84,6 +80,7 @@ def packaged( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("Artifact Published CloudEvent.")) @common_artifact_options def published( @@ -91,7 +88,7 @@ def published( id: str, name: str = None, version: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -107,4 +104,4 @@ def published( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) \ No newline at end of file + requests.post(cde_sink, headers=headers, data=body) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index b623b89..b1c73fd 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -1,18 +1,14 @@ """Module for cli branch commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -51,7 +47,7 @@ def common_branch_options(function): "--data", "-d", required=False, - type=(str,str), + type=(str, str), multiple=True, help="Branch Data.", )(function) @@ -66,7 +62,7 @@ def created( id: str, name: str = None, repoid: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -92,7 +88,7 @@ def deleted( id: str, name: str = None, repoid: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -109,4 +105,3 @@ def deleted( # send and print event requests.post(cde_sink, headers=headers, data=body) - diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 377d22c..f8ab20b 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -1,18 +1,14 @@ """Module for cli build commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -51,8 +47,8 @@ def common_build_options(function): "--data", "-d", required=False, - #type=click.Tuple([str, str]), - type=(str,str), + # type=click.Tuple([str, str]), + type=(str, str), multiple=True, help="Build Data.", )(function) @@ -67,7 +63,7 @@ def started( id: str, name: str = None, artifact: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -93,7 +89,7 @@ def finished( id: str, name: str = None, artifact: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -111,6 +107,7 @@ def finished( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_build_options def queued( @@ -118,7 +115,7 @@ def queued( id: str, name: str = None, artifact: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index a676626..983b1f7 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -1,18 +1,14 @@ """Module for cli environment commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -51,7 +47,7 @@ def common_env_options(function): "--data", "-d", required=False, - type=(str,str), + type=(str, str), multiple=True, help="Environment's Data.", )(function) @@ -66,7 +62,7 @@ def created( id: str, name: str = None, repo: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -84,6 +80,7 @@ def created( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) @common_env_options def deleted( @@ -91,7 +88,7 @@ def deleted( id: str, name: str = None, repo: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -117,7 +114,7 @@ def modified( id: str, name: str = None, repo: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -134,4 +131,3 @@ def modified( # send and print event requests.post(cde_sink, headers=headers, data=body) - diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index c7deadc..42115c8 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -1,18 +1,14 @@ """Module for cli pipelinerun commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -65,7 +61,7 @@ def common_pipelinerun_options(function): "--data", "-d", required=False, - type=(str,str), + type=(str, str), multiple=True, help="Pipeline Run's Data.", )(function) @@ -82,7 +78,7 @@ def started( status: str = None, url: str = None, errors: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -102,6 +98,7 @@ def started( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("PipelineRun Finished CloudEvent.")) @common_pipelinerun_options def finished( @@ -111,7 +108,7 @@ def finished( status: str = None, url: str = None, errors: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -131,6 +128,7 @@ def finished( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_pipelinerun_options def queued( @@ -140,7 +138,7 @@ def queued( status: str = None, url: str = None, errors: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index aee4596..73f1406 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -1,18 +1,14 @@ """Module for cli service commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -51,7 +47,7 @@ def common_service_options(function): "--data", "-d", required=False, - type=(str,str), + type=(str, str), multiple=True, help="Service's Data.", )(function) @@ -66,7 +62,7 @@ def deployed( envid: str, name: str = None, version: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -84,6 +80,7 @@ def deployed( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("Service Upgraded CloudEvent.")) @common_service_options def upgraded( @@ -91,7 +88,7 @@ def upgraded( envid: str, name: str = None, version: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -109,6 +106,7 @@ def upgraded( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) @common_service_options def removed( @@ -116,7 +114,7 @@ def removed( envid: str, name: str = None, version: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -134,6 +132,7 @@ def removed( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) @common_service_options def rolledback( @@ -141,7 +140,7 @@ def rolledback( envid: str, name: str = None, version: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index d671d88..ea41533 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -1,18 +1,14 @@ """Module for cli taskrun commands.""" from __future__ import annotations -import os +import os from typing import List import click import requests - from cloudevents.http import CloudEvent, to_structured -from cdevents.cli.utils import ( - add_disclaimer_text, - print_function_args, -) +from cdevents.cli.utils import add_disclaimer_text, print_function_args # pylint: disable=unused-argument @@ -51,7 +47,7 @@ def common_taskrun_options(function): "--data", "-d", required=False, - type=(str,str), + type=(str, str), multiple=True, help="Task Run's Data.", )(function) @@ -66,7 +62,7 @@ def started( id: str, name: str = None, pipelineid: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { @@ -84,6 +80,7 @@ def started( # send and print event requests.post(cde_sink, headers=headers, data=body) + @click.command(help=add_disclaimer_text("TaskRun Finished CloudEvent.")) @common_taskrun_options def finished( @@ -91,7 +88,7 @@ def finished( id: str, name: str = None, pipelineid: str = None, - data :List[str] = None, + data: List[str] = None, ): print_function_args() attributes = { diff --git a/cli/cdevents/cli/utils.py b/cli/cdevents/cli/utils.py index 7a7df6e..a252249 100644 --- a/cli/cdevents/cli/utils.py +++ b/cli/cdevents/cli/utils.py @@ -113,7 +113,8 @@ def is_windows() -> bool: def _os_name() -> str: return os.name -#TODO: Update disclaimer text + +# TODO: Update disclaimer text DISCLAIMER_TEXT = """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! N.B. Due to data privacy regulations, all locally generated cdevents data files ,such as hdf5 etc, must be deleted after a logging session is finished. diff --git a/cli/setup.cfg b/cli/setup.cfg index 882c407..5c06369 100644 --- a/cli/setup.cfg +++ b/cli/setup.cfg @@ -13,52 +13,51 @@ author_email = info@dowhile.com keywords = cdevents, cli url = todo classifiers = - Development Status :: 3 - Alpha - Intended Audience :: Developers - License :: Other/Proprietary License - Natural Language :: English - Operating System :: OS Independent - Programming Language :: Python :: 3 - Programming Language :: Python :: 3.5 - Programming Language :: Python :: 3.6 - Programming Language :: Python :: 3.7 - Programming Language :: Python :: 3.9 - Topic :: Software Development :: Libraries :: Python Modules + Development Status :: 3 - Alpha + Intended Audience :: Developers + License :: Other/Proprietary License + Natural Language :: English + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.9 + Topic :: Software Development :: Libraries :: Python Modules [options] packages = find_namespace: zip_safe = False include_package_data = True install_requires = - click>=8.0.4 - pyyaml>=6.0 - click-option-group - requests - cloudevents + click>=8.0.4 + pyyaml>=6.0 + click-option-group + requests + cloudevents [options.extras_require] dev = - black - bump2version - isort - mypy - pre-commit - pydocstyle - pytest - pytest_mock - yamllint - pylint - + black + bump2version + isort + mypy + pre-commit + pydocstyle + pytest + pytest_mock + yamllint + pylint build = - wheel + wheel [options.packages.find] include = - cdevents.* + cdevents.* [bdist_wheel] universal = 0 [options.entry_points] console_scripts = - cdevents = cdevents.cli.__main__:cli + cdevents = cdevents.cli.__main__:cli diff --git a/requirements/test.txt b/requirements/test.txt index 9178c0c..c962aa3 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,7 +1,8 @@ -flake8 +flake8==4.0.1 pep8-naming flake8-import-order flake8-print flake8-strict -pytest +pytest==7.1.2 +pytest-mock==3.7.0 pytest-cov diff --git a/targets.mk b/targets.mk index 0e3df07..7705d88 100644 --- a/targets.mk +++ b/targets.mk @@ -1,6 +1,31 @@ help: @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) +clean: clean-build clean-pyc clean-test clean-mypy ## remove all build, test, coverage and Python artifacts + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + # N.B. line below removes editable intallation of package in venv + # find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -f .coverage + rm -fr htmlcov/ + rm -fr .pytest_cache + +clean-mypy: ## remove MyPy cache files + rm -fr .mypy_cache/ + + init: clean ## install the package in editable mode including dev dependencies pip install -e .[dev] pre-commit install @@ -33,30 +58,6 @@ lint: ## run pylint exit "$${exit_code}" fi -clean: clean-build clean-pyc clean-test clean-mypy ## remove all build, test, coverage and Python artifacts - -clean-build: ## remove build artifacts - rm -fr build/ - rm -fr dist/ - rm -fr .eggs/ - # N.B. line below removes editable intallation of package in venv - # find . -name '*.egg-info' -exec rm -fr {} + - find . -name '*.egg' -exec rm -f {} + - -clean-pyc: ## remove Python file artifacts - find . -name '*.pyc' -exec rm -f {} + - find . -name '*.pyo' -exec rm -f {} + - find . -name '*~' -exec rm -f {} + - find . -name '__pycache__' -exec rm -fr {} + - -clean-test: ## remove test and coverage artifacts - rm -f .coverage - rm -fr htmlcov/ - rm -fr .pytest_cache - -clean-mypy: ## remove MyPy cache files - rm -fr .mypy_cache/ - bump = patch bumpversion: ## Bumps the (default: patch) version of this package. To bump minor or major, add bump=minor or bump=major to the make call. bumpversion --allow-dirty $(bump) From 387cea87a1928906cdffdf93e15a5c924c856225 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Tue, 12 Jul 2022 12:53:18 +0200 Subject: [PATCH 08/34] Update docker files & commands --- Dockerfile | 8 +------- Makefile | 6 +++--- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/Dockerfile b/Dockerfile index ac1888b..e65f1d6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,18 +1,12 @@ # syntax=docker/dockerfile:1 -FROM python:3.8 +FROM python:3.9.12-slim-buster # Setup environment RUN apt-get update && apt-get install -y \ python3-distutils \ build-essential -# Copy requirements -COPY ./requirements ./requirements - -# Installing requirements -RUN pip install -r ./requirements - # Copy needed files (see .dockerignore for what will be included) COPY . /cdevents-client diff --git a/Makefile b/Makefile index 4b104dd..a94003e 100644 --- a/Makefile +++ b/Makefile @@ -54,10 +54,10 @@ check: ## Runs pre-commit hooks on all files pre-commit run --all-files docker-build: ## Build and package Docker container - docker build -t cdevents-client -f Dockerfile . + docker build -t cdevents -f Dockerfile . -docker-shell: ## Opens a shell - docker run --add-host=host.docker.internal:host-gateway --volume /"$(shell pwd)"/output/:/root/cdevents-client/ -it cdevents-client bash +docker-shell: ## Opens a bash + docker run --rm --network host --volume $(pwd)/output/:/root/cdevents-client/ -it cdevents bash .PHONY: packages $(PACKAGES) .PHONY: packages $(INITPACKAGES) From 7cb769bb9f30072ebfed79fc817416f42715e1c1 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Fri, 15 Jul 2022 11:46:46 +0200 Subject: [PATCH 09/34] Read from configuration --- cli/cdevents/cli/artifact.py | 54 +++----- cli/cdevents/cli/branch.py | 9 +- cli/cdevents/cli/build.py | 12 +- cli/cdevents/cli/cdevents_command.py | 44 +++++++ cli/cdevents/cli/configuration_handler.py | 122 ++++++++++++++++++ cli/cdevents/cli/configuration_reader.py | 87 +++++++++++++ cli/cdevents/cli/constants.py | 4 - cli/cdevents/cli/env.py | 11 +- cli/cdevents/cli/pipelinerun.py | 11 +- cli/cdevents/cli/service.py | 14 +- cli/cdevents/cli/taskrun.py | 8 +- cli/cdevents/configuration/configuration.yaml | 17 +-- 12 files changed, 318 insertions(+), 75 deletions(-) create mode 100644 cli/cdevents/cli/cdevents_command.py create mode 100644 cli/cdevents/cli/configuration_handler.py create mode 100644 cli/cdevents/cli/configuration_reader.py diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 596c8cc..53e4e6c 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -5,23 +5,13 @@ from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_artifact_options(function): """Decorator for common cli options for artifact.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--id", "-i", @@ -58,50 +48,36 @@ def common_artifact_options(function): @click.command(help=add_disclaimer_text("Artifact Packaged CloudEvent.")) @common_artifact_options def packaged( - cde_sink: str, id: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.artifact.packaged.v1", - "source": "cde-cli", - "extensions": { - "artifactid": id, - "artifactname": name, - "artifactversion": version, - }, + artifact_packaged_eventV1 = "cd.artifact.packaged.v1" + extensions = { + "artifactid": id, + "artifactname": name, + "artifactversion": version, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - - # send and print event - requests.post(cde_sink, headers=headers, data=body) + cdevents_command = CDeventsCommand() + cdevents_command.run(artifact_packaged_eventV1, extensions, data) @click.command(help=add_disclaimer_text("Artifact Published CloudEvent.")) @common_artifact_options def published( - cde_sink: str, id: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.artifact.published.v1", - "source": "cde-cli", - "extensions": { - "artifactid": id, - "artifactname": name, - "artifactversion": version, - }, + artifact_published_eventV1 = "cd.artifact.published.v1" + extensions = { + "artifactid": id, + "artifactname": name, + "artifactversion": version, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - - # send and print event - requests.post(cde_sink, headers=headers, data=body) + cdevents_command = CDeventsCommand() + cdevents_command.run(artifact_published_eventV1, extensions, data) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index b1c73fd..7090b6e 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -1,6 +1,7 @@ """Module for cli branch commands.""" from __future__ import annotations +import logging import os from typing import List @@ -10,6 +11,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args +_log = logging.getLogger(__name__) # pylint: disable=unused-argument def common_branch_options(function): @@ -78,8 +80,8 @@ def created( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) - + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Branch Deleted CloudEvent.")) @common_branch_options @@ -104,4 +106,5 @@ def deleted( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") \ No newline at end of file diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index f8ab20b..8ba8f09 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -1,6 +1,7 @@ """Module for cli build commands.""" from __future__ import annotations +import logging import os from typing import List @@ -10,6 +11,8 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args +_log = logging.getLogger(__name__) + # pylint: disable=unused-argument def common_build_options(function): @@ -79,7 +82,8 @@ def started( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Build Finished CloudEvent.")) @@ -105,7 +109,8 @@ def finished( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @@ -131,4 +136,5 @@ def queued( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") diff --git a/cli/cdevents/cli/cdevents_command.py b/cli/cdevents/cli/cdevents_command.py new file mode 100644 index 0000000..1e9c763 --- /dev/null +++ b/cli/cdevents/cli/cdevents_command.py @@ -0,0 +1,44 @@ +"""Module for cli common command code.""" +import logging +from abc import ABC +import requests + +from cdevents.cli.configuration_handler import ConfigurationHandler +from cloudevents.http import CloudEvent, to_structured +from cdevents.cli.configuration_handler import new_default_configuration_handler + +class CDeventsCommand(ABC): + """Abstract base class for all Hostlog commands.""" + + def __init__(self, config_handler: ConfigurationHandler = None): + """Initializes base class. + + Args: + config_handler (ConfigurationHandler): the configuration handler. + """ + self._log = logging.getLogger(__name__) + self._config_handler = config_handler + if config_handler is None: + self._config_handler = new_default_configuration_handler() + + def run(self, type, extensions, data): + """run command. + """ + attributes = { + "type": type, + "source": self.config_handler.source.name, + "extensions": extensions, + } + event = CloudEvent(attributes, dict(data)) + headers, body = to_structured(event) + cde_link = self.config_handler.client.host + + # send and print event + result = requests.post(cde_link, headers=headers, data=body) + self._log.info(f"Response with state code {result.status_code}") + + + @property + def config_handler(self) -> ConfigurationHandler: + """Property for configuration handler.""" + return self._config_handler diff --git a/cli/cdevents/cli/configuration_handler.py b/cli/cdevents/cli/configuration_handler.py new file mode 100644 index 0000000..0428ccc --- /dev/null +++ b/cli/cdevents/cli/configuration_handler.py @@ -0,0 +1,122 @@ +"""Module for configuration provider.""" +from __future__ import annotations + +import copy +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Union + +from cdevents.cli.configuration_reader import ConfigurationReader +from cdevents.cli.constants import DEAFULT_CONFIGURATION_FILE +from cdevents.cli.utils import DictUtils + + +def get_default_configuration_file() -> str: + """Returns the default configuration file path.""" + return DEAFULT_CONFIGURATION_FILE + +def new_default_configuration_handler() -> ConfigurationHandler: + """Returnes a configuration handler with the default configuration file""" + config_handler: ConfigurationHandler = ConfigurationHandler.create_new( + get_default_configuration_file() + ) + + return config_handler + + +def new_configuration_handler_with_override( + client_host, source_name +) -> ConfigurationHandler: + """Returnes a configuration handler where args override configuration file.""" + args_as_config = ConfigurationHandler.create_override_config( + client_host=client_host, + source_name=source_name + ) + + config_handler: ConfigurationHandler = ConfigurationHandler.create_new( + get_default_configuration_file(), args_as_config + ) + + return config_handler + + +class ConfigurationHandler: + """Class for providing configuration.""" + + def __init__(self, configuration: dict): + """Initializes the configuration. + + Args: + configuration (dict): The configuration. + """ + self.client = _ClientConfig(**configuration["client"]) + self.source = _SourceConfig(**configuration["source"]) + + @staticmethod + def create_override_config( + client_host: str = None, + source_name: str = None, + ) -> dict: + """Create a dict that can be used for overriding the default configuration. + + Args: + host (str, optional): client host address. Defaults to None. + name (str, optional): source name. Defaults to None. + + Returns: + dict: the dict to ovverride configuration with. + """ + override_dict: dict = {} + if client_host: + DictUtils.merge_dicts({"client": {"host": client_host}}, override_dict) + if source_name: + DictUtils.merge_dicts({"source": {"name": source_name}}, override_dict) + + return override_dict + + @staticmethod + def create_new( + configuration_files: Union[list[str], str] = None, override_config: dict = None + ) -> ConfigurationHandler: + """Reads default configurationfile plus any additional configuration files provided. + + Additional configuration files will be merged with the default configfuration file. + Ovveride configuration will ovverid any configuration from files. + A configuration provider is returned. + + Args: + configuration_files (Union[list[str], str], optional): yaml or json configration file. \ + Defaults to None. + override_config (dict):override configuration from cli args. Defaults to None. + + Returns: + ConfigurationHandler: the handler. + """ + file_list = [] + if isinstance(configuration_files, str) or isinstance(configuration_files, Path): + file_list.append(configuration_files) + elif isinstance(configuration_files, list): + file_list.extend(configuration_files) + + reader = ConfigurationReader() + for _file in file_list: + reader.read_configuration(_file) + + # merge dicts + if override_config: + _config = copy.deepcopy(override_config) + DictUtils.merge_dicts(reader.configuration["configuration"], _config) + else: + _config = reader.configuration["configuration"] + + return ConfigurationHandler(_config) + + +@dataclass +class _ClientConfig: + host: str + +@dataclass +class _SourceConfig: + name: str diff --git a/cli/cdevents/cli/configuration_reader.py b/cli/cdevents/cli/configuration_reader.py new file mode 100644 index 0000000..e8f0c63 --- /dev/null +++ b/cli/cdevents/cli/configuration_reader.py @@ -0,0 +1,87 @@ +# Should support yaml, json file json config string +"""Module for configuration read and provisioning.""" +import copy +import json +import logging +from pathlib import Path +from typing import Union + +import yaml + +from cdevents.cli.utils import DictUtils + + +class ConfigurationReader: + """Handle reading of configuration. + + Configuration source can be provided as file paths or JSON string. + """ + + _YAML_FILE_SUFFIXES = [".yml", ".yaml"] + _JSON_FILE_SUFFIXES = [".json"] + + def __init__(self) -> None: # noqa: D107 + self._configuration: dict = {} + self._log = logging.getLogger(__name__) + + @property + def configuration(self) -> dict: + """Returns a deep copy of the configuration dict.""" + return copy.deepcopy(self._configuration) + + @configuration.setter + def configuration(self, configuration: dict): + """Merge existing configuration with new configuration. + + If the new configuration have the same corresponding keys, + the new configuration will overwrite the previous. + + Args: + configuration (dict): _description_ + """ + _config = copy.deepcopy(configuration) + if not self._configuration: + self._configuration = _config + else: + DictUtils.merge_dicts( + self._configuration, + _config, + ) + self._configuration = _config + + def read_configuration(self, configuration_file: Union[str, Path]): + """Read configuration from file. + + Args: + configuration (Union[str, Path]): Path to configuration file. + + Raises: + FileNotFoundError: Thrown if configuration file does not exist + ValueError: Thrown if file suffix is not supported. + """ + _config_file = Path(configuration_file) + self._log.debug("Reading configuration file '%s'", _config_file) + if not _config_file.exists(): + raise FileNotFoundError(f"Configuration file {_config_file} not found.") + elif self._is_supported_yaml_suffix(_config_file): + self.configuration = yaml.safe_load(_config_file.read_text(encoding="utf-8")) + + elif self._is_supported_json_suffix(_config_file): + self.configuration = json.loads(_config_file.read_text("utf-8")) + + else: + error_msg = ( + f"Unsupported file format {_config_file.suffix!r}," + + f" Supported formats: {self._YAML_FILE_SUFFIXES+self._JSON_FILE_SUFFIXES!r}" + ) + self._log.error(error_msg) + raise ValueError(error_msg) + self._log.debug("Configuration: '%s'", self.configuration) + + @staticmethod + def _is_supported_json_suffix(_config_file: Path) -> bool: + return _config_file.suffix.lower() in ConfigurationReader._JSON_FILE_SUFFIXES + + @staticmethod + def _is_supported_yaml_suffix(_config_file: Path) -> bool: + return _config_file.suffix.lower() in ConfigurationReader._YAML_FILE_SUFFIXES diff --git a/cli/cdevents/cli/constants.py b/cli/cdevents/cli/constants.py index 6f04189..63c5b2a 100644 --- a/cli/cdevents/cli/constants.py +++ b/cli/cdevents/cli/constants.py @@ -7,7 +7,3 @@ LOGGING_CONFIGURATION_FILE = str( Path(_CLI_CDEVENTS_DIR, "configuration", "logging-configuration.yaml") ) - -BYTES_IN_KILOBYTES = 1024 -BYTES_IN_MEGABYTES = BYTES_IN_KILOBYTES * BYTES_IN_KILOBYTES -BYTES_IN_GIGABYTES = BYTES_IN_MEGABYTES * BYTES_IN_KILOBYTES diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index 983b1f7..d7055dd 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -1,6 +1,7 @@ """Module for cli environment commands.""" from __future__ import annotations +import logging import os from typing import List @@ -10,6 +11,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args +_log = logging.getLogger(__name__) # pylint: disable=unused-argument def common_env_options(function): @@ -78,7 +80,8 @@ def created( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) @@ -104,7 +107,8 @@ def deleted( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Environment Modified CloudEvent.")) @@ -130,4 +134,5 @@ def modified( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 42115c8..50dcdb7 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -1,6 +1,7 @@ """Module for cli pipelinerun commands.""" from __future__ import annotations +import logging import os from typing import List @@ -10,6 +11,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args +_log = logging.getLogger(__name__) # pylint: disable=unused-argument def common_pipelinerun_options(function): @@ -96,7 +98,8 @@ def started( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("PipelineRun Finished CloudEvent.")) @@ -126,7 +129,8 @@ def finished( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @@ -156,4 +160,5 @@ def queued( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index 73f1406..98bead1 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -1,6 +1,7 @@ """Module for cli service commands.""" from __future__ import annotations +import logging import os from typing import List @@ -10,6 +11,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args +_log = logging.getLogger(__name__) # pylint: disable=unused-argument def common_service_options(function): @@ -78,7 +80,8 @@ def deployed( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Service Upgraded CloudEvent.")) @@ -104,7 +107,8 @@ def upgraded( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) @@ -130,7 +134,8 @@ def removed( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) @@ -156,4 +161,5 @@ def rolledback( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index ea41533..4db0fd4 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -1,6 +1,7 @@ """Module for cli taskrun commands.""" from __future__ import annotations +import logging import os from typing import List @@ -10,6 +11,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args +_log = logging.getLogger(__name__) # pylint: disable=unused-argument def common_taskrun_options(function): @@ -78,7 +80,8 @@ def started( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") @click.command(help=add_disclaimer_text("TaskRun Finished CloudEvent.")) @@ -104,4 +107,5 @@ def finished( headers, body = to_structured(event) # send and print event - requests.post(cde_sink, headers=headers, data=body) + result = requests.post(cde_sink, headers=headers, data=body) + _log.debug(f"Response with state code {result.status_code}") diff --git a/cli/cdevents/configuration/configuration.yaml b/cli/cdevents/configuration/configuration.yaml index a7acaef..e7fa2e8 100644 --- a/cli/cdevents/configuration/configuration.yaml +++ b/cli/cdevents/configuration/configuration.yaml @@ -1,17 +1,6 @@ --- configuration: - output: - directory: ${HOME}/cdevents_client - utc_timestamps: false - trace_logging: false # Warning: Trace logging is VERY slow!! + source: + name: cde-cli client: - host: 127.0.0.1 - port: 30700 - dcf_version: 4 - timeout_seconds: 5 - max_retries: 3 - process_handling: - enable_multiprocessing: false - enable_worker_logging: false # Warning: logging is VERY slow!! - number_of_workers: -1 # Default is -1. Auto selects number of processes - # after number of physical cores of the host. + host: http://localhost:8080 From 61fec1de14316d88a2b6315dc6ee9b2ac72efb51 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Fri, 15 Jul 2022 14:39:58 +0200 Subject: [PATCH 10/34] Update all services --- cli/cdevents/cli/artifact.py | 9 +-- cli/cdevents/cli/branch.py | 56 +++++-------------- cli/cdevents/cli/build.py | 79 ++++++++------------------ cli/cdevents/cli/env.py | 77 ++++++++------------------ cli/cdevents/cli/pipelinerun.py | 90 ++++++++++-------------------- cli/cdevents/cli/service.py | 98 ++++++++++----------------------- cli/cdevents/cli/taskrun.py | 57 ++++++------------- 7 files changed, 137 insertions(+), 329 deletions(-) diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 53e4e6c..d9bfeef 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -54,14 +54,15 @@ def packaged( data: List[str] = None, ): print_function_args() - artifact_packaged_eventV1 = "cd.artifact.packaged.v1" + artifact_packaged_event_v1 = "cd.artifact.packaged.v1" extensions = { "artifactid": id, "artifactname": name, "artifactversion": version, } + cdevents_command = CDeventsCommand() - cdevents_command.run(artifact_packaged_eventV1, extensions, data) + cdevents_command.run(artifact_packaged_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Artifact Published CloudEvent.")) @@ -73,11 +74,11 @@ def published( data: List[str] = None, ): print_function_args() - artifact_published_eventV1 = "cd.artifact.published.v1" + artifact_published_event_v1 = "cd.artifact.published.v1" extensions = { "artifactid": id, "artifactname": name, "artifactversion": version, } cdevents_command = CDeventsCommand() - cdevents_command.run(artifact_published_eventV1, extensions, data) + cdevents_command.run(artifact_published_event_v1, extensions, data) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index 7090b6e..044e8d5 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -1,29 +1,17 @@ """Module for cli branch commands.""" from __future__ import annotations -import logging import os from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - -_log = logging.getLogger(__name__) +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_branch_options(function): """Decorator for common cli options for branch.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--id", "-i", @@ -60,51 +48,37 @@ def common_branch_options(function): @click.command(help=add_disclaimer_text("Branch Created CloudEvent.")) @common_branch_options def created( - cde_sink: str, id: str, name: str = None, repoid: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.repository.branch.created.v1", - "source": "cde-cli", - "extensions": { - "branchid": id, - "branchname": name, - "branchrepositoryid": repoid, - }, + branch_created_event_v1 = "cd.repository.branch.created.v1" + extensions = { + "branchid": id, + "branchname": name, + "branchrepositoryid": repoid, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(branch_created_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Branch Deleted CloudEvent.")) @common_branch_options def deleted( - cde_sink: str, id: str, name: str = None, repoid: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.repository.branch.deleted.v1", - "source": "cde-cli", - "extensions": { - "branchid": id, - "branchname": name, - "branchrepositoryid": repoid, - }, + branch_deleted_event_v1 = "cd.repository.branch.deleted.v1" + extensions = { + "branchid": id, + "branchname": name, + "branchrepositoryid": repoid, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") \ No newline at end of file + cdevents_command = CDeventsCommand() + cdevents_command.run(branch_deleted_event_v1, extensions, data) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 8ba8f09..61dc0b7 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -1,30 +1,17 @@ """Module for cli build commands.""" from __future__ import annotations -import logging import os from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - -_log = logging.getLogger(__name__) - +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_build_options(function): """Decorator for common cli options for build.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--id", "-i", @@ -62,79 +49,57 @@ def common_build_options(function): @click.command(help=add_disclaimer_text("Build Started CloudEvent.")) @common_build_options def started( - cde_sink: str, id: str, name: str = None, artifact: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.build.started.v1", - "source": "cde-cli", - "extensions": { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - }, + build_started_event_v1 = "cd.build.started.v1" + extensions = { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(build_started_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Build Finished CloudEvent.")) @common_build_options def finished( - cde_sink: str, id: str, name: str = None, artifact: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.build.finished.v1", - "source": "cde-cli", - "extensions": { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - }, + build_finished_event_v1 = "cd.build.finished.v1" + extensions = { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(build_finished_event_v1, extensions, data) @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_build_options def queued( - cde_sink: str, id: str, name: str = None, artifact: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.build.queued.v1", - "source": "cde-cli", - "extensions": { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - }, + build_queued_event_v1 = "cd.build.queued.v1" + extensions = { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(build_queued_event_v1, extensions, data) diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index d7055dd..3e99647 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -1,29 +1,17 @@ """Module for cli environment commands.""" from __future__ import annotations -import logging import os from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - -_log = logging.getLogger(__name__) +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_env_options(function): """Decorator for common cli options for environment.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--id", "-i", @@ -60,79 +48,58 @@ def common_env_options(function): @click.command(help=add_disclaimer_text("Environment Created CloudEvent.")) @common_env_options def created( - cde_sink: str, id: str, name: str = None, repo: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.environment.created.v1", - "source": "cde-cli", - "extensions": { - "envId": id, - "envname": name, - "envrepourl": repo, - }, + environment_created_event_v1 = "cd.environment.created.v1" + extensions = { + "envId": id, + "envname": name, + "envrepourl": repo, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(environment_created_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) @common_env_options def deleted( - cde_sink: str, id: str, name: str = None, repo: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.environment.deleted.v1", - "source": "cde-cli", - "extensions": { - "envId": id, - "envname": name, - "envrepourl": repo, - }, + environment_deleted_event_v1 = "cd.environment.deleted.v1" + extensions = { + "envId": id, + "envname": name, + "envrepourl": repo, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(environment_deleted_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Environment Modified CloudEvent.")) @common_env_options def modified( - cde_sink: str, id: str, name: str = None, repo: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.environment.modified.v1", - "source": "cde-cli", - "extensions": { - "envId": id, - "envname": name, - "envrepourl": repo, - }, + environment_modified_event_v1 = "cd.environment.modified.v1" + extensions = { + "envId": id, + "envname": name, + "envrepourl": repo, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(environment_modified_event_v1, extensions, data) diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 50dcdb7..5b961cd 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -1,29 +1,17 @@ """Module for cli pipelinerun commands.""" from __future__ import annotations -import logging import os from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - -_log = logging.getLogger(__name__) +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_pipelinerun_options(function): """Decorator for common cli options for pipelinerun.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--id", "-i", @@ -74,7 +62,6 @@ def common_pipelinerun_options(function): @click.command(help=add_disclaimer_text("PipelineRun Started CloudEvent.")) @common_pipelinerun_options def started( - cde_sink: str, id: str, name: str = None, status: str = None, @@ -83,29 +70,22 @@ def started( data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.pipelinerun.started.v1", - "source": "cde-cli", - "extensions": { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - }, + pipeline_run_started_event_v1 = "cd.pipelinerun.started.v1" + extensions = { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(pipeline_run_started_event_v1, extensions, data) @click.command(help=add_disclaimer_text("PipelineRun Finished CloudEvent.")) @common_pipelinerun_options def finished( - cde_sink: str, id: str, name: str = None, status: str = None, @@ -114,29 +94,21 @@ def finished( data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.pipelinerun.finished.v1", - "source": "cde-cli", - "extensions": { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - }, + pipeline_run_finished_event_v1 = "cd.pipelinerun.finished.v1" + extensions = { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(pipeline_run_finished_event_v1, extensions, data) @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_pipelinerun_options def queued( - cde_sink: str, id: str, name: str = None, status: str = None, @@ -145,20 +117,14 @@ def queued( data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.pipelinerun.queued.v1", - "source": "cde-cli", - "extensions": { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - }, + pipeline_run_queued_event_v1 = "cd.pipelinerun.queued.v1" + extensions = { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(pipeline_run_queued_event_v1, extensions, data) diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index 98bead1..a984b92 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -1,29 +1,17 @@ """Module for cli service commands.""" from __future__ import annotations -import logging import os from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - -_log = logging.getLogger(__name__) +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_service_options(function): """Decorator for common cli options for service.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--envid", "-e", @@ -60,106 +48,78 @@ def common_service_options(function): @click.command(help=add_disclaimer_text("Service Deployed CloudEvent.")) @common_service_options def deployed( - cde_sink: str, envid: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.service.deployed.v1", - "source": "cde-cli", - "extensions": { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - }, + service_deployed_event_v1 = "cd.service.deployed.v1" + extensions = { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(service_deployed_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Service Upgraded CloudEvent.")) @common_service_options def upgraded( - cde_sink: str, envid: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.service.upgraded.v1", - "source": "cde-cli", - "extensions": { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - }, + service_upgraded_event_v1 = "cd.service.upgraded.v1" + extensions = { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(service_upgraded_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) @common_service_options def removed( - cde_sink: str, envid: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.service.removed.v1", - "source": "cde-cli", - "extensions": { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - }, + service_removed_event_v1 = "cd.service.removed.v1" + extensions = { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(service_removed_event_v1, extensions, data) @click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) @common_service_options def rolledback( - cde_sink: str, envid: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.service.rolledback.v1", - "source": "cde-cli", - "extensions": { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - }, + service_rolledback_event_v1 = "cd.service.rolledback.v1" + extensions = { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(service_rolledback_event_v1, extensions, data) diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index 4db0fd4..6fb6a82 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -1,29 +1,17 @@ """Module for cli taskrun commands.""" from __future__ import annotations -import logging import os from typing import List import click -import requests -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.utils import add_disclaimer_text, print_function_args - -_log = logging.getLogger(__name__) +from cdevents.cli.cdevents_command import CDeventsCommand # pylint: disable=unused-argument def common_taskrun_options(function): """Decorator for common cli options for taskrun.""" - function = click.option( - "--cde_sink", - "-c", - required=False, - type=str, - default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"), - help="CDE_SINK", - )(function) function = click.option( "--id", "-i", @@ -60,52 +48,39 @@ def common_taskrun_options(function): @click.command(help=add_disclaimer_text("TaskRun Started CloudEvent.")) @common_taskrun_options def started( - cde_sink: str, id: str, name: str = None, pipelineid: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.taskrun.started.v1", - "source": "cde-cli", - "extensions": { - "taskrunid": id, - "taskrunname": name, - "taskrunpipelineid": pipelineid, - }, + task_run_started_event_v1 = "cd.taskrun.started.v1" + extensions = { + "taskrunid": id, + "taskrunname": name, + "taskrunpipelineid": pipelineid, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(task_run_started_event_v1, extensions, data) @click.command(help=add_disclaimer_text("TaskRun Finished CloudEvent.")) @common_taskrun_options def finished( - cde_sink: str, id: str, name: str = None, pipelineid: str = None, data: List[str] = None, ): print_function_args() - attributes = { - "type": "cd.taskrun.finished.v1", - "source": "cde-cli", - "extensions": { - "taskrunid": id, - "taskrunname": name, - "taskrunpipelineid": pipelineid, - }, + task_run_finished_event_v1 = "cd.taskrun.finished.v1" + extensions = { + "taskrunid": id, + "taskrunname": name, + "taskrunpipelineid": pipelineid, } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - # send and print event - result = requests.post(cde_sink, headers=headers, data=body) - _log.debug(f"Response with state code {result.status_code}") + cdevents_command = CDeventsCommand() + cdevents_command.run(task_run_finished_event_v1, extensions, data) + From 88c74daaf9abbc3f0a2d81ce2a612597d72c683f Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Thu, 21 Jul 2022 13:55:19 +0200 Subject: [PATCH 11/34] Add core pakage --- cdevents/__init__.py | 3 - cli/cdevents/cli/__main__.py | 3 +- cli/cdevents/cli/artifact.py | 25 +++--- cli/cdevents/cli/branch.py | 30 +++---- cli/cdevents/cli/build.py | 37 +++----- cli/cdevents/cli/cdevents_command.py | 35 ++++---- cli/cdevents/cli/env.py | 37 +++----- cli/cdevents/cli/pipelinerun.py | 43 +++------- cli/cdevents/cli/service.py | 47 ++++------- cli/cdevents/cli/taskrun.py | 26 ++---- cli/setup.cfg | 2 +- core/Makefile | 7 ++ core/README.md | 1 + core/cdevents/core/__init__.py | 4 + core/cdevents/core/event_sender.py | 26 ++++++ core/cdevents/core/event_type.py | 56 +++++++++++++ core/cdevents/core/events.py | 121 +++++++++++++++++++++++++++ core/setup.cfg | 58 +++++++++++++ core/setup.py | 10 +++ 19 files changed, 390 insertions(+), 181 deletions(-) delete mode 100644 cdevents/__init__.py create mode 100644 core/Makefile create mode 100644 core/README.md create mode 100644 core/cdevents/core/__init__.py create mode 100644 core/cdevents/core/event_sender.py create mode 100644 core/cdevents/core/event_type.py create mode 100644 core/cdevents/core/events.py create mode 100644 core/setup.cfg create mode 100644 core/setup.py diff --git a/cdevents/__init__.py b/cdevents/__init__.py deleted file mode 100644 index f7b521c..0000000 --- a/cdevents/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""CDEvents Python SDK.""" - -__version__ = "0.0.1" diff --git a/cli/cdevents/cli/__main__.py b/cli/cdevents/cli/__main__.py index da1aa75..38851ce 100644 --- a/cli/cdevents/cli/__main__.py +++ b/cli/cdevents/cli/__main__.py @@ -6,11 +6,12 @@ import click import yaml +from cdevents.cli.constants import LOGGING_CONFIGURATION_FILE + from cdevents.cli.artifact import packaged, published from cdevents.cli.branch import created as branch_created from cdevents.cli.branch import deleted as branch_deleted from cdevents.cli.build import finished, queued, started -from cdevents.cli.constants import LOGGING_CONFIGURATION_FILE from cdevents.cli.env import created as env_created from cdevents.cli.env import deleted as env_deleted from cdevents.cli.env import modified as env_modified diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index d9bfeef..1f540dd 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_artifact_options(function): """Decorator for common cli options for artifact.""" @@ -54,15 +57,10 @@ def packaged( data: List[str] = None, ): print_function_args() - artifact_packaged_event_v1 = "cd.artifact.packaged.v1" - extensions = { - "artifactid": id, - "artifactname": name, - "artifactversion": version, - } - + e = Events() + new_event = e.create_artifact_event(event_type.ArtifactPackagedEventV1, id, name, version, data) cdevents_command = CDeventsCommand() - cdevents_command.run(artifact_packaged_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Artifact Published CloudEvent.")) @@ -74,11 +72,8 @@ def published( data: List[str] = None, ): print_function_args() - artifact_published_event_v1 = "cd.artifact.published.v1" - extensions = { - "artifactid": id, - "artifactname": name, - "artifactversion": version, - } + + e = Events() + new_event = e.create_artifact_event(event_type.ArtifactPublishedEventV1, id, name, version, data) cdevents_command = CDeventsCommand() - cdevents_command.run(artifact_published_event_v1, extensions, data) + cdevents_command.run(new_event) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index 044e8d5..de7b9f8 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_branch_options(function): """Decorator for common cli options for branch.""" @@ -53,16 +56,12 @@ def created( repoid: str = None, data: List[str] = None, ): - print_function_args() - branch_created_event_v1 = "cd.repository.branch.created.v1" - extensions = { - "branchid": id, - "branchname": name, - "branchrepositoryid": repoid, - } - + print_function_args() + e = Events() + new_event = e.create_branch_event(event_type.BranchCreatedEventV1, id, name, repoid, data) cdevents_command = CDeventsCommand() - cdevents_command.run(branch_created_event_v1, extensions, data) + cdevents_command.run(new_event) + @click.command(help=add_disclaimer_text("Branch Deleted CloudEvent.")) @common_branch_options @@ -72,13 +71,8 @@ def deleted( repoid: str = None, data: List[str] = None, ): - print_function_args() - branch_deleted_event_v1 = "cd.repository.branch.deleted.v1" - extensions = { - "branchid": id, - "branchname": name, - "branchrepositoryid": repoid, - } - + print_function_args() + e = Events() + new_event = e.create_branch_event(event_type.BranchDeletedEventV1, id, name, repoid, data) cdevents_command = CDeventsCommand() - cdevents_command.run(branch_deleted_event_v1, extensions, data) + cdevents_command.run(new_event) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 61dc0b7..05298e8 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_build_options(function): """Decorator for common cli options for build.""" @@ -55,15 +58,10 @@ def started( data: List[str] = None, ): print_function_args() - build_started_event_v1 = "cd.build.started.v1" - extensions = { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - } - + e = Events() + new_event = e.create_build_event(event_type.BuildStartedEventV1, id, name, artifact, data) cdevents_command = CDeventsCommand() - cdevents_command.run(build_started_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Build Finished CloudEvent.")) @common_build_options @@ -74,16 +72,10 @@ def finished( data: List[str] = None, ): print_function_args() - build_finished_event_v1 = "cd.build.finished.v1" - extensions = { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - } - + e = Events() + new_event = e.create_build_event(event_type.BuildFinishedEventV1, id, name, artifact, data) cdevents_command = CDeventsCommand() - cdevents_command.run(build_finished_event_v1, extensions, data) - + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_build_options @@ -94,12 +86,7 @@ def queued( data: List[str] = None, ): print_function_args() - build_queued_event_v1 = "cd.build.queued.v1" - extensions = { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - } - + e = Events() + new_event = e.create_build_event(event_type.BuildQueuedEventV1, id, name, artifact, data) cdevents_command = CDeventsCommand() - cdevents_command.run(build_queued_event_v1, extensions, data) + cdevents_command.run(new_event) diff --git a/cli/cdevents/cli/cdevents_command.py b/cli/cdevents/cli/cdevents_command.py index 1e9c763..3f23863 100644 --- a/cli/cdevents/cli/cdevents_command.py +++ b/cli/cdevents/cli/cdevents_command.py @@ -3,10 +3,14 @@ from abc import ABC import requests +from cloudevents.http import CloudEvent + +from cdevents.core.event_sender import EventSender + from cdevents.cli.configuration_handler import ConfigurationHandler -from cloudevents.http import CloudEvent, to_structured from cdevents.cli.configuration_handler import new_default_configuration_handler + class CDeventsCommand(ABC): """Abstract base class for all Hostlog commands.""" @@ -21,21 +25,24 @@ def __init__(self, config_handler: ConfigurationHandler = None): if config_handler is None: self._config_handler = new_default_configuration_handler() - def run(self, type, extensions, data): + def run(self, event: CloudEvent): """run command. """ - attributes = { - "type": type, - "source": self.config_handler.source.name, - "extensions": extensions, - } - event = CloudEvent(attributes, dict(data)) - headers, body = to_structured(event) - cde_link = self.config_handler.client.host - - # send and print event - result = requests.post(cde_link, headers=headers, data=body) - self._log.info(f"Response with state code {result.status_code}") + # attributes = { + # "type": type, + # "source": self.config_handler.source.name, + # "extensions": extensions, + # } + # event = CloudEvent(attributes, dict(data)) + # headers, body = to_structured(event) + # cde_link = self.config_handler.client.host + + # # send and print event + # result = requests.post(cde_link, headers=headers, data=body) + # self._log.info(f"Response with state code {result.status_code}") + + e = EventSender(cde_link=self.config_handler.client.host) + e.send(event) @property diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index 3e99647..f728738 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_env_options(function): """Decorator for common cli options for environment.""" @@ -54,15 +57,10 @@ def created( data: List[str] = None, ): print_function_args() - environment_created_event_v1 = "cd.environment.created.v1" - extensions = { - "envId": id, - "envname": name, - "envrepourl": repo, - } - + e = Events() + new_event = e.create_environment_event(event_type.EnvironmentCreatedEventV1, id, name, repo, data) cdevents_command = CDeventsCommand() - cdevents_command.run(environment_created_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) @@ -74,16 +72,10 @@ def deleted( data: List[str] = None, ): print_function_args() - environment_deleted_event_v1 = "cd.environment.deleted.v1" - extensions = { - "envId": id, - "envname": name, - "envrepourl": repo, - } - + e = Events() + new_event = e.create_environment_event(event_type.EnvironmentDeletedEventV1, id, name, repo, data) cdevents_command = CDeventsCommand() - cdevents_command.run(environment_deleted_event_v1, extensions, data) - + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Environment Modified CloudEvent.")) @common_env_options @@ -94,12 +86,7 @@ def modified( data: List[str] = None, ): print_function_args() - environment_modified_event_v1 = "cd.environment.modified.v1" - extensions = { - "envId": id, - "envname": name, - "envrepourl": repo, - } - + e = Events() + new_event = e.create_environment_event(event_type.EnvironmentModifiedEventV1, id, name, repo, data) cdevents_command = CDeventsCommand() - cdevents_command.run(environment_modified_event_v1, extensions, data) + cdevents_command.run(new_event) \ No newline at end of file diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 5b961cd..5c3efe9 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_pipelinerun_options(function): """Decorator for common cli options for pipelinerun.""" @@ -70,17 +73,10 @@ def started( data: List[str] = None, ): print_function_args() - pipeline_run_started_event_v1 = "cd.pipelinerun.started.v1" - extensions = { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - } - + e = Events() + new_event = e.create_pipelinerun_event(event_type.PipelineRunStartedEventV1, id, name, status, url, errors, data) cdevents_command = CDeventsCommand() - cdevents_command.run(pipeline_run_started_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("PipelineRun Finished CloudEvent.")) @@ -94,17 +90,10 @@ def finished( data: List[str] = None, ): print_function_args() - pipeline_run_finished_event_v1 = "cd.pipelinerun.finished.v1" - extensions = { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - } - + e = Events() + new_event = e.create_pipelinerun_event(event_type.PipelineRunFinishedEventV1, id, name, status, url, errors, data) cdevents_command = CDeventsCommand() - cdevents_command.run(pipeline_run_finished_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_pipelinerun_options @@ -117,14 +106,8 @@ def queued( data: List[str] = None, ): print_function_args() - pipeline_run_queued_event_v1 = "cd.pipelinerun.queued.v1" - extensions = { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - } - + e = Events() + new_event = e.create_pipelinerun_event(event_type.PipelineRunQueuedEventV1, id, name, status, url, errors, data) cdevents_command = CDeventsCommand() - cdevents_command.run(pipeline_run_queued_event_v1, extensions, data) + cdevents_command.run(new_event) + diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index a984b92..0c085c6 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_service_options(function): """Decorator for common cli options for service.""" @@ -54,15 +57,10 @@ def deployed( data: List[str] = None, ): print_function_args() - service_deployed_event_v1 = "cd.service.deployed.v1" - extensions = { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - } - + e = Events() + new_event = e.create_service_event(event_type.ServiceDeployedEventV1, envid, name, version, data) cdevents_command = CDeventsCommand() - cdevents_command.run(service_deployed_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Service Upgraded CloudEvent.")) @@ -74,15 +72,10 @@ def upgraded( data: List[str] = None, ): print_function_args() - service_upgraded_event_v1 = "cd.service.upgraded.v1" - extensions = { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - } - + e = Events() + new_event = e.create_service_event(event_type.ServiceUpgradedEventV1, envid, name, version, data) cdevents_command = CDeventsCommand() - cdevents_command.run(service_upgraded_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) @@ -94,15 +87,10 @@ def removed( data: List[str] = None, ): print_function_args() - service_removed_event_v1 = "cd.service.removed.v1" - extensions = { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - } - + e = Events() + new_event = e.create_service_event(event_type.ServiceRemovedEventV1, envid, name, version, data) cdevents_command = CDeventsCommand() - cdevents_command.run(service_removed_event_v1, extensions, data) + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) @@ -114,12 +102,7 @@ def rolledback( data: List[str] = None, ): print_function_args() - service_rolledback_event_v1 = "cd.service.rolledback.v1" - extensions = { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - } - + e = Events() + new_event = e.create_service_event(event_type.ServiceRolledbackEventV1, envid, name, version, data) cdevents_command = CDeventsCommand() - cdevents_command.run(service_rolledback_event_v1, extensions, data) + cdevents_command.run(new_event) diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index 6fb6a82..e55b864 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -9,6 +9,9 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand +from cdevents.core.events import Events +from cdevents.core import event_type + # pylint: disable=unused-argument def common_taskrun_options(function): """Decorator for common cli options for taskrun.""" @@ -54,16 +57,10 @@ def started( data: List[str] = None, ): print_function_args() - task_run_started_event_v1 = "cd.taskrun.started.v1" - extensions = { - "taskrunid": id, - "taskrunname": name, - "taskrunpipelineid": pipelineid, - } - + e = Events() + new_event = e.create_taskrun_event(event_type.TaskRunStartedEventV1, id, name, pipelineid, data) cdevents_command = CDeventsCommand() - cdevents_command.run(task_run_started_event_v1, extensions, data) - + cdevents_command.run(new_event) @click.command(help=add_disclaimer_text("TaskRun Finished CloudEvent.")) @common_taskrun_options @@ -74,13 +71,8 @@ def finished( data: List[str] = None, ): print_function_args() - task_run_finished_event_v1 = "cd.taskrun.finished.v1" - extensions = { - "taskrunid": id, - "taskrunname": name, - "taskrunpipelineid": pipelineid, - } - + e = Events() + new_event = e.create_taskrun_event(event_type.TaskRunFinishedEventV1, id, name, pipelineid, data) cdevents_command = CDeventsCommand() - cdevents_command.run(task_run_finished_event_v1, extensions, data) + cdevents_command.run(new_event) diff --git a/cli/setup.cfg b/cli/setup.cfg index 5c06369..a7b87aa 100644 --- a/cli/setup.cfg +++ b/cli/setup.cfg @@ -33,8 +33,8 @@ install_requires = click>=8.0.4 pyyaml>=6.0 click-option-group - requests cloudevents + cdevents.core [options.extras_require] dev = diff --git a/core/Makefile b/core/Makefile new file mode 100644 index 0000000..0bf7a38 --- /dev/null +++ b/core/Makefile @@ -0,0 +1,7 @@ +include ../header.mk + +SRC := cdevents/core + +MAKEFILE_LIST=../targets.mk + +include $(MAKEFILE_LIST) diff --git a/core/README.md b/core/README.md new file mode 100644 index 0000000..c0aa5b4 --- /dev/null +++ b/core/README.md @@ -0,0 +1 @@ +# CDevents Core diff --git a/core/cdevents/core/__init__.py b/core/cdevents/core/__init__.py new file mode 100644 index 0000000..b6c803e --- /dev/null +++ b/core/cdevents/core/__init__.py @@ -0,0 +1,4 @@ +"""CDEvents CLI provides command-line interaction with Cd-Event client functionality.""" + +__version__ = "0.0.1" + diff --git a/core/cdevents/core/event_sender.py b/core/cdevents/core/event_sender.py new file mode 100644 index 0000000..5a82fcb --- /dev/null +++ b/core/cdevents/core/event_sender.py @@ -0,0 +1,26 @@ + +"""Core events sender.""" + +import requests + +from cloudevents.http import CloudEvent, to_structured + +class EventSender(): + """Events Sender.""" + + def __init__(self, cde_link: str = None): + """Initializes class. + """ + self._cde_link = cde_link + if cde_link is None: + self._cde_link = "http://localhost:8080" + + + def send(self, event: CloudEvent): + """send events. + """ + headers, body = to_structured(event) + + # send and print event + result = requests.post(self._cde_link, headers=headers, data=body) + print(f"Response with state code {result.status_code}") diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py new file mode 100644 index 0000000..c1ff47c --- /dev/null +++ b/core/cdevents/core/event_type.py @@ -0,0 +1,56 @@ +"""Constants Event types.""" + +# PipelineRun events +PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" +PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" +PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" + +# TaskRun events +TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" +TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" + +# Repository events +RepositoryCreatedEventV1 :str = "cd.repository.created.v1" +RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" +RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" + +# Branch Events +BranchCreatedEventV1 :str = "cd.repository.branch.created.v1" +BranchDeletedEventV1 :str = "cd.repository.branch.deleted.v1" + +# Change Events +ChangeCreatedEventV1 :str = "cd.repository.change.created.v1" +ChangeUpdatedEventV1 :str = "cd.repository.change.updated.v1" +ChangeReviewedEventV1 :str = "cd.repository.change.reviewed.v1" +ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" +ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" + +# Build Events +BuildStartedEventV1 :str = "cd.build.started.v1" +BuildQueuedEventV1 :str = "cd.build.queued.v1" +BuildFinishedEventV1 :str = "cd.build.finished.v1" + +# Test Events +TestCaseStartedEventV1 :str = "cd.test.case.started.v1" +TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" +TestCaseFinishedEventV1 :str = "cd.test.case.finished.v1" + +TestSuiteStartedEventV1 :str = "cd.test.suite.started.v1" +TestSuiteQueuedEventV1 :str = "cd.test.suite.queued.v1" +TestSuiteFinishedEventV1 :str = "cd.test.suite.finished.v1" + +# Artifact Events +ArtifactPackagedEventV1 :str = "cd.artifact.packaged.v1" +ArtifactPublishedEventV1 :str = "cd.artifact.published.v1" + +# Environment Events +EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" +EnvironmentModifiedEventV1 :str = "cd.environment.modified.v1" +EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" + +# Service Events +ServiceDeployedEventV1 :str = "cd.service.deployed.v1" +ServiceUpgradedEventV1 :str = "cd.service.upgraded.v1" +ServiceRolledbackEventV1 :str = "cd.service.rolledback.v1" +ServiceRemovedEventV1 :str = "cd.service.removed.v1" + diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py new file mode 100644 index 0000000..02a8019 --- /dev/null +++ b/core/cdevents/core/events.py @@ -0,0 +1,121 @@ +"""Core events.""" + +from cloudevents.http import CloudEvent + +class Events(): + """Events.""" + + def __init__(self): + """Initializes class. + """ + + def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEvent: + """Create event. + """ + attributes = { + "type": event_type, + "source": "cde-cli", + "extensions": extensions, + } + + event = CloudEvent(attributes, dict(data)) + + return event + + def create_artifact_event(self, event_type: str , id: str, name: str, version: str, data = {}) -> CloudEvent: + """Create artifact event. + """ + + extensions = { + "artifactid": id, + "artifactname": name, + "artifactversion": version, + } + event = self.create_event(event_type, extensions, data) + + return event + + def create_branch_event(self, event_type: str , id: str, name: str, repoid: str, data = {}) -> CloudEvent: + """Create branch event. + """ + + extensions = { + "branchid": id, + "branchname": name, + "branchrepositoryid": repoid, + } + event = self.create_event(event_type, extensions, data) + + return event + + + def create_build_event(self, event_type: str , id: str, name: str, artifact: str, data = {}) -> CloudEvent: + """Create build event. + """ + + extensions = { + "buildid": id, + "buildname": name, + "buildartifactid": artifact, + } + event = self.create_event(event_type, extensions, data) + + return event + + def create_environment_event(self, event_type: str , id: str, name: str, repo: str, data = {}) -> CloudEvent: + """Create environment event. + """ + + extensions = { + "envId": id, + "envname": name, + "envrepourl": repo, + } + event = self.create_event(event_type, extensions, data) + + return event + + def create_pipelinerun_event(self, event_type: str , id: str, name: str, status: str, url: str, errors: str, data = {}) -> CloudEvent: + """Create pipelinerun event. + """ + + extensions = { + "pipelinerunid": id, + "pipelinerunname": name, + "pipelinerunstatus": status, + "pipelinerunurl": url, + "pipelinerunerrors": errors, + } + event = self.create_event(event_type, extensions, data) + + return event + + def create_service_event(self, event_type: str , envid: str, name: str, version: str, data = {}) -> CloudEvent: + """Create service event. + """ + + extensions = { + "serviceenvid": envid, + "servicename": name, + "serviceversion": version, + } + + event = self.create_event(event_type, extensions, data) + + return event + + + def create_taskrun_event(self, event_type: str, id: str, name: str, pipelineid: str, data = {}) -> CloudEvent: + """Create taskrun event. + """ + + extensions = { + "taskrunid": id, + "taskrunname": name, + "taskrunpipelineid": pipelineid, + } + + event = self.create_event(event_type, extensions, data) + + return event + diff --git a/core/setup.cfg b/core/setup.cfg new file mode 100644 index 0000000..7397488 --- /dev/null +++ b/core/setup.cfg @@ -0,0 +1,58 @@ +[bumpversion] +current_version = 0.0.1 + +[bumpversion:file:./cdevents/core/__init__.py] + +[metadata] +name = cdevents.core +description = CDEvents Core +long_description = file: README.md +version = attr: cdevents.core.__version__ +author = doWhile +author_email = info@dowhile.com +keywords = CDEvents, core +url = todo +classifiers = + Development Status :: 3 - Alpha + Intended Audience :: Developers + License :: Other/Proprietary License + Natural Language :: English + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.9 + Topic :: Software Development :: Libraries :: Python Modules + +[options] +packages = find_namespace: +zip_safe = False +include_package_data = True +install_requires = + PyYAML + requests + cloudevents + +[options.extras_require] +dev = + black + bump2version + isort + mypy + pre-commit + pydocstyle + pytest + pytest_mock + yamllint + pylint + deepdiff +build = + wheel + +[options.packages.find] +include = + cdevents.* + +[bdist_wheel] +universal = 0 diff --git a/core/setup.py b/core/setup.py new file mode 100644 index 0000000..f3d9343 --- /dev/null +++ b/core/setup.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""The setup script.""" + +__requires__ = "setuptools >= 44.0.0" + +from setuptools import setup + +setup() From 0bb3411e8ec1c9dc9995c341f9dc03ef2d5082bf Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Tue, 26 Jul 2022 14:11:17 +0200 Subject: [PATCH 12/34] add artifact extension --- cli/cdevents/cli/cdevents_command.py | 13 --------- cli/cdevents/cli/utils.py | 6 +--- core/cdevents/core/event_sender.py | 1 - .../core/extensions/artifact_extension.py | 28 +++++++++++++++++++ .../core/extensions/service_extension.py | 28 +++++++++++++++++++ 5 files changed, 57 insertions(+), 19 deletions(-) create mode 100644 core/cdevents/core/extensions/artifact_extension.py create mode 100644 core/cdevents/core/extensions/service_extension.py diff --git a/cli/cdevents/cli/cdevents_command.py b/cli/cdevents/cli/cdevents_command.py index 3f23863..3dd38f1 100644 --- a/cli/cdevents/cli/cdevents_command.py +++ b/cli/cdevents/cli/cdevents_command.py @@ -28,19 +28,6 @@ def __init__(self, config_handler: ConfigurationHandler = None): def run(self, event: CloudEvent): """run command. """ - # attributes = { - # "type": type, - # "source": self.config_handler.source.name, - # "extensions": extensions, - # } - # event = CloudEvent(attributes, dict(data)) - # headers, body = to_structured(event) - # cde_link = self.config_handler.client.host - - # # send and print event - # result = requests.post(cde_link, headers=headers, data=body) - # self._log.info(f"Response with state code {result.status_code}") - e = EventSender(cde_link=self.config_handler.client.host) e.send(event) diff --git a/cli/cdevents/cli/utils.py b/cli/cdevents/cli/utils.py index a252249..441a6bd 100644 --- a/cli/cdevents/cli/utils.py +++ b/cli/cdevents/cli/utils.py @@ -115,11 +115,7 @@ def _os_name() -> str: # TODO: Update disclaimer text -DISCLAIMER_TEXT = """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - N.B. Due to data privacy regulations, all locally generated cdevents data files - ,such as hdf5 etc, must be deleted after a logging session is finished. - Exluded are log files generated by Vigem on the way to be stored in Oden - !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!""" +DISCLAIMER_TEXT = "" def add_disclaimer_text(help_text: str) -> str: diff --git a/core/cdevents/core/event_sender.py b/core/cdevents/core/event_sender.py index 5a82fcb..6ac55f6 100644 --- a/core/cdevents/core/event_sender.py +++ b/core/cdevents/core/event_sender.py @@ -1,4 +1,3 @@ - """Core events sender.""" import requests diff --git a/core/cdevents/core/extensions/artifact_extension.py b/core/cdevents/core/extensions/artifact_extension.py new file mode 100644 index 0000000..80a0426 --- /dev/null +++ b/core/cdevents/core/extensions/artifact_extension.py @@ -0,0 +1,28 @@ +"""ArtifactExtension represents the extension for extension context.""" + +from cloudevents.http import CloudEvent + +ArtifactIdExtension = "artifactid" +ArtifactNameExtension = "artifactname" +ArtifactVersionExtension = "artifactversion" + + +class ArtifactExtension(): + """Artifact Extension.""" + def __init__(self) -> None: + pass + + def read_transformer(): + """Read transformer.""" + pass + + def write_transformer(event: CloudEvent, extensions: dict) -> CloudEvent: + """Write transformer.""" + if event._attributes["extensions"].get(ArtifactIdExtension): + event._attributes["extensions"].set(ArtifactIdExtension, extensions.get(ArtifactIdExtension)) + if event._attributes["extensions"].get(ArtifactNameExtension): + event._attributes["extensions"].set(ArtifactNameExtension, extensions.get(ArtifactNameExtension)) + if event._attributes["extensions"].get(ArtifactVersionExtension): + event._attributes["extensions"].set(ArtifactVersionExtension, extensions.get(ArtifactVersionExtension)) + return event + diff --git a/core/cdevents/core/extensions/service_extension.py b/core/cdevents/core/extensions/service_extension.py new file mode 100644 index 0000000..23474db --- /dev/null +++ b/core/cdevents/core/extensions/service_extension.py @@ -0,0 +1,28 @@ +"""ServiceExtension represents the extension for extension context.""" + +from cloudevents.http import CloudEvent + +ServiceEnvIdExtension = "serviceenvid" +ServiceNameExtension = "servicename" +ServiceVersionExtension = "serviceversion" + + +class ServiceExtension(): + """Service Extension.""" + def __init__(self) -> None: + pass + + def read_transformer(): + """Read transformer.""" + pass + + def write_transformer(event: CloudEvent, extensions: dict) -> CloudEvent: + """Write transformer.""" + if event._attributes["extensions"].get(ServiceEnvIdExtension): + event._attributes["extensions"].set(ServiceEnvIdExtension, extensions.get(ServiceEnvIdExtension)) + if event._attributes["extensions"].get(ServiceNameExtension): + event._attributes["extensions"].set(ServiceNameExtension, extensions.get(ServiceNameExtension)) + if event._attributes["extensions"].get(ServiceVersionExtension): + event._attributes["extensions"].set(ServiceVersionExtension, extensions.get(ServiceVersionExtension)) + return event + From fa40865839828cbf686007d617c46104a6046777 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 27 Jul 2022 12:08:41 +0200 Subject: [PATCH 13/34] update make file --- Makefile | 6 +----- targets.mk | 7 +------ 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index a94003e..28156fb 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ include header.mk -PACKAGES = cli +PACKAGES = core cli export ABS_ROOT_PATH=$(shell pwd) .PHONY: packages $(PACKAGES) @@ -22,10 +22,6 @@ BUMPVERSIONPACKAGES = $(PACKAGES:%=bumpversion-%) help: ## Prints this help text @python -c "$$PRINT_HELP_PYSCRIPT" < Makefile -init: $(INITPACKAGES) ## Installs all packages in editable mode including dev dependencies -$(INITPACKAGES): - $(MAKE) -C $(@:init-%=%) init - package-install: $(INSTALLPACKAGES) ## Installs all packages without dev dependencies $(INSTALLPACKAGES): $(MAKE) -C $(@:package-install-%=%) package-install diff --git a/targets.mk b/targets.mk index 7705d88..70a48fa 100644 --- a/targets.mk +++ b/targets.mk @@ -25,13 +25,8 @@ clean-test: ## remove test and coverage artifacts clean-mypy: ## remove MyPy cache files rm -fr .mypy_cache/ - -init: clean ## install the package in editable mode including dev dependencies - pip install -e .[dev] - pre-commit install - package-install: ## install the package without dev dependencies - pip install . + pip install -e . test: ## run tests quickly with the default Python python -m pytest -m unit From 47b69dbe4601256c9d5986339410e5e0ea051974 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Thu, 28 Jul 2022 15:22:52 +0200 Subject: [PATCH 14/34] add test for core --- cli/cdevents/cli/cdevents_command.py | 2 +- cli/setup.cfg | 1 + cli/tests/__init__.py | 1 + cli/tests/test_utils.py | 99 ++++++++++++++++++++++++++++ cli/tests/test_version.py | 16 +++++ core/setup.cfg | 1 + core/tests/__init__.py | 1 + core/tests/test_events.py | 72 ++++++++++++++++++++ core/tests/test_version.py | 16 +++++ pytest.ini | 7 ++ targets.mk | 2 +- 11 files changed, 216 insertions(+), 2 deletions(-) create mode 100644 cli/tests/__init__.py create mode 100644 cli/tests/test_utils.py create mode 100644 cli/tests/test_version.py create mode 100644 core/tests/__init__.py create mode 100644 core/tests/test_events.py create mode 100644 core/tests/test_version.py create mode 100644 pytest.ini diff --git a/cli/cdevents/cli/cdevents_command.py b/cli/cdevents/cli/cdevents_command.py index 3dd38f1..2365ae7 100644 --- a/cli/cdevents/cli/cdevents_command.py +++ b/cli/cdevents/cli/cdevents_command.py @@ -12,7 +12,7 @@ class CDeventsCommand(ABC): - """Abstract base class for all Hostlog commands.""" + """Abstract base class for all CDevents commands.""" def __init__(self, config_handler: ConfigurationHandler = None): """Initializes base class. diff --git a/cli/setup.cfg b/cli/setup.cfg index a7b87aa..7319fe5 100644 --- a/cli/setup.cfg +++ b/cli/setup.cfg @@ -30,6 +30,7 @@ packages = find_namespace: zip_safe = False include_package_data = True install_requires = + pytest click>=8.0.4 pyyaml>=6.0 click-option-group diff --git a/cli/tests/__init__.py b/cli/tests/__init__.py new file mode 100644 index 0000000..149f70c --- /dev/null +++ b/cli/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for core package.""" diff --git a/cli/tests/test_utils.py b/cli/tests/test_utils.py new file mode 100644 index 0000000..a65d0b0 --- /dev/null +++ b/cli/tests/test_utils.py @@ -0,0 +1,99 @@ +"""Testing for module utils.""" +from datetime import datetime +from unittest import mock + +import pytest + +from cdevents.cli.utils import DictUtils, time_stamp + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.mark.unit +def test_merge_dicts_1(): + source = {"a": 66} + target = {"b": 77, "c": 88} + expected = {"a": 66, "b": 77, "c": 88} + merge_and_test(source, target, expected) + + +@pytest.mark.unit +def test_merge_dicts_2(): + source = {"a": 66} + target = {"a": 77} + expected = {"a": 77} + merge_and_test(source, target, expected) + + +@pytest.mark.unit +def test_merge_dicts_3(): + source = {} + target = {"a": 77} + expected = {"a": 77} + merge_and_test(source, target, expected) + + +@pytest.mark.unit +def test_merge_dicts_3_1(): + target = {} + source = {"a": 77} + expected = {"a": 77} + merge_and_test(source, target, expected) + + +@pytest.mark.unit +def test_merge_dicts_4(): + source = {"a": {"aa": 11, "aaa": {"aaaa": 111}}} + target = {"b": {"bb": 22, "bbb": {"bbbb": 222}}} + expected = { + "a": {"aa": 11, "aaa": {"aaaa": 111}}, + "b": {"bb": 22, "bbb": {"bbbb": 222}}, + } + merge_and_test(source, target, expected) + + +@pytest.mark.unit +def test_merge_dicts_5(): + source = { + "a": {"aa": 12, "aaa": {"aaaa": 222, "bbb": 333}}, + "b": 4, + "c": [8, 9], + "d": [1], + } + target = { + "a": {"aa": 11, "aaa": {"aaaa": 111}}, + "b": 5, + "c": [1, 2, 3], + "d": {"v": 1}, + } + expected = { + "a": {"aa": 11, "aaa": {"aaaa": 111, "bbb": 333}}, + "b": 5, + "c": [1, 2, 3, 8, 9], + "d": {"v": 1}, + } + merge_and_test(source, target, expected) + + +def merge_and_test(source, target, expected): + DictUtils.merge_dicts(source, target) + assert target == expected + + +# FIXME: add test for times_tamep +# VALID_TIME_STAMP_REGEX= +EXPECTED_DATETIME = datetime( + year=2022, + month=1, + day=12, + hour=10, + minute=44, + second=23, +) +EXPECTED_TIMESTAMP = "20220112T104423000" + + +@pytest.mark.unit +@mock.patch("cdevents.cli.utils._utcnow") +def test_time_stamp(mock_utcnow): + mock_utcnow.return_value = EXPECTED_DATETIME + actual = time_stamp("T") + assert actual == EXPECTED_TIMESTAMP diff --git a/cli/tests/test_version.py b/cli/tests/test_version.py new file mode 100644 index 0000000..5bd0a1e --- /dev/null +++ b/cli/tests/test_version.py @@ -0,0 +1,16 @@ +import re + +import pytest + +from cdevents.cli import __version__ + +# From https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +VALID_SEMVER_REGEX = ( + r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)" + r"(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$" +) + + +@pytest.mark.unit +def test_version_is_semantic(): + assert re.fullmatch(VALID_SEMVER_REGEX, __version__) diff --git a/core/setup.cfg b/core/setup.cfg index 7397488..bac04f5 100644 --- a/core/setup.cfg +++ b/core/setup.cfg @@ -30,6 +30,7 @@ packages = find_namespace: zip_safe = False include_package_data = True install_requires = + pytest PyYAML requests cloudevents diff --git a/core/tests/__init__.py b/core/tests/__init__.py new file mode 100644 index 0000000..149f70c --- /dev/null +++ b/core/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for core package.""" diff --git a/core/tests/test_events.py b/core/tests/test_events.py new file mode 100644 index 0000000..ec1160a --- /dev/null +++ b/core/tests/test_events.py @@ -0,0 +1,72 @@ + + +from pickle import NONE +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + + +@pytest.mark.unit +def test_create_event(): + event = Events().create_event(event_type="event_type", extensions={"test": "test"}) + assert event is not None + assert event._attributes["type"] == "event_type" + assert event._attributes["extensions"] == {"test": "test"} + +@pytest.mark.unit +def test_create_artifact_event(): + event = Events().create_artifact_event(event_type.ArtifactPackagedEventV1, id="_id", name="_name", version="_version", data={"artifact": "_artifact"}) + assert event is not None + assert event._attributes["type"] == event_type.ArtifactPackagedEventV1 + assert event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} + assert event.data == {"artifact": "_artifact"} + +@pytest.mark.unit +def test_create_branch_event(): + event = Events().create_branch_event(event_type.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"branch": "_branch"}) + assert event is not None + assert event._attributes["type"] == event_type.BranchCreatedEventV1 + assert event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} + assert event.data == {"branch": "_branch"} + +@pytest.mark.unit +def test_create_build_event(): + event = Events().create_build_event(event_type.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) + assert event is not None + assert event._attributes["type"] == event_type.BuildFinishedEventV1 + assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert event.data == {"build": "_build"} + +@pytest.mark.unit +def test_create_environment_event(): + event = Events().create_environment_event(event_type.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) + assert event is not None + assert event._attributes["type"] == event_type.EnvironmentCreatedEventV1 + assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert event.data == {"environment": "_environment"} + +@pytest.mark.unit +def test_create_pipelinerun_event(): + event = Events().create_pipelinerun_event(event_type.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) + assert event is not None + assert event._attributes["type"] == event_type.PipelineRunFinishedEventV1 + assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert event.data == {"pipelinerun": "_pipelinerun"} + +@pytest.mark.unit +def test_create_service_event(): + event = Events().create_service_event(event_type.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) + assert event is not None + assert event._attributes["type"] == event_type.ServiceDeployedEventV1 + assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert event.data == {"service": "_service"} + + +@pytest.mark.unit +def test_create_taskrun_event(): + event = Events().create_taskrun_event(event_type.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"taskrun": "_taskrun"}) + assert event is not None + assert event._attributes["type"] == event_type.TaskRunFinishedEventV1 + assert event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} + assert event.data == {"taskrun": "_taskrun"} diff --git a/core/tests/test_version.py b/core/tests/test_version.py new file mode 100644 index 0000000..104f763 --- /dev/null +++ b/core/tests/test_version.py @@ -0,0 +1,16 @@ +import re + +import pytest + +from cdevents.core import __version__ + +# From https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +VALID_SEMVER_REGEX = ( + r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)" + r"(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$" +) + + +@pytest.mark.unit +def test_version_is_semantic(): + assert re.fullmatch(VALID_SEMVER_REGEX, __version__) diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..0739683 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,7 @@ +[pytest] +testpaths = + cli/tests + core/tests +markers = + unit: mark for unit tests + integration: integration tests diff --git a/targets.mk b/targets.mk index 70a48fa..fbd6617 100644 --- a/targets.mk +++ b/targets.mk @@ -29,7 +29,7 @@ package-install: ## install the package without dev dependencies pip install -e . test: ## run tests quickly with the default Python - python -m pytest -m unit + python -m pytest -m unit -vv dist: clean ## builds source and wheel package python setup.py sdist From eadb36ff4c3bcab2141ea6b78cd413029d435515 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Fri, 29 Jul 2022 11:43:24 +0200 Subject: [PATCH 15/34] add repository event --- cli/cdevents/cli/__main__.py | 12 ++++ cli/cdevents/cli/repository.py | 94 ++++++++++++++++++++++++++++++++ core/cdevents/core/event_type.py | 61 ++++++++++----------- core/cdevents/core/events.py | 15 +++++ 4 files changed, 151 insertions(+), 31 deletions(-) create mode 100644 cli/cdevents/cli/repository.py diff --git a/cli/cdevents/cli/__main__.py b/cli/cdevents/cli/__main__.py index 38851ce..686348c 100644 --- a/cli/cdevents/cli/__main__.py +++ b/cli/cdevents/cli/__main__.py @@ -18,6 +18,9 @@ from cdevents.cli.pipelinerun import finished as pipe_finished from cdevents.cli.pipelinerun import queued as pipe_queued from cdevents.cli.pipelinerun import started as pipe_started +from cdevents.cli.repository import created as repo_created +from cdevents.cli.repository import deleted as repo_deleted +from cdevents.cli.repository import modified as repo_modified from cdevents.cli.service import deployed as service_deployed from cdevents.cli.service import removed as service_removed from cdevents.cli.service import rolledback as service_rolledback @@ -81,6 +84,14 @@ def pipelinerun(): pipelinerun.add_command(pipe_finished) pipelinerun.add_command(pipe_queued) +@click.group(help=add_disclaimer_text("""Commands Repository related CloudEvent.""")) +def repository(): + """Click group for command 'repository'.""" + +repository.add_command(repo_created) +repository.add_command(repo_modified) +repository.add_command(repo_deleted) + @click.group(help=add_disclaimer_text("""Commands Service related CloudEvent.""")) def service(): @@ -119,6 +130,7 @@ def cli(): cli.add_command(branch) cli.add_command(env) cli.add_command(pipelinerun) +cli.add_command(repository) cli.add_command(service) cli.add_command(taskrun) diff --git a/cli/cdevents/cli/repository.py b/cli/cdevents/cli/repository.py new file mode 100644 index 0000000..faff5ed --- /dev/null +++ b/cli/cdevents/cli/repository.py @@ -0,0 +1,94 @@ +"""Module for cli repository commands.""" +from __future__ import annotations + +import os +from typing import List + +import click + +from cdevents.cli.utils import add_disclaimer_text, print_function_args +from cdevents.cli.cdevents_command import CDeventsCommand + +from cdevents.core.events import Events +from cdevents.core import event_type + +# pylint: disable=unused-argument +def common_repository_options(function): + """Decorator for common cli options for repository.""" + function = click.option( + "--id", + "-i", + required=False, + type=str, + help="Repository Id.", + )(function) + function = click.option( + "--name", + "-n", + required=False, + type=str, + help="Repository's Name.", + )(function) + function = click.option( + "--url", + "-u", + required=False, + type=str, + help="Repository's URL.", + )(function) + function = click.option( + "--data", + "-d", + required=False, + type=(str, str), + multiple=True, + help="Repository's Data.", + )(function) + + return function + + +@click.command(help=add_disclaimer_text("Repository Created CloudEvent.")) +@common_repository_options +def created( + id: str, + name: str = None, + url: str = None, + data: List[str] = None, +): + print_function_args() + e = Events() + new_event = e.create_repository_event(event_type.RepositoryCreatedEventV1, id, name, url, data) + cdevents_command = CDeventsCommand() + cdevents_command.run(new_event) + + +@click.command(help=add_disclaimer_text("Repository Modified CloudEvent.")) +@common_repository_options +def modified( + id: str, + name: str = None, + url: str = None, + data: List[str] = None, +): + print_function_args() + e = Events() + new_event = e.create_repository_event(event_type.RepositoryModifiedEventV1, id, name, url, data) + cdevents_command = CDeventsCommand() + cdevents_command.run(new_event) + + +@click.command(help=add_disclaimer_text("Repository Deleted CloudEvent.")) +@common_repository_options +def deleted( + id: str, + name: str = None, + url: str = None, + data: List[str] = None, +): + print_function_args() + e = Events() + new_event = e.create_repository_event(event_type.RepositoryModifiedEventV1, id, name, url, data) + cdevents_command = CDeventsCommand() + cdevents_command.run(new_event) + diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index c1ff47c..a132d47 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -1,23 +1,18 @@ """Constants Event types.""" -# PipelineRun events -PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" -PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" -PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" - -# TaskRun events -TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" -TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" - -# Repository events -RepositoryCreatedEventV1 :str = "cd.repository.created.v1" -RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" -RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" +# Artifact Events +ArtifactPackagedEventV1 :str = "cd.artifact.packaged.v1" +ArtifactPublishedEventV1 :str = "cd.artifact.published.v1" # Branch Events BranchCreatedEventV1 :str = "cd.repository.branch.created.v1" BranchDeletedEventV1 :str = "cd.repository.branch.deleted.v1" +# Build Events +BuildStartedEventV1 :str = "cd.build.started.v1" +BuildQueuedEventV1 :str = "cd.build.queued.v1" +BuildFinishedEventV1 :str = "cd.build.finished.v1" + # Change Events ChangeCreatedEventV1 :str = "cd.repository.change.created.v1" ChangeUpdatedEventV1 :str = "cd.repository.change.updated.v1" @@ -25,32 +20,36 @@ ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" -# Build Events -BuildStartedEventV1 :str = "cd.build.started.v1" -BuildQueuedEventV1 :str = "cd.build.queued.v1" -BuildFinishedEventV1 :str = "cd.build.finished.v1" - -# Test Events -TestCaseStartedEventV1 :str = "cd.test.case.started.v1" -TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" -TestCaseFinishedEventV1 :str = "cd.test.case.finished.v1" - -TestSuiteStartedEventV1 :str = "cd.test.suite.started.v1" -TestSuiteQueuedEventV1 :str = "cd.test.suite.queued.v1" -TestSuiteFinishedEventV1 :str = "cd.test.suite.finished.v1" - -# Artifact Events -ArtifactPackagedEventV1 :str = "cd.artifact.packaged.v1" -ArtifactPublishedEventV1 :str = "cd.artifact.published.v1" - # Environment Events EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" EnvironmentModifiedEventV1 :str = "cd.environment.modified.v1" EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" +# PipelineRun events +PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" +PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" +PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" + +# Repository events +RepositoryCreatedEventV1 :str = "cd.repository.created.v1" +RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" +RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" + # Service Events ServiceDeployedEventV1 :str = "cd.service.deployed.v1" ServiceUpgradedEventV1 :str = "cd.service.upgraded.v1" ServiceRolledbackEventV1 :str = "cd.service.rolledback.v1" ServiceRemovedEventV1 :str = "cd.service.removed.v1" +# TaskRun events +TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" +TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" + +# Test Events +TestCaseStartedEventV1 :str = "cd.test.case.started.v1" +TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" +TestCaseFinishedEventV1 :str = "cd.test.case.finished.v1" + +TestSuiteStartedEventV1 :str = "cd.test.suite.started.v1" +TestSuiteQueuedEventV1 :str = "cd.test.suite.queued.v1" +TestSuiteFinishedEventV1 :str = "cd.test.suite.finished.v1" diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index 02a8019..a713f64 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -90,6 +90,21 @@ def create_pipelinerun_event(self, event_type: str , id: str, name: str, status: return event + def create_repository_event(self, event_type: str , id: str, name: str, url: str, data = {}) -> CloudEvent: + """Create repository event. + """ + + extensions = { + "repositoryid": id, + "repositoryname": name, + "repositoryurl": url, + } + + event = self.create_event(event_type, extensions, data) + + return event + + def create_service_event(self, event_type: str , envid: str, name: str, version: str, data = {}) -> CloudEvent: """Create service event. """ From 6728488c8f7c3eb01cee1d472c61eebfe5bb1eaa Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Fri, 29 Jul 2022 12:11:41 +0200 Subject: [PATCH 16/34] add test cases --- core/tests/test_artifact.py | 20 +++++++++++ core/tests/test_branch.py | 20 +++++++++++ core/tests/test_build.py | 28 +++++++++++++++ core/tests/test_environment.py | 28 +++++++++++++++ core/tests/test_events.py | 62 ---------------------------------- core/tests/test_pipelinerun.py | 29 ++++++++++++++++ core/tests/test_repository.py | 28 +++++++++++++++ core/tests/test_service.py | 40 ++++++++++++++++++++++ core/tests/test_taskrun.py | 20 +++++++++++ 9 files changed, 213 insertions(+), 62 deletions(-) create mode 100644 core/tests/test_artifact.py create mode 100644 core/tests/test_branch.py create mode 100644 core/tests/test_build.py create mode 100644 core/tests/test_environment.py create mode 100644 core/tests/test_pipelinerun.py create mode 100644 core/tests/test_repository.py create mode 100644 core/tests/test_service.py create mode 100644 core/tests/test_taskrun.py diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py new file mode 100644 index 0000000..0f4cc84 --- /dev/null +++ b/core/tests/test_artifact.py @@ -0,0 +1,20 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_artifact_packaged_v1(): + event = Events().create_artifact_event(event_type.ArtifactPackagedEventV1, id="_id", name="_name", version="_version", data={"artifact": "_artifact"}) + assert event is not None + assert event._attributes["type"] == event_type.ArtifactPackagedEventV1 + assert event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} + assert event.data == {"artifact": "_artifact"} + +@pytest.mark.unit +def test_artifact_published_v1(): + event = Events().create_artifact_event(event_type.ArtifactPublishedEventV1, id="_id", name="_name", version="_version", data={"artifact": "_artifact"}) + assert event is not None + assert event._attributes["type"] == event_type.ArtifactPublishedEventV1 + assert event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} + assert event.data == {"artifact": "_artifact"} diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py new file mode 100644 index 0000000..4c304ff --- /dev/null +++ b/core/tests/test_branch.py @@ -0,0 +1,20 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_repository_branch_created(): + event = Events().create_branch_event(event_type.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"branch": "_branch"}) + assert event is not None + assert event._attributes["type"] == event_type.BranchCreatedEventV1 + assert event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} + assert event.data == {"branch": "_branch"} + +@pytest.mark.unit +def test_repository_branch_deleted(): + event = Events().create_branch_event(event_type.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid", data={"branch": "_branch"}) + assert event is not None + assert event._attributes["type"] == event_type.BranchDeletedEventV1 + assert event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} + assert event.data == {"branch": "_branch"} diff --git a/core/tests/test_build.py b/core/tests/test_build.py new file mode 100644 index 0000000..2090cc0 --- /dev/null +++ b/core/tests/test_build.py @@ -0,0 +1,28 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_build_started(): + event = Events().create_build_event(event_type.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) + assert event is not None + assert event._attributes["type"] == event_type.BuildStartedEventV1 + assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert event.data == {"build": "_build"} + +@pytest.mark.unit +def test_build_queued(): + event = Events().create_build_event(event_type.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) + assert event is not None + assert event._attributes["type"] == event_type.BuildQueuedEventV1 + assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert event.data == {"build": "_build"} + +@pytest.mark.unit +def test_build_finished(): + event = Events().create_build_event(event_type.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) + assert event is not None + assert event._attributes["type"] == event_type.BuildFinishedEventV1 + assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert event.data == {"build": "_build"} diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py new file mode 100644 index 0000000..3c3a5da --- /dev/null +++ b/core/tests/test_environment.py @@ -0,0 +1,28 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_environment_created(): + event = Events().create_environment_event(event_type.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) + assert event is not None + assert event._attributes["type"] == event_type.EnvironmentCreatedEventV1 + assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert event.data == {"environment": "_environment"} + +@pytest.mark.unit +def test_environment_modified(): + event = Events().create_environment_event(event_type.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) + assert event is not None + assert event._attributes["type"] == event_type.EnvironmentModifiedEventV1 + assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert event.data == {"environment": "_environment"} + +@pytest.mark.unit +def test_environment_deleted(): + event = Events().create_environment_event(event_type.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) + assert event is not None + assert event._attributes["type"] == event_type.EnvironmentDeletedEventV1 + assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert event.data == {"environment": "_environment"} diff --git a/core/tests/test_events.py b/core/tests/test_events.py index ec1160a..daeaa10 100644 --- a/core/tests/test_events.py +++ b/core/tests/test_events.py @@ -1,72 +1,10 @@ - - -from pickle import NONE -from cdevents.core import event_type import pytest from cdevents.core.events import Events - @pytest.mark.unit def test_create_event(): event = Events().create_event(event_type="event_type", extensions={"test": "test"}) assert event is not None assert event._attributes["type"] == "event_type" assert event._attributes["extensions"] == {"test": "test"} - -@pytest.mark.unit -def test_create_artifact_event(): - event = Events().create_artifact_event(event_type.ArtifactPackagedEventV1, id="_id", name="_name", version="_version", data={"artifact": "_artifact"}) - assert event is not None - assert event._attributes["type"] == event_type.ArtifactPackagedEventV1 - assert event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} - assert event.data == {"artifact": "_artifact"} - -@pytest.mark.unit -def test_create_branch_event(): - event = Events().create_branch_event(event_type.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"branch": "_branch"}) - assert event is not None - assert event._attributes["type"] == event_type.BranchCreatedEventV1 - assert event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} - assert event.data == {"branch": "_branch"} - -@pytest.mark.unit -def test_create_build_event(): - event = Events().create_build_event(event_type.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) - assert event is not None - assert event._attributes["type"] == event_type.BuildFinishedEventV1 - assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} - assert event.data == {"build": "_build"} - -@pytest.mark.unit -def test_create_environment_event(): - event = Events().create_environment_event(event_type.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) - assert event is not None - assert event._attributes["type"] == event_type.EnvironmentCreatedEventV1 - assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} - assert event.data == {"environment": "_environment"} - -@pytest.mark.unit -def test_create_pipelinerun_event(): - event = Events().create_pipelinerun_event(event_type.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) - assert event is not None - assert event._attributes["type"] == event_type.PipelineRunFinishedEventV1 - assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} - assert event.data == {"pipelinerun": "_pipelinerun"} - -@pytest.mark.unit -def test_create_service_event(): - event = Events().create_service_event(event_type.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) - assert event is not None - assert event._attributes["type"] == event_type.ServiceDeployedEventV1 - assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} - assert event.data == {"service": "_service"} - - -@pytest.mark.unit -def test_create_taskrun_event(): - event = Events().create_taskrun_event(event_type.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"taskrun": "_taskrun"}) - assert event is not None - assert event._attributes["type"] == event_type.TaskRunFinishedEventV1 - assert event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} - assert event.data == {"taskrun": "_taskrun"} diff --git a/core/tests/test_pipelinerun.py b/core/tests/test_pipelinerun.py new file mode 100644 index 0000000..5a4d469 --- /dev/null +++ b/core/tests/test_pipelinerun.py @@ -0,0 +1,29 @@ +from pickle import NONE +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_pipelinerun_started(): + event = Events().create_pipelinerun_event(event_type.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) + assert event is not None + assert event._attributes["type"] == event_type.PipelineRunStartedEventV1 + assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert event.data == {"pipelinerun": "_pipelinerun"} + +@pytest.mark.unit +def test_pipelinerun_finished(): + event = Events().create_pipelinerun_event(event_type.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) + assert event is not None + assert event._attributes["type"] == event_type.PipelineRunFinishedEventV1 + assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert event.data == {"pipelinerun": "_pipelinerun"} + +@pytest.mark.unit +def test_pipelinerun_queued(): + event = Events().create_pipelinerun_event(event_type.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) + assert event is not None + assert event._attributes["type"] == event_type.PipelineRunQueuedEventV1 + assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert event.data == {"pipelinerun": "_pipelinerun"} diff --git a/core/tests/test_repository.py b/core/tests/test_repository.py new file mode 100644 index 0000000..d970b03 --- /dev/null +++ b/core/tests/test_repository.py @@ -0,0 +1,28 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_repository_created(): + event = Events().create_repository_event(event_type.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"repository": "_repository"}) + assert event is not None + assert event._attributes["type"] == event_type.RepositoryCreatedEventV1 + assert event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert event.data == {"repository": "_repository"} + +@pytest.mark.unit +def test_repository_modified(): + event = Events().create_repository_event(event_type.RepositoryModifiedEventV1, id="_id", name="_name", url="_url", data={"repository": "_repository"}) + assert event is not None + assert event._attributes["type"] == event_type.RepositoryModifiedEventV1 + assert event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert event.data == {"repository": "_repository"} + +@pytest.mark.unit +def test_repository_deleted(): + event = Events().create_repository_event(event_type.RepositoryDeletedEventV1, id="_id", name="_name", url="_url", data={"repository": "_repository"}) + assert event is not None + assert event._attributes["type"] == event_type.RepositoryDeletedEventV1 + assert event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert event.data == {"repository": "_repository"} diff --git a/core/tests/test_service.py b/core/tests/test_service.py new file mode 100644 index 0000000..e8ed052 --- /dev/null +++ b/core/tests/test_service.py @@ -0,0 +1,40 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_service_deployed(): + event = Events().create_service_event(event_type.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) + assert event is not None + assert event._attributes["type"] == event_type.ServiceDeployedEventV1 + assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert event.data == {"service": "_service"} + + +@pytest.mark.unit +def test_service_upgraded(): + event = Events().create_service_event(event_type.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) + assert event is not None + assert event._attributes["type"] == event_type.ServiceUpgradedEventV1 + assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert event.data == {"service": "_service"} + + +@pytest.mark.unit +def test_service_rolledback(): + event = Events().create_service_event(event_type.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) + assert event is not None + assert event._attributes["type"] == event_type.ServiceRolledbackEventV1 + assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert event.data == {"service": "_service"} + + +@pytest.mark.unit +def test_service_removed(): + event = Events().create_service_event(event_type.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) + assert event is not None + assert event._attributes["type"] == event_type.ServiceRemovedEventV1 + assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert event.data == {"service": "_service"} + diff --git a/core/tests/test_taskrun.py b/core/tests/test_taskrun.py new file mode 100644 index 0000000..b8873b2 --- /dev/null +++ b/core/tests/test_taskrun.py @@ -0,0 +1,20 @@ +from cdevents.core import event_type +import pytest + +from cdevents.core.events import Events + +@pytest.mark.unit +def test_taskrun_started(): + event = Events().create_taskrun_event(event_type.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"taskrun": "_taskrun"}) + assert event is not None + assert event._attributes["type"] == event_type.TaskRunStartedEventV1 + assert event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} + assert event.data == {"taskrun": "_taskrun"} + +@pytest.mark.unit +def test_taskrun_finished(): + event = Events().create_taskrun_event(event_type.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"taskrun": "_taskrun"}) + assert event is not None + assert event._attributes["type"] == event_type.TaskRunFinishedEventV1 + assert event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} + assert event.data == {"taskrun": "_taskrun"} From 889a665d40d7f7f20007f2a5f122f25ac10d1e35 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Mon, 1 Aug 2022 13:49:57 +0200 Subject: [PATCH 17/34] add first cli tests --- cli/cdevents/cli/configuration_handler.py | 4 +- cli/cdevents/cli/constants.py | 2 +- cli/tests/configuration_test.yaml | 8 ++ cli/tests/test_configuration_handler.py | 49 +++++++++++ cli/tests/test_configuration_reader.py | 99 +++++++++++++++++++++++ cli/tests/test_constants.py | 17 ++++ cli/tests/test_main.py | 15 ++++ 7 files changed, 191 insertions(+), 3 deletions(-) create mode 100644 cli/tests/configuration_test.yaml create mode 100644 cli/tests/test_configuration_handler.py create mode 100644 cli/tests/test_configuration_reader.py create mode 100644 cli/tests/test_constants.py create mode 100644 cli/tests/test_main.py diff --git a/cli/cdevents/cli/configuration_handler.py b/cli/cdevents/cli/configuration_handler.py index 0428ccc..2ab089b 100644 --- a/cli/cdevents/cli/configuration_handler.py +++ b/cli/cdevents/cli/configuration_handler.py @@ -8,13 +8,13 @@ from typing import Union from cdevents.cli.configuration_reader import ConfigurationReader -from cdevents.cli.constants import DEAFULT_CONFIGURATION_FILE +from cdevents.cli.constants import DEFAULT_CONFIGURATION_FILE from cdevents.cli.utils import DictUtils def get_default_configuration_file() -> str: """Returns the default configuration file path.""" - return DEAFULT_CONFIGURATION_FILE + return DEFAULT_CONFIGURATION_FILE def new_default_configuration_handler() -> ConfigurationHandler: """Returnes a configuration handler with the default configuration file""" diff --git a/cli/cdevents/cli/constants.py b/cli/cdevents/cli/constants.py index 63c5b2a..9996948 100644 --- a/cli/cdevents/cli/constants.py +++ b/cli/cdevents/cli/constants.py @@ -3,7 +3,7 @@ # configuration/configuration.yaml _CLI_CDEVENTS_DIR = Path(__file__).parent.parent -DEAFULT_CONFIGURATION_FILE = str(Path(_CLI_CDEVENTS_DIR, "configuration", "configuration.yaml")) +DEFAULT_CONFIGURATION_FILE = str(Path(_CLI_CDEVENTS_DIR, "configuration", "configuration.yaml")) LOGGING_CONFIGURATION_FILE = str( Path(_CLI_CDEVENTS_DIR, "configuration", "logging-configuration.yaml") ) diff --git a/cli/tests/configuration_test.yaml b/cli/tests/configuration_test.yaml new file mode 100644 index 0000000..5018b4d --- /dev/null +++ b/cli/tests/configuration_test.yaml @@ -0,0 +1,8 @@ +# N.B. The file is used for testing the configuration handler. +# The content should reflect the content of the default configuration file cli/configuration/configuration.yaml +--- +configuration: + source: + name: cde-cli + client: + host: http://localhost:8080 diff --git a/cli/tests/test_configuration_handler.py b/cli/tests/test_configuration_handler.py new file mode 100644 index 0000000..8d36bc5 --- /dev/null +++ b/cli/tests/test_configuration_handler.py @@ -0,0 +1,49 @@ +"""Module for tests related to configuration_handler.""" +import os +from pathlib import Path + +import pytest + +from cdevents.cli.configuration_handler import ConfigurationHandler + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +THIS_DIR: Path = Path(__file__).parent +TEST_CONFIG_FILE: str = Path(THIS_DIR, "configuration_test.yaml").as_posix() + + +@pytest.mark.unit +def test_create_config_handler(): + + handler = ConfigurationHandler.create_new(TEST_CONFIG_FILE) + assert isinstance(handler, ConfigurationHandler) + + assert handler.source.name == "cde-cli" + assert handler.client.host == "http://localhost:8080" + + +@pytest.mark.unit +def test_create_config_handler_with_override(): + + expected_source_name = "MySourceName" + expected_client_host = "http://myhost:5000" + override_config = { + "source": { + "name": expected_source_name, + }, + "client": { + "host": expected_client_host, + }, + } + handler = ConfigurationHandler.create_new(TEST_CONFIG_FILE, override_config=override_config) + assert isinstance(handler, ConfigurationHandler) + + assert handler.source.name == expected_source_name + assert handler.client.host == expected_client_host + + +@pytest.mark.unit +def test_create_empty_override_dict(): + + expected = {} + actual = ConfigurationHandler.create_override_config() + assert expected == actual diff --git a/cli/tests/test_configuration_reader.py b/cli/tests/test_configuration_reader.py new file mode 100644 index 0000000..c0fce6f --- /dev/null +++ b/cli/tests/test_configuration_reader.py @@ -0,0 +1,99 @@ +"""Module testing ConfigurationReader""" +import json +import unittest +from pathlib import Path +from unittest.mock import patch + +import pytest +import yaml + +from cdevents.cli.configuration_reader import ConfigurationReader + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +TEST_DIR = Path(__file__).parent +CONFIG_DIR: Path = Path(TEST_DIR, "configurations") + +YAML_CONFIG_1 = """--- +configuration: + source: + name: cde-cli + client: + host: http://localhost:8080 +""" +DICT_CONFIG_1 = yaml.safe_load(YAML_CONFIG_1) + +JSON_CONFIG_1 = json.dumps(DICT_CONFIG_1) +YAML_CONFIG_2 = """--- +configuration: + source: + name: mysource + client: + host: http://myhost:5000 +""" +DICT_CONFIG_2 = { + "configuration": { + "source": {"name": "mysource"}, + "client": {"host": "http://myhost:5000"}, + }, +} + +DUMMY_PATH = "my/dummy/path/dummy.yaml" + + +class TestConfigurationReader(unittest.TestCase): + # pylint: disable=unused-argument + def setUp(self) -> None: + self.reader = ConfigurationReader() + + @pytest.mark.unit + @patch.object(Path, "exists", return_value=False) + def test_read_configuration_with_invalid_file_path_then_exception(self, mocked_exists): + with self.assertRaises(FileNotFoundError): + self.reader.read_configuration(Path(DUMMY_PATH)) + + @pytest.mark.unit + @patch.object(Path, "read_text", return_value=YAML_CONFIG_1) + @patch.object(Path, "exists", return_value=True) + def test_read_configuration_with_valid_yaml_file(self, mocked_exists, mocked_read_text): + self.reader.read_configuration(Path(DUMMY_PATH)) + actual = self.reader.configuration + self.assertDictEqual(actual, DICT_CONFIG_1) + + @pytest.mark.unit + @patch.object(Path, "read_text", return_value=JSON_CONFIG_1) + @patch.object(Path, "exists", return_value=True) + def test_read_configuration_with_valid_json_file(self, mocked_exists, mocked_read_text): + self.reader.read_configuration(Path("path/to/my/config.json")) + actual = self.reader.configuration + self.assertDictEqual(actual, DICT_CONFIG_1) + + @pytest.mark.unit + @patch.object(Path, "exists", return_value=True) + def test_read_configuration_with_invalid_filetype_then_value_error( + self, + mocked_exists, + ): + with self.assertRaises(ValueError): + self.reader.read_configuration(Path("path/to/my/invalid_config.jsonX")) + + @pytest.mark.unit + @patch.object(Path, "read_text", side_effect=[YAML_CONFIG_1, YAML_CONFIG_2]) + @patch.object(Path, "exists", return_value=True) + def test_read_configuration_with_2_configs(self, mocked_exists, mocked_read_text): + """Second configuration overwrites previous.""" + self.reader.read_configuration(Path(DUMMY_PATH)) + actual = self.reader.configuration + self.assertDictEqual(actual, DICT_CONFIG_1) + self.reader.read_configuration(Path("dummy_config2.yml")) + actual_2 = self.reader.configuration + self.assertDictEqual(actual_2, DICT_CONFIG_2) + + @pytest.mark.unit + def test_is_supported_suffix_with_valid_suffix(self): + self.assertTrue(ConfigurationReader._is_supported_json_suffix(Path("valid_suffix.json"))) + self.assertTrue(ConfigurationReader._is_supported_yaml_suffix(Path("valid_suffix.yml"))) + self.assertTrue(ConfigurationReader._is_supported_yaml_suffix(Path("valid_suffix.yAMl"))) + + @pytest.mark.unit + def test_is_supported_suffix_with_invalid_suffix(self): + self.assertFalse(ConfigurationReader._is_supported_yaml_suffix(Path("valid_suffix.berra"))) diff --git a/cli/tests/test_constants.py b/cli/tests/test_constants.py new file mode 100644 index 0000000..085e21f --- /dev/null +++ b/cli/tests/test_constants.py @@ -0,0 +1,17 @@ +"""Tests for constants.""" +from pathlib import Path + +import pytest + +from cdevents.cli.constants import DEFAULT_CONFIGURATION_FILE, LOGGING_CONFIGURATION_FILE + +# pylint: disable=missing-function-docstring, missing-class-docstring + +@pytest.mark.unit +def test_default_config_exist(): + assert Path(DEFAULT_CONFIGURATION_FILE).exists() + + +@pytest.mark.unit +def test_logging_config_file_exist(): + assert Path(LOGGING_CONFIGURATION_FILE).exists() diff --git a/cli/tests/test_main.py b/cli/tests/test_main.py new file mode 100644 index 0000000..8fdb00e --- /dev/null +++ b/cli/tests/test_main.py @@ -0,0 +1,15 @@ +import pytest +from click.testing import CliRunner + +from cdevents.cli.__main__ import cli + +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +@pytest.mark.unit +def test_cli_main(runner: CliRunner): + + result = runner.invoke(cli, ["--help"]) + assert result.exit_code == 0 From 063307fb904cbb689f38815210474bf4c3c94bee Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Mon, 1 Aug 2022 16:25:04 +0200 Subject: [PATCH 18/34] add artifact tests --- cli/tests/test_artifact.py | 80 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 cli/tests/test_artifact.py diff --git a/cli/tests/test_artifact.py b/cli/tests/test_artifact.py new file mode 100644 index 0000000..4ed109e --- /dev/null +++ b/cli/tests/test_artifact.py @@ -0,0 +1,80 @@ +"""Unit tests for artifact.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.artifact import packaged, published +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring + +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +VERSION_ARG = "version" +DATA_ARG = "data" + +@pytest.mark.unit +def test_packaged(runner: CliRunner): + """Test packaging of an artifact.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_version = "MyArtifact" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + packaged, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{VERSION_ARG}", + expected_version, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{VERSION_ARG}={expected_version}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + + + +@pytest.mark.unit +def test_published(runner: CliRunner): + """Test published of an artifact.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_version = "MyArtifact" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + published, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{VERSION_ARG}", + expected_version, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{VERSION_ARG}={expected_version}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + From 36a30471b6b215fb45ebc86f742c2abc8d61082d Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 13:31:02 +0200 Subject: [PATCH 19/34] add artifact obj --- cli/cdevents/cli/artifact.py | 18 ++++++---------- core/cdevents/core/artifact.py | 37 ++++++++++++++++++++++++++++++++ core/cdevents/core/event_type.py | 8 ++++--- core/cdevents/core/events.py | 35 ++++++++++-------------------- core/tests/test_artifact.py | 26 +++++++++++----------- 5 files changed, 74 insertions(+), 50 deletions(-) create mode 100644 core/cdevents/core/artifact.py diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 1f540dd..4d24068 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -1,16 +1,13 @@ """Module for cli artifact commands.""" from __future__ import annotations -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.artifact import Artifact, ArtifactType # pylint: disable=unused-argument def common_artifact_options(function): @@ -57,10 +54,10 @@ def packaged( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_artifact_event(event_type.ArtifactPackagedEventV1, id, name, version, data) + artifact = Artifact(ArtifactType.ArtifactPackagedEventV1, id, name, version) + artifact_event = artifact.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(artifact_event) @click.command(help=add_disclaimer_text("Artifact Published CloudEvent.")) @@ -72,8 +69,7 @@ def published( data: List[str] = None, ): print_function_args() - - e = Events() - new_event = e.create_artifact_event(event_type.ArtifactPublishedEventV1, id, name, version, data) + artifact = Artifact(ArtifactType.ArtifactPublishedEventV1, id, name, version) + artifact_event = artifact.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(artifact_event) diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py new file mode 100644 index 0000000..c8bc5c1 --- /dev/null +++ b/core/cdevents/core/artifact.py @@ -0,0 +1,37 @@ +"""artifact""" + +from enum import Enum +from cdevents.core.events import Events + +class ArtifactType(Enum): + ArtifactPackagedEventV1: str = "cd.artifact.packaged.v1" + ArtifactPublishedEventV1: str = "cd.artifact.published.v1" + + +class Artifact(Events): + """Events.""" + + def __init__(self, artifact_type: ArtifactType, id: str, name: str, version: str): + """Initializes class. + """ + self._event_type = artifact_type + self._id = id + self._name = name + self._version = version + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "artifactid": self._id, + "artifactname": self._name, + "artifactversion": self._version, + } + return extensions + + def create_event(self, data: dict={}): + """Create artifact event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index a132d47..5177d28 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -1,8 +1,10 @@ """Constants Event types.""" -# Artifact Events -ArtifactPackagedEventV1 :str = "cd.artifact.packaged.v1" -ArtifactPublishedEventV1 :str = "cd.artifact.published.v1" +# pylint: TODO: + +# # Artifact Events +# ArtifactPackagedEventV1 :str = "cd.artifact.packaged.v1" +# ArtifactPublishedEventV1 :str = "cd.artifact.published.v1" # Branch Events BranchCreatedEventV1 :str = "cd.repository.branch.created.v1" diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index a713f64..cefb811 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -22,31 +22,18 @@ def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEven return event - def create_artifact_event(self, event_type: str , id: str, name: str, version: str, data = {}) -> CloudEvent: - """Create artifact event. - """ - - extensions = { - "artifactid": id, - "artifactname": name, - "artifactversion": version, - } - event = self.create_event(event_type, extensions, data) - - return event - - def create_branch_event(self, event_type: str , id: str, name: str, repoid: str, data = {}) -> CloudEvent: - """Create branch event. - """ + # def create_branch_event(self, event_type: str , id: str, name: str, repoid: str, data = {}) -> CloudEvent: + # """Create branch event. + # """ - extensions = { - "branchid": id, - "branchname": name, - "branchrepositoryid": repoid, - } - event = self.create_event(event_type, extensions, data) - - return event + # extensions = { + # "branchid": id, + # "branchname": name, + # "branchrepositoryid": repoid, + # } + # event = self.create_event(event_type, extensions, data) + + # return event def create_build_event(self, event_type: str , id: str, name: str, artifact: str, data = {}) -> CloudEvent: diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py index 0f4cc84..da77434 100644 --- a/core/tests/test_artifact.py +++ b/core/tests/test_artifact.py @@ -1,20 +1,22 @@ -from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.artifact import Artifact, ArtifactType @pytest.mark.unit def test_artifact_packaged_v1(): - event = Events().create_artifact_event(event_type.ArtifactPackagedEventV1, id="_id", name="_name", version="_version", data={"artifact": "_artifact"}) - assert event is not None - assert event._attributes["type"] == event_type.ArtifactPackagedEventV1 - assert event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} - assert event.data == {"artifact": "_artifact"} + artifact = Artifact(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version") + artifact_event = artifact.create_event(data={"key1": "value1"}) + assert artifact_event is not None + assert artifact_event._attributes["type"] == "cd.artifact.packaged.v1" + assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} + assert artifact_event.data == {"key1": "value1"} @pytest.mark.unit def test_artifact_published_v1(): - event = Events().create_artifact_event(event_type.ArtifactPublishedEventV1, id="_id", name="_name", version="_version", data={"artifact": "_artifact"}) - assert event is not None - assert event._attributes["type"] == event_type.ArtifactPublishedEventV1 - assert event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} - assert event.data == {"artifact": "_artifact"} + artifact = Artifact(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version") + artifact_event = artifact.create_event(data={"key1": "value1"}) + assert artifact_event is not None + assert artifact_event._attributes["type"] == "cd.artifact.published.v1" + assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} + assert artifact_event.data == {"key1": "value1"} + From bf199f6831e1f31800d32175a7e95c698eac65fd Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 13:31:28 +0200 Subject: [PATCH 20/34] add branch obj --- cli/cdevents/cli/branch.py | 20 +++++----- cli/tests/test_branch.py | 77 ++++++++++++++++++++++++++++++++++++ core/cdevents/core/branch.py | 37 +++++++++++++++++ core/tests/test_branch.py | 25 ++++++------ 4 files changed, 136 insertions(+), 23 deletions(-) create mode 100644 cli/tests/test_branch.py create mode 100644 core/cdevents/core/branch.py diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index de7b9f8..2360792 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -1,7 +1,6 @@ """Module for cli branch commands.""" from __future__ import annotations -import os from typing import List import click @@ -9,8 +8,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.branch import Branch, BranchType # pylint: disable=unused-argument def common_branch_options(function): @@ -56,11 +54,11 @@ def created( repoid: str = None, data: List[str] = None, ): - print_function_args() - e = Events() - new_event = e.create_branch_event(event_type.BranchCreatedEventV1, id, name, repoid, data) + print_function_args() + branch = Branch(branch_type=BranchType.BranchCreatedEventV1, id=id, name=name, repoid=repoid) + branch_event = branch.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(branch_event) @click.command(help=add_disclaimer_text("Branch Deleted CloudEvent.")) @@ -71,8 +69,8 @@ def deleted( repoid: str = None, data: List[str] = None, ): - print_function_args() - e = Events() - new_event = e.create_branch_event(event_type.BranchDeletedEventV1, id, name, repoid, data) + print_function_args() + branch = Branch(branch_type=BranchType.BranchDeletedEventV1, id=id, name=name, repoid=repoid) + branch_event = branch.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(branch_event) diff --git a/cli/tests/test_branch.py b/cli/tests/test_branch.py new file mode 100644 index 0000000..0d9104f --- /dev/null +++ b/cli/tests/test_branch.py @@ -0,0 +1,77 @@ +"""Unit tests for artifact.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.branch import created, deleted +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring + +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +REPOID_ARG = "repoid" +DATA_ARG = "data" + +@pytest.mark.unit +def test_created(runner: CliRunner): + """Test created of a branch.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_repoid = "repo1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + created, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{REPOID_ARG}", + expected_repoid, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{REPOID_ARG}={expected_repoid}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_deleted(runner: CliRunner): + """Test deleted of a branch.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_repoid = "repo1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + deleted, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{REPOID_ARG}", + expected_repoid, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{REPOID_ARG}={expected_repoid}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py new file mode 100644 index 0000000..963310f --- /dev/null +++ b/core/cdevents/core/branch.py @@ -0,0 +1,37 @@ +"""branch""" + +from enum import Enum +from cdevents.core.events import Events + +class BranchType(Enum): + BranchCreatedEventV1: str = "cd.repository.branch.created.v1" + BranchDeletedEventV1: str = "cd.repository.branch.deleted.v1" + + +class Branch(Events): + """Events.""" + + def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str): + """Initializes class. + """ + self._event_type = branch_type + self._id = id + self._name = name + self._repoid = repoid + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "branchid": self._id, + "branchname": self._name, + "branchrepositoryid": self._repoid, + } + return extensions + + def create_event(self, data: dict={}): + """Create branch event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py index 4c304ff..41557d8 100644 --- a/core/tests/test_branch.py +++ b/core/tests/test_branch.py @@ -1,20 +1,21 @@ -from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.branch import Branch, BranchType @pytest.mark.unit def test_repository_branch_created(): - event = Events().create_branch_event(event_type.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"branch": "_branch"}) - assert event is not None - assert event._attributes["type"] == event_type.BranchCreatedEventV1 - assert event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} - assert event.data == {"branch": "_branch"} + branch = Branch(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid") + branch_event = branch.create_event(data={"key1": "value1"}) + assert branch_event is not None + assert branch_event._attributes["type"] == "cd.repository.branch.created.v1" + assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} + assert branch_event.data == {"key1": "value1"} @pytest.mark.unit def test_repository_branch_deleted(): - event = Events().create_branch_event(event_type.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid", data={"branch": "_branch"}) - assert event is not None - assert event._attributes["type"] == event_type.BranchDeletedEventV1 - assert event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} - assert event.data == {"branch": "_branch"} + branch = Branch(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid") + branch_event = branch.create_event(data={"key1": "value1"}) + assert branch_event is not None + assert branch_event._attributes["type"] == "cd.repository.branch.deleted.v1" + assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} + assert branch_event.data == {"key1": "value1"} \ No newline at end of file From 972507b909f74afae45c0dfbd7aa2f1e35222c88 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 14:08:46 +0200 Subject: [PATCH 21/34] add command line tests --- cli/tests/test_branch.py | 2 +- cli/tests/test_build.py | 108 +++++++++++++++++++++++++++ cli/tests/test_env.py | 108 +++++++++++++++++++++++++++ cli/tests/test_pipelinerun.py | 133 +++++++++++++++++++++++++++++++++ cli/tests/test_repository.py | 105 ++++++++++++++++++++++++++ cli/tests/test_service.py | 134 ++++++++++++++++++++++++++++++++++ cli/tests/test_taskrun.py | 76 +++++++++++++++++++ 7 files changed, 665 insertions(+), 1 deletion(-) create mode 100644 cli/tests/test_build.py create mode 100644 cli/tests/test_env.py create mode 100644 cli/tests/test_pipelinerun.py create mode 100644 cli/tests/test_repository.py create mode 100644 cli/tests/test_service.py create mode 100644 cli/tests/test_taskrun.py diff --git a/cli/tests/test_branch.py b/cli/tests/test_branch.py index 0d9104f..c2f8cfd 100644 --- a/cli/tests/test_branch.py +++ b/cli/tests/test_branch.py @@ -1,4 +1,4 @@ -"""Unit tests for artifact.""" +"""Unit tests for branch.""" import pytest from unittest.mock import patch from click.testing import CliRunner diff --git a/cli/tests/test_build.py b/cli/tests/test_build.py new file mode 100644 index 0000000..9c6380d --- /dev/null +++ b/cli/tests/test_build.py @@ -0,0 +1,108 @@ +"""Unit tests for build.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.build import started, finished, queued +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +ARTIFACT_ARG = "artifact" +DATA_ARG = "data" + +@pytest.mark.unit +def test_started(runner: CliRunner): + """Test started of a build.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_artifact = "artifact1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + started, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{ARTIFACT_ARG}", + expected_artifact, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{ARTIFACT_ARG}={expected_artifact}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + + +@pytest.mark.unit +def test_finished(runner: CliRunner): + """Test finished of a build.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_artifact = "artifact1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + finished, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{ARTIFACT_ARG}", + expected_artifact, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{ARTIFACT_ARG}={expected_artifact}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + + +@pytest.mark.unit +def test_queued(runner: CliRunner): + """Test queued of a build.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_artifact = "artifact1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + queued, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{ARTIFACT_ARG}", + expected_artifact, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{ARTIFACT_ARG}={expected_artifact}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + diff --git a/cli/tests/test_env.py b/cli/tests/test_env.py new file mode 100644 index 0000000..ca293f8 --- /dev/null +++ b/cli/tests/test_env.py @@ -0,0 +1,108 @@ +"""Unit tests for env.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.env import created, deleted, modified +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +REPO_ARG = "repo" +DATA_ARG = "data" + +@pytest.mark.unit +def test_started(runner: CliRunner): + """Test started of an env.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_repo = "my-repo" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + created, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{REPO_ARG}", + expected_repo, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{REPO_ARG}={expected_repo}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + + +@pytest.mark.unit +def test_started(runner: CliRunner): + """Test started of an env.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_repo = "my-repo" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + deleted, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{REPO_ARG}", + expected_repo, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{REPO_ARG}={expected_repo}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + + +@pytest.mark.unit +def test_started(runner: CliRunner): + """Test started of an env.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_repo = "my-repo" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + modified, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{REPO_ARG}", + expected_repo, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{REPO_ARG}={expected_repo}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + diff --git a/cli/tests/test_pipelinerun.py b/cli/tests/test_pipelinerun.py new file mode 100644 index 0000000..b90ac8f --- /dev/null +++ b/cli/tests/test_pipelinerun.py @@ -0,0 +1,133 @@ +"""Unit tests for pipelinerun.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.pipelinerun import started, finished, queued +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +STATUS_ARG = "status" +URL_ARG = "url" +ERRORS_ARG = "errors" +DATA_ARG = "data" + +@pytest.mark.unit +def test_started(runner: CliRunner): + """Test started of an env.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_status = "success" + expected_url = "https://my-url.com" + expected_errors = "my-errors" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + started, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{STATUS_ARG}", + expected_status, + f"--{URL_ARG}", + expected_url, + f"--{ERRORS_ARG}", + expected_errors, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{STATUS_ARG}={expected_status}" in result.stdout + assert f"{URL_ARG}={expected_url}" in result.stdout + assert f"{ERRORS_ARG}={expected_errors}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + + +@pytest.mark.unit +def test_finished(runner: CliRunner): + """Test finished of an env.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_status = "success" + expected_url = "https://my-url.com" + expected_errors = "my-errors" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + finished, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{STATUS_ARG}", + expected_status, + f"--{URL_ARG}", + expected_url, + f"--{ERRORS_ARG}", + expected_errors, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{STATUS_ARG}={expected_status}" in result.stdout + assert f"{URL_ARG}={expected_url}" in result.stdout + assert f"{ERRORS_ARG}={expected_errors}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_queued(runner: CliRunner): + """Test queued of an env.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_status = "success" + expected_url = "https://my-url.com" + expected_errors = "my-errors" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + queued, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{STATUS_ARG}", + expected_status, + f"--{URL_ARG}", + expected_url, + f"--{ERRORS_ARG}", + expected_errors, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{STATUS_ARG}={expected_status}" in result.stdout + assert f"{URL_ARG}={expected_url}" in result.stdout + assert f"{ERRORS_ARG}={expected_errors}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + diff --git a/cli/tests/test_repository.py b/cli/tests/test_repository.py new file mode 100644 index 0000000..bd13089 --- /dev/null +++ b/cli/tests/test_repository.py @@ -0,0 +1,105 @@ +"""Unit tests for repository.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.repository import created, deleted, modified +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +URL_ARG = "url" +DATA_ARG = "data" + +@pytest.mark.unit +def test_created(runner: CliRunner): + """Test created of an repository.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_url = "https://my-url.com" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + created, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{URL_ARG}", + expected_url, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{URL_ARG}={expected_url}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_modified(runner: CliRunner): + """Test modified of an repository.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_url = "https://my-url.com" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + modified, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{URL_ARG}", + expected_url, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{URL_ARG}={expected_url}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_deleted(runner: CliRunner): + """Test deleted of an repository.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_url = "https://my-url.com" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + deleted, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{URL_ARG}", + expected_url, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{URL_ARG}={expected_url}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout diff --git a/cli/tests/test_service.py b/cli/tests/test_service.py new file mode 100644 index 0000000..cb9bca0 --- /dev/null +++ b/cli/tests/test_service.py @@ -0,0 +1,134 @@ +"""Unit tests for service.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.service import deployed, upgraded, removed, rolledback +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ENVID_ARG = "envid" +NAME_ARG = "name" +VERSION_ARG = "version" +DATA_ARG = "data" + +@pytest.mark.unit +def test_deployed(runner: CliRunner): + """Test deployed of an service.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_version = "1.0.0" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + deployed, + [ + f"--{ENVID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{VERSION_ARG}", + expected_version, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ENVID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{VERSION_ARG}={expected_version}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_upgraded(runner: CliRunner): + """Test upgraded of an service.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_version = "1.0.0" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + upgraded, + [ + f"--{ENVID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{VERSION_ARG}", + expected_version, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ENVID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{VERSION_ARG}={expected_version}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_removed(runner: CliRunner): + """Test removed of an service.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_version = "1.0.0" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + removed, + [ + f"--{ENVID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{VERSION_ARG}", + expected_version, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ENVID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{VERSION_ARG}={expected_version}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_rolledback(runner: CliRunner): + """Test rolledback of an service.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_version = "1.0.0" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + rolledback, + [ + f"--{ENVID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{VERSION_ARG}", + expected_version, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ENVID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{VERSION_ARG}={expected_version}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout diff --git a/cli/tests/test_taskrun.py b/cli/tests/test_taskrun.py new file mode 100644 index 0000000..ba134d2 --- /dev/null +++ b/cli/tests/test_taskrun.py @@ -0,0 +1,76 @@ +"""Unit tests for taskrun.""" +import pytest +from unittest.mock import patch +from click.testing import CliRunner + +from cdevents.cli.taskrun import started, finished +from cdevents.cli.cdevents_command import CDeventsCommand + +# pylint: disable=missing-function-docstring, protected-access, missing-class-docstring +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +ID_ARG = "id" +NAME_ARG = "name" +PIPLINEID_ARG = "pipelineid" +DATA_ARG = "data" + +@pytest.mark.unit +def test_started(runner: CliRunner): + """Test started of an taskrun.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_pipelineid = "pipeline1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + started, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{PIPLINEID_ARG}", + expected_pipelineid, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{PIPLINEID_ARG}={expected_pipelineid}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout + +@pytest.mark.unit +def test_finished(runner: CliRunner): + """Test finished of an taskrun.""" + + expected_id = "task1" + expected_name = "My Task Run" + expected_pipelineid = "pipeline1" + expected_data = ["key1", "value1"] + + with patch.object(CDeventsCommand, "run", spec=CDeventsCommand): + result = runner.invoke( + finished, + [ + f"--{ID_ARG}", + expected_id, + f"--{NAME_ARG}", + expected_name, + f"--{PIPLINEID_ARG}", + expected_pipelineid, + f"--{DATA_ARG}", + *expected_data, + ], + ) + assert result.exit_code == 0 + assert f"{ID_ARG}={expected_id}" in result.stdout + assert f"{NAME_ARG}={expected_name}" in result.stdout + assert f"{PIPLINEID_ARG}={expected_pipelineid}" in result.stdout + assert f"{DATA_ARG}=({tuple(expected_data)},)" in result.stdout From f08971880cb00f0ea601ac842f5133cb065132c8 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 14:35:29 +0200 Subject: [PATCH 22/34] add build and env obj --- cli/cdevents/cli/build.py | 21 ++++++++--------- cli/cdevents/cli/env.py | 21 ++++++++--------- core/cdevents/core/artifact.py | 2 +- core/cdevents/core/branch.py | 2 +- core/cdevents/core/build.py | 38 ++++++++++++++++++++++++++++++ core/cdevents/core/env.py | 38 ++++++++++++++++++++++++++++++ core/cdevents/core/event_type.py | 18 -------------- core/cdevents/core/events.py | 40 -------------------------------- core/tests/test_artifact.py | 4 ++-- core/tests/test_branch.py | 4 ++-- core/tests/test_build.py | 36 ++++++++++++++-------------- core/tests/test_environment.py | 36 +++++++++++++++------------- 12 files changed, 141 insertions(+), 119 deletions(-) create mode 100644 core/cdevents/core/build.py create mode 100644 core/cdevents/core/env.py diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 05298e8..d39a4aa 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -9,8 +9,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.build import Build, BuildType # pylint: disable=unused-argument def common_build_options(function): @@ -58,10 +57,10 @@ def started( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_build_event(event_type.BuildStartedEventV1, id, name, artifact, data) + build = Build(build_type=BuildType.BuildStartedEventV1, id=id, name=name, artifact=artifact) + build_event = build.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(build_event) @click.command(help=add_disclaimer_text("Build Finished CloudEvent.")) @common_build_options @@ -72,10 +71,10 @@ def finished( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_build_event(event_type.BuildFinishedEventV1, id, name, artifact, data) + build = Build(build_type=BuildType.BuildFinishedEventV1, id=id, name=name, artifact=artifact) + build_event = build.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(build_event) @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_build_options @@ -86,7 +85,7 @@ def queued( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_build_event(event_type.BuildQueuedEventV1, id, name, artifact, data) + build = Build(build_type=BuildType.BuildQueuedEventV1, id=id, name=name, artifact=artifact) + build_event = build.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(build_event) diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index f728738..cd6b5f2 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -9,8 +9,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.env import Env, EnvType # pylint: disable=unused-argument def common_env_options(function): @@ -57,10 +56,10 @@ def created( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_environment_event(event_type.EnvironmentCreatedEventV1, id, name, repo, data) + env = Env(build_type=EnvType.EnvironmentCreatedEventV1, id=id, name=name, repo=repo) + env_event = env.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(env_event) @click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) @@ -72,10 +71,10 @@ def deleted( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_environment_event(event_type.EnvironmentDeletedEventV1, id, name, repo, data) + env = Env(env_type=EnvType.EnvironmentDeletedEventV1, id=id, name=name, repo=repo) + env_event = env.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(env_event) @click.command(help=add_disclaimer_text("Environment Modified CloudEvent.")) @common_env_options @@ -86,7 +85,7 @@ def modified( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_environment_event(event_type.EnvironmentModifiedEventV1, id, name, repo, data) + env = Env(env_type=EnvType.EnvironmentModifiedEventV1, id=id, name=name, repo=repo) + env_event = env.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) \ No newline at end of file + cdevents_command.run(env_event) \ No newline at end of file diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py index c8bc5c1..1b5ede1 100644 --- a/core/cdevents/core/artifact.py +++ b/core/cdevents/core/artifact.py @@ -9,7 +9,7 @@ class ArtifactType(Enum): class Artifact(Events): - """Events.""" + """Artifact.""" def __init__(self, artifact_type: ArtifactType, id: str, name: str, version: str): """Initializes class. diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index 963310f..4b603f1 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -9,7 +9,7 @@ class BranchType(Enum): class Branch(Events): - """Events.""" + """Brach.""" def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str): """Initializes class. diff --git a/core/cdevents/core/build.py b/core/cdevents/core/build.py new file mode 100644 index 0000000..e8b1f13 --- /dev/null +++ b/core/cdevents/core/build.py @@ -0,0 +1,38 @@ +"""build""" + +from enum import Enum +from cdevents.core.events import Events + +class BuildType(Enum): + BuildStartedEventV1 :str = "cd.build.started.v1" + BuildQueuedEventV1 :str = "cd.build.queued.v1" + BuildFinishedEventV1 :str = "cd.build.finished.v1" + + +class Build(Events): + """build.""" + + def __init__(self, build_type: BuildType, id: str, name: str, artifact: str): + """Initializes class. + """ + self._event_type = build_type + self._id = id + self._name = name + self._artifact = artifact + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "buildid": self._id, + "buildname": self._name, + "buildartifactid": self._artifact, + } + return extensions + + def create_event(self, data: dict={}): + """Create build event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/cdevents/core/env.py b/core/cdevents/core/env.py new file mode 100644 index 0000000..aaf8733 --- /dev/null +++ b/core/cdevents/core/env.py @@ -0,0 +1,38 @@ +"""env""" + +from enum import Enum +from cdevents.core.events import Events + +class EnvType(Enum): + EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" + EnvironmentModifiedEventV1 :str = "cd.environment.modified.v1" + EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" + + +class Env(Events): + """Env.""" + + def __init__(self, env_type: EnvType, id: str, name: str, repo: str): + """Initializes class. + """ + self._event_type = env_type + self._id = id + self._name = name + self._repo = repo + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "envId": self._id, + "envname": self._name, + "envrepourl": self._repo, + } + return extensions + + def create_event(self, data: dict={}): + """Create env event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index 5177d28..59b9c23 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -2,19 +2,6 @@ # pylint: TODO: -# # Artifact Events -# ArtifactPackagedEventV1 :str = "cd.artifact.packaged.v1" -# ArtifactPublishedEventV1 :str = "cd.artifact.published.v1" - -# Branch Events -BranchCreatedEventV1 :str = "cd.repository.branch.created.v1" -BranchDeletedEventV1 :str = "cd.repository.branch.deleted.v1" - -# Build Events -BuildStartedEventV1 :str = "cd.build.started.v1" -BuildQueuedEventV1 :str = "cd.build.queued.v1" -BuildFinishedEventV1 :str = "cd.build.finished.v1" - # Change Events ChangeCreatedEventV1 :str = "cd.repository.change.created.v1" ChangeUpdatedEventV1 :str = "cd.repository.change.updated.v1" @@ -22,11 +9,6 @@ ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" -# Environment Events -EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" -EnvironmentModifiedEventV1 :str = "cd.environment.modified.v1" -EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" - # PipelineRun events PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index cefb811..29bed39 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -22,46 +22,6 @@ def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEven return event - # def create_branch_event(self, event_type: str , id: str, name: str, repoid: str, data = {}) -> CloudEvent: - # """Create branch event. - # """ - - # extensions = { - # "branchid": id, - # "branchname": name, - # "branchrepositoryid": repoid, - # } - # event = self.create_event(event_type, extensions, data) - - # return event - - - def create_build_event(self, event_type: str , id: str, name: str, artifact: str, data = {}) -> CloudEvent: - """Create build event. - """ - - extensions = { - "buildid": id, - "buildname": name, - "buildartifactid": artifact, - } - event = self.create_event(event_type, extensions, data) - - return event - - def create_environment_event(self, event_type: str , id: str, name: str, repo: str, data = {}) -> CloudEvent: - """Create environment event. - """ - - extensions = { - "envId": id, - "envname": name, - "envrepourl": repo, - } - event = self.create_event(event_type, extensions, data) - - return event - def create_pipelinerun_event(self, event_type: str , id: str, name: str, status: str, url: str, errors: str, data = {}) -> CloudEvent: """Create pipelinerun event. """ diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py index da77434..6200b71 100644 --- a/core/tests/test_artifact.py +++ b/core/tests/test_artifact.py @@ -7,7 +7,7 @@ def test_artifact_packaged_v1(): artifact = Artifact(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version") artifact_event = artifact.create_event(data={"key1": "value1"}) assert artifact_event is not None - assert artifact_event._attributes["type"] == "cd.artifact.packaged.v1" + assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} assert artifact_event.data == {"key1": "value1"} @@ -16,7 +16,7 @@ def test_artifact_published_v1(): artifact = Artifact(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version") artifact_event = artifact.create_event(data={"key1": "value1"}) assert artifact_event is not None - assert artifact_event._attributes["type"] == "cd.artifact.published.v1" + assert artifact_event._attributes["type"] ==ArtifactType.ArtifactPublishedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} assert artifact_event.data == {"key1": "value1"} diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py index 41557d8..8fdbe28 100644 --- a/core/tests/test_branch.py +++ b/core/tests/test_branch.py @@ -7,7 +7,7 @@ def test_repository_branch_created(): branch = Branch(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid") branch_event = branch.create_event(data={"key1": "value1"}) assert branch_event is not None - assert branch_event._attributes["type"] == "cd.repository.branch.created.v1" + assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} assert branch_event.data == {"key1": "value1"} @@ -16,6 +16,6 @@ def test_repository_branch_deleted(): branch = Branch(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid") branch_event = branch.create_event(data={"key1": "value1"}) assert branch_event is not None - assert branch_event._attributes["type"] == "cd.repository.branch.deleted.v1" + assert branch_event._attributes["type"] == BranchType.BranchDeletedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} assert branch_event.data == {"key1": "value1"} \ No newline at end of file diff --git a/core/tests/test_build.py b/core/tests/test_build.py index 2090cc0..0a1875d 100644 --- a/core/tests/test_build.py +++ b/core/tests/test_build.py @@ -1,28 +1,30 @@ -from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.build import Build, BuildType @pytest.mark.unit def test_build_started(): - event = Events().create_build_event(event_type.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) - assert event is not None - assert event._attributes["type"] == event_type.BuildStartedEventV1 - assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} - assert event.data == {"build": "_build"} + build = Build(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact") + build_event = build.create_event(data={"key1": "value1"}) + assert build_event is not None + assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value + assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert build_event.data == {"key1": "value1"} @pytest.mark.unit def test_build_queued(): - event = Events().create_build_event(event_type.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) - assert event is not None - assert event._attributes["type"] == event_type.BuildQueuedEventV1 - assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} - assert event.data == {"build": "_build"} + build = Build(build_type=BuildType.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact") + build_event = build.create_event(data={"key1": "value1"}) + assert build_event is not None + assert build_event._attributes["type"] == BuildType.BuildQueuedEventV1.value + assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert build_event.data == {"key1": "value1"} @pytest.mark.unit def test_build_finished(): - event = Events().create_build_event(event_type.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"build": "_build"}) - assert event is not None - assert event._attributes["type"] == event_type.BuildFinishedEventV1 - assert event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} - assert event.data == {"build": "_build"} + build = Build(build_type=BuildType.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact") + build_event = build.create_event(data={"key1": "value1"}) + assert build_event is not None + assert build_event._attributes["type"] == BuildType.BuildFinishedEventV1.value + assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert build_event.data == {"key1": "value1"} diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py index 3c3a5da..81904b4 100644 --- a/core/tests/test_environment.py +++ b/core/tests/test_environment.py @@ -1,28 +1,32 @@ from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.env import Env, EnvType @pytest.mark.unit def test_environment_created(): - event = Events().create_environment_event(event_type.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) - assert event is not None - assert event._attributes["type"] == event_type.EnvironmentCreatedEventV1 - assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} - assert event.data == {"environment": "_environment"} + env = Env(env_type=EnvType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo") + env_event = env.create_event(data={"key1": "value1"}) + assert env_event is not None + assert env_event._attributes["type"] == EnvType.EnvironmentCreatedEventV1.value + assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert env_event.data == {"key1": "value1"} + @pytest.mark.unit def test_environment_modified(): - event = Events().create_environment_event(event_type.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) - assert event is not None - assert event._attributes["type"] == event_type.EnvironmentModifiedEventV1 - assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} - assert event.data == {"environment": "_environment"} + env = Env(env_type=EnvType.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo") + env_event = env.create_event(data={"key1": "value1"}) + assert env_event is not None + assert env_event._attributes["type"] == EnvType.EnvironmentModifiedEventV1.value + assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert env_event.data == {"key1": "value1"} @pytest.mark.unit def test_environment_deleted(): - event = Events().create_environment_event(event_type.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo", data={"environment": "_environment"}) - assert event is not None - assert event._attributes["type"] == event_type.EnvironmentDeletedEventV1 - assert event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} - assert event.data == {"environment": "_environment"} + env = Env(env_type=EnvType.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo") + env_event = env.create_event(data={"key1": "value1"}) + assert env_event is not None + assert env_event._attributes["type"] == EnvType.EnvironmentDeletedEventV1.value + assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert env_event.data == {"key1": "value1"} \ No newline at end of file From 2aa7160f1c81d31ddbb497ecbfe819b54ea4609d Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 14:46:39 +0200 Subject: [PATCH 23/34] add PipelineRun obj --- cli/cdevents/cli/env.py | 3 --- cli/cdevents/cli/pipelinerun.py | 27 +++++++++----------- core/cdevents/core/event_type.py | 5 ---- core/cdevents/core/events.py | 15 ----------- core/cdevents/core/pipelinerun.py | 42 +++++++++++++++++++++++++++++++ core/tests/test_environment.py | 1 - core/tests/test_pipelinerun.py | 37 ++++++++++++++------------- 7 files changed, 73 insertions(+), 57 deletions(-) create mode 100644 core/cdevents/core/pipelinerun.py diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index cd6b5f2..6eeb8f9 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -1,9 +1,6 @@ """Module for cli environment commands.""" from __future__ import annotations - -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 5c3efe9..33eba34 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -1,16 +1,12 @@ """Module for cli pipelinerun commands.""" from __future__ import annotations - -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.pipelinerun import Pipelinerun, PipelinerunType # pylint: disable=unused-argument def common_pipelinerun_options(function): @@ -73,11 +69,10 @@ def started( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_pipelinerun_event(event_type.PipelineRunStartedEventV1, id, name, status, url, errors, data) + pipelinerun = Pipelinerun(PipelinerunType.PipelineRunStartedEventV1, id=id, name=name, status=status, url=url, errors=errors) + pipelinerun_event = pipelinerun.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) - + cdevents_command.run(pipelinerun_event) @click.command(help=add_disclaimer_text("PipelineRun Finished CloudEvent.")) @common_pipelinerun_options @@ -90,10 +85,11 @@ def finished( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_pipelinerun_event(event_type.PipelineRunFinishedEventV1, id, name, status, url, errors, data) + pipelinerun = Pipelinerun(PipelinerunType.PipelineRunFinishedEventV1, id=id, name=name, status=status, url=url, errors=errors) + pipelinerun_event = pipelinerun.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(pipelinerun_event) + @click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent.")) @common_pipelinerun_options @@ -106,8 +102,9 @@ def queued( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_pipelinerun_event(event_type.PipelineRunQueuedEventV1, id, name, status, url, errors, data) + pipelinerun = Pipelinerun(PipelinerunType.PipelineRunQueuedEventV1, id=id, name=name, status=status, url=url, errors=errors) + pipelinerun_event = pipelinerun.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(pipelinerun_event) + diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index 59b9c23..0589ba1 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -9,11 +9,6 @@ ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" -# PipelineRun events -PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" -PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" -PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" - # Repository events RepositoryCreatedEventV1 :str = "cd.repository.created.v1" RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index 29bed39..b172ee7 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -22,21 +22,6 @@ def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEven return event - def create_pipelinerun_event(self, event_type: str , id: str, name: str, status: str, url: str, errors: str, data = {}) -> CloudEvent: - """Create pipelinerun event. - """ - - extensions = { - "pipelinerunid": id, - "pipelinerunname": name, - "pipelinerunstatus": status, - "pipelinerunurl": url, - "pipelinerunerrors": errors, - } - event = self.create_event(event_type, extensions, data) - - return event - def create_repository_event(self, event_type: str , id: str, name: str, url: str, data = {}) -> CloudEvent: """Create repository event. """ diff --git a/core/cdevents/core/pipelinerun.py b/core/cdevents/core/pipelinerun.py new file mode 100644 index 0000000..c74562e --- /dev/null +++ b/core/cdevents/core/pipelinerun.py @@ -0,0 +1,42 @@ +"""pipelinerun""" + +from enum import Enum +from cdevents.core.events import Events + +class PipelinerunType(Enum): + PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" + PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" + PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" + + +class Pipelinerun(Events): + """Pipelinerun.""" + + def __init__(self, pipelinerun_type: PipelinerunType, id: str, name: str, status: str, url: str, errors: str): + """Initializes class. + """ + self._event_type = pipelinerun_type + self._id = id + self._name = name + self._status = status + self._url = url + self._errors = errors + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "pipelinerunid": self._id, + "pipelinerunname": self._name, + "pipelinerunstatus": self._status, + "pipelinerunurl": self._url, + "pipelinerunerrors": self._errors, + } + return extensions + + def create_event(self, data: dict={}): + """Create pipelinerun event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py index 81904b4..0114535 100644 --- a/core/tests/test_environment.py +++ b/core/tests/test_environment.py @@ -1,4 +1,3 @@ -from cdevents.core import event_type import pytest from cdevents.core.env import Env, EnvType diff --git a/core/tests/test_pipelinerun.py b/core/tests/test_pipelinerun.py index 5a4d469..4825311 100644 --- a/core/tests/test_pipelinerun.py +++ b/core/tests/test_pipelinerun.py @@ -1,29 +1,30 @@ -from pickle import NONE -from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.pipelinerun import Pipelinerun, PipelinerunType @pytest.mark.unit def test_pipelinerun_started(): - event = Events().create_pipelinerun_event(event_type.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) - assert event is not None - assert event._attributes["type"] == event_type.PipelineRunStartedEventV1 - assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} - assert event.data == {"pipelinerun": "_pipelinerun"} + pipelinerun = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors") + pipelinerun_event = pipelinerun.create_event(data={"key1": "value1"}) + assert pipelinerun_event is not None + assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value + assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert pipelinerun_event.data == {"key1": "value1"} @pytest.mark.unit def test_pipelinerun_finished(): - event = Events().create_pipelinerun_event(event_type.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) - assert event is not None - assert event._attributes["type"] == event_type.PipelineRunFinishedEventV1 - assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} - assert event.data == {"pipelinerun": "_pipelinerun"} + pipelinerun = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors") + pipelinerun_event = pipelinerun.create_event(data={"key1": "value1"}) + assert pipelinerun_event is not None + assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunFinishedEventV1.value + assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert pipelinerun_event.data == {"key1": "value1"} @pytest.mark.unit def test_pipelinerun_queued(): - event = Events().create_pipelinerun_event(event_type.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"pipelinerun": "_pipelinerun"}) - assert event is not None - assert event._attributes["type"] == event_type.PipelineRunQueuedEventV1 - assert event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} - assert event.data == {"pipelinerun": "_pipelinerun"} + pipelinerun = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors") + pipelinerun_event = pipelinerun.create_event(data={"key1": "value1"}) + assert pipelinerun_event is not None + assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunQueuedEventV1.value + assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert pipelinerun_event.data == {"key1": "value1"} From f53567a0846afc6b55cb6812b883f6490bab3ea6 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 14:57:36 +0200 Subject: [PATCH 24/34] add repository obj --- cli/cdevents/cli/repository.py | 24 +++++++++----------- core/cdevents/core/events.py | 13 ----------- core/cdevents/core/repository.py | 38 ++++++++++++++++++++++++++++++++ core/tests/test_repository.py | 38 ++++++++++++++++++-------------- 4 files changed, 70 insertions(+), 43 deletions(-) create mode 100644 core/cdevents/core/repository.py diff --git a/cli/cdevents/cli/repository.py b/cli/cdevents/cli/repository.py index faff5ed..c06d9cd 100644 --- a/cli/cdevents/cli/repository.py +++ b/cli/cdevents/cli/repository.py @@ -1,16 +1,12 @@ """Module for cli repository commands.""" from __future__ import annotations - -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.repository import Repository, RepositoryType # pylint: disable=unused-argument def common_repository_options(function): @@ -57,10 +53,10 @@ def created( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_repository_event(event_type.RepositoryCreatedEventV1, id, name, url, data) + repository = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url) + pipelinerun_event = repository.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(pipelinerun_event) @click.command(help=add_disclaimer_text("Repository Modified CloudEvent.")) @@ -72,10 +68,10 @@ def modified( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_repository_event(event_type.RepositoryModifiedEventV1, id, name, url, data) + repository = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url) + pipelinerun_event = repository.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(pipelinerun_event) @click.command(help=add_disclaimer_text("Repository Deleted CloudEvent.")) @@ -87,8 +83,8 @@ def deleted( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_repository_event(event_type.RepositoryModifiedEventV1, id, name, url, data) + repository = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url) + pipelinerun_event = repository.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(pipelinerun_event) diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index b172ee7..fa1a45f 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -22,19 +22,6 @@ def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEven return event - def create_repository_event(self, event_type: str , id: str, name: str, url: str, data = {}) -> CloudEvent: - """Create repository event. - """ - - extensions = { - "repositoryid": id, - "repositoryname": name, - "repositoryurl": url, - } - - event = self.create_event(event_type, extensions, data) - - return event def create_service_event(self, event_type: str , envid: str, name: str, version: str, data = {}) -> CloudEvent: diff --git a/core/cdevents/core/repository.py b/core/cdevents/core/repository.py new file mode 100644 index 0000000..973fc05 --- /dev/null +++ b/core/cdevents/core/repository.py @@ -0,0 +1,38 @@ +"""repository""" + +from enum import Enum +from cdevents.core.events import Events + +class RepositoryType(Enum): + RepositoryCreatedEventV1 :str = "cd.repository.created.v1" + RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" + RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" + + +class Repository(Events): + """Repository.""" + + def __init__(self, repository_type: RepositoryType, id: str, name: str, url: str): + """Initializes class. + """ + self._event_type = repository_type + self._id = id + self._name = name + self._url = url + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "repositoryid": self._id, + "repositoryname": self._name, + "repositoryurl": self._url, + } + return extensions + + def create_event(self, data: dict={}): + """Create Repository event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/tests/test_repository.py b/core/tests/test_repository.py index d970b03..50a3be8 100644 --- a/core/tests/test_repository.py +++ b/core/tests/test_repository.py @@ -1,28 +1,34 @@ from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.repository import Repository, RepositoryType @pytest.mark.unit def test_repository_created(): - event = Events().create_repository_event(event_type.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"repository": "_repository"}) - assert event is not None - assert event._attributes["type"] == event_type.RepositoryCreatedEventV1 - assert event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} - assert event.data == {"repository": "_repository"} + repository = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url") + repository_event = repository.create_event(data={"key1": "value1"}) + assert repository_event is not None + assert repository_event._attributes["type"] == RepositoryType.RepositoryCreatedEventV1.value + assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert repository_event.data == {"key1": "value1"} + @pytest.mark.unit def test_repository_modified(): - event = Events().create_repository_event(event_type.RepositoryModifiedEventV1, id="_id", name="_name", url="_url", data={"repository": "_repository"}) - assert event is not None - assert event._attributes["type"] == event_type.RepositoryModifiedEventV1 - assert event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} - assert event.data == {"repository": "_repository"} + repository = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id="_id", name="_name", url="_url") + repository_event = repository.create_event(data={"key1": "value1"}) + assert repository_event is not None + assert repository_event._attributes["type"] == RepositoryType.RepositoryModifiedEventV1.value + assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert repository_event.data == {"key1": "value1"} + @pytest.mark.unit def test_repository_deleted(): - event = Events().create_repository_event(event_type.RepositoryDeletedEventV1, id="_id", name="_name", url="_url", data={"repository": "_repository"}) - assert event is not None - assert event._attributes["type"] == event_type.RepositoryDeletedEventV1 - assert event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} - assert event.data == {"repository": "_repository"} + repository = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id="_id", name="_name", url="_url") + repository_event = repository.create_event(data={"key1": "value1"}) + assert repository_event is not None + assert repository_event._attributes["type"] == RepositoryType.RepositoryDeletedEventV1.value + assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert repository_event.data == {"key1": "value1"} + From 2c98ad4cc0d02d766a7058b3e9ce2a1c12a8b909 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 15:03:22 +0200 Subject: [PATCH 25/34] add service obj --- cli/cdevents/cli/artifact.py | 1 - cli/cdevents/cli/branch.py | 2 -- cli/cdevents/cli/build.py | 3 --- cli/cdevents/cli/repository.py | 12 +++++----- cli/cdevents/cli/service.py | 31 +++++++++++-------------- core/cdevents/core/event_type.py | 11 --------- core/cdevents/core/events.py | 16 ------------- core/cdevents/core/service.py | 39 ++++++++++++++++++++++++++++++++ 8 files changed, 58 insertions(+), 57 deletions(-) create mode 100644 core/cdevents/core/service.py diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 4d24068..94f4538 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -1,6 +1,5 @@ """Module for cli artifact commands.""" from __future__ import annotations - from typing import List import click diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index 2360792..c25e620 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -1,8 +1,6 @@ """Module for cli branch commands.""" from __future__ import annotations - from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index d39a4aa..ee9a621 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -1,9 +1,6 @@ """Module for cli build commands.""" from __future__ import annotations - -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args diff --git a/cli/cdevents/cli/repository.py b/cli/cdevents/cli/repository.py index c06d9cd..99db8f8 100644 --- a/cli/cdevents/cli/repository.py +++ b/cli/cdevents/cli/repository.py @@ -54,9 +54,9 @@ def created( ): print_function_args() repository = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url) - pipelinerun_event = repository.create_event(data) + repository_event = repository.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(pipelinerun_event) + cdevents_command.run(repository_event) @click.command(help=add_disclaimer_text("Repository Modified CloudEvent.")) @@ -69,9 +69,9 @@ def modified( ): print_function_args() repository = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url) - pipelinerun_event = repository.create_event(data) + repository_event = repository.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(pipelinerun_event) + cdevents_command.run(repository_event) @click.command(help=add_disclaimer_text("Repository Deleted CloudEvent.")) @@ -84,7 +84,7 @@ def deleted( ): print_function_args() repository = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url) - pipelinerun_event = repository.create_event(data) + repository_event = repository.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(pipelinerun_event) + cdevents_command.run(repository_event) diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index 0c085c6..1c3cbf2 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -1,16 +1,12 @@ """Module for cli service commands.""" from __future__ import annotations - -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.service import Service, ServiceType # pylint: disable=unused-argument def common_service_options(function): @@ -57,11 +53,10 @@ def deployed( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_service_event(event_type.ServiceDeployedEventV1, envid, name, version, data) + service = Service(service_type=ServiceType.ServiceDeployedEventV1, envid=envid, name=name, version=version) + service_event = service.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) - + cdevents_command.run(service_event) @click.command(help=add_disclaimer_text("Service Upgraded CloudEvent.")) @common_service_options @@ -72,10 +67,10 @@ def upgraded( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_service_event(event_type.ServiceUpgradedEventV1, envid, name, version, data) + service = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid=envid, name=name, version=version) + service_event = service.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(service_event) @click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) @@ -87,10 +82,10 @@ def removed( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_service_event(event_type.ServiceRemovedEventV1, envid, name, version, data) + service = Service(service_type=ServiceType.ServiceRemovedEventV1, envid=envid, name=name, version=version) + service_event = service.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(service_event) @click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) @@ -102,7 +97,7 @@ def rolledback( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_service_event(event_type.ServiceRolledbackEventV1, envid, name, version, data) + service = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid=envid, name=name, version=version) + service_event = service.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(service_event) diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index 0589ba1..59feb30 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -9,17 +9,6 @@ ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" -# Repository events -RepositoryCreatedEventV1 :str = "cd.repository.created.v1" -RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" -RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" - -# Service Events -ServiceDeployedEventV1 :str = "cd.service.deployed.v1" -ServiceUpgradedEventV1 :str = "cd.service.upgraded.v1" -ServiceRolledbackEventV1 :str = "cd.service.rolledback.v1" -ServiceRemovedEventV1 :str = "cd.service.removed.v1" - # TaskRun events TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index fa1a45f..05e0fac 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -23,22 +23,6 @@ def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEven return event - - def create_service_event(self, event_type: str , envid: str, name: str, version: str, data = {}) -> CloudEvent: - """Create service event. - """ - - extensions = { - "serviceenvid": envid, - "servicename": name, - "serviceversion": version, - } - - event = self.create_event(event_type, extensions, data) - - return event - - def create_taskrun_event(self, event_type: str, id: str, name: str, pipelineid: str, data = {}) -> CloudEvent: """Create taskrun event. """ diff --git a/core/cdevents/core/service.py b/core/cdevents/core/service.py new file mode 100644 index 0000000..705a9f4 --- /dev/null +++ b/core/cdevents/core/service.py @@ -0,0 +1,39 @@ +"""service""" + +from enum import Enum +from cdevents.core.events import Events + +class ServiceType(Enum): + ServiceDeployedEventV1 :str = "cd.service.deployed.v1" + ServiceUpgradedEventV1 :str = "cd.service.upgraded.v1" + ServiceRolledbackEventV1 :str = "cd.service.rolledback.v1" + ServiceRemovedEventV1 :str = "cd.service.removed.v1" + + +class Service(Events): + """Service.""" + + def __init__(self, service_type: ServiceType, envid: str, name: str, version: str): + """Initializes class. + """ + self._event_type = service_type + self._envid = envid + self._name = name + self._version = version + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "serviceenvid": self._envid, + "servicename": self._name, + "serviceversion": self._version, + } + return extensions + + def create_event(self, data: dict={}): + """Create Service event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event From e5ff182d47f59bc7675a38c9f7b835cc0ec8a7b3 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 3 Aug 2022 15:17:13 +0200 Subject: [PATCH 26/34] add taskrun obj --- cli/cdevents/cli/taskrun.py | 18 +++++-------- core/cdevents/core/event_type.py | 4 --- core/cdevents/core/taskrun.py | 38 ++++++++++++++++++++++++++ core/tests/test_service.py | 46 +++++++++++++++++--------------- core/tests/test_taskrun.py | 26 +++++++++--------- 5 files changed, 84 insertions(+), 48 deletions(-) create mode 100644 core/cdevents/core/taskrun.py diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index e55b864..4605386 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -1,16 +1,12 @@ """Module for cli taskrun commands.""" from __future__ import annotations - -import os from typing import List - import click from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.events import Events -from cdevents.core import event_type +from cdevents.core.taskrun import TaskRun, TaskRunType # pylint: disable=unused-argument def common_taskrun_options(function): @@ -57,10 +53,10 @@ def started( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_taskrun_event(event_type.TaskRunStartedEventV1, id, name, pipelineid, data) + taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1, id=id, name=name, pipelineid=pipelineid) + taskrun_event = taskrun.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(taskrun_event) @click.command(help=add_disclaimer_text("TaskRun Finished CloudEvent.")) @common_taskrun_options @@ -71,8 +67,8 @@ def finished( data: List[str] = None, ): print_function_args() - e = Events() - new_event = e.create_taskrun_event(event_type.TaskRunFinishedEventV1, id, name, pipelineid, data) + taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id=id, name=name, pipelineid=pipelineid) + taskrun_event = taskrun.create_event(data) cdevents_command = CDeventsCommand() - cdevents_command.run(new_event) + cdevents_command.run(taskrun_event) diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index 59feb30..52e6f45 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -9,10 +9,6 @@ ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" -# TaskRun events -TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" -TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" - # Test Events TestCaseStartedEventV1 :str = "cd.test.case.started.v1" TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" diff --git a/core/cdevents/core/taskrun.py b/core/cdevents/core/taskrun.py new file mode 100644 index 0000000..d0eaf38 --- /dev/null +++ b/core/cdevents/core/taskrun.py @@ -0,0 +1,38 @@ +"""taskrun""" + +from enum import Enum +from cdevents.core.events import Events + +class TaskRunType(Enum): + TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" + TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" + + +class TaskRun(Events): + """Taskrun.""" + + def __init__(self, taskrun_type: TaskRunType, id: str, name: str, pipelineid: str): + """Initializes class. + """ + self._event_type = taskrun_type + self._id= id + self._name = name + self._pipelineid = pipelineid + + + def create_extensions(self): + """Create extensions. + """ + extensions = { + "taskrunid": self._id, + "taskrunname": self._name, + "taskrunpipelineid": self._pipelineid, + } + return extensions + + def create_event(self, data: dict={}): + """Create taskrun event. + """ + extensions = self.create_extensions() + event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) + return event diff --git a/core/tests/test_service.py b/core/tests/test_service.py index e8ed052..64c8cf0 100644 --- a/core/tests/test_service.py +++ b/core/tests/test_service.py @@ -1,40 +1,44 @@ from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.service import Service, ServiceType @pytest.mark.unit def test_service_deployed(): - event = Events().create_service_event(event_type.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) - assert event is not None - assert event._attributes["type"] == event_type.ServiceDeployedEventV1 - assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} - assert event.data == {"service": "_service"} + service = Service(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version") + service_event = service.create_event(data={"key1": "value1"}) + assert service_event is not None + assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value + assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert service_event.data == {"key1": "value1"} @pytest.mark.unit def test_service_upgraded(): - event = Events().create_service_event(event_type.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) - assert event is not None - assert event._attributes["type"] == event_type.ServiceUpgradedEventV1 - assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} - assert event.data == {"service": "_service"} + service = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version") + service_event = service.create_event(data={"key1": "value1"}) + assert service_event is not None + assert service_event._attributes["type"] == ServiceType.ServiceUpgradedEventV1.value + assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert service_event.data == {"key1": "value1"} @pytest.mark.unit def test_service_rolledback(): - event = Events().create_service_event(event_type.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) - assert event is not None - assert event._attributes["type"] == event_type.ServiceRolledbackEventV1 - assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} - assert event.data == {"service": "_service"} + service = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version") + service_event = service.create_event(data={"key1": "value1"}) + assert service_event is not None + assert service_event._attributes["type"] == ServiceType.ServiceRolledbackEventV1.value + assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert service_event.data == {"key1": "value1"} @pytest.mark.unit def test_service_removed(): - event = Events().create_service_event(event_type.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version", data={"service": "_service"}) - assert event is not None - assert event._attributes["type"] == event_type.ServiceRemovedEventV1 - assert event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} - assert event.data == {"service": "_service"} + service = Service(service_type=ServiceType.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version") + service_event = service.create_event(data={"key1": "value1"}) + assert service_event is not None + assert service_event._attributes["type"] == ServiceType.ServiceRemovedEventV1.value + assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert service_event.data == {"key1": "value1"} diff --git a/core/tests/test_taskrun.py b/core/tests/test_taskrun.py index b8873b2..0dc9fac 100644 --- a/core/tests/test_taskrun.py +++ b/core/tests/test_taskrun.py @@ -1,20 +1,22 @@ -from cdevents.core import event_type import pytest -from cdevents.core.events import Events +from cdevents.core.taskrun import TaskRun, TaskRunType @pytest.mark.unit def test_taskrun_started(): - event = Events().create_taskrun_event(event_type.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"taskrun": "_taskrun"}) - assert event is not None - assert event._attributes["type"] == event_type.TaskRunStartedEventV1 - assert event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} - assert event.data == {"taskrun": "_taskrun"} + taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1,id="_id", name="_name", pipelineid="_pipelineid") + taskrun_event = taskrun.create_event(data={"key1": "value1"}) + assert taskrun_event is not None + assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value + assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} + assert taskrun_event.data == {"key1": "value1"} + @pytest.mark.unit def test_taskrun_finished(): - event = Events().create_taskrun_event(event_type.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"taskrun": "_taskrun"}) - assert event is not None - assert event._attributes["type"] == event_type.TaskRunFinishedEventV1 - assert event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} - assert event.data == {"taskrun": "_taskrun"} + taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1,id="_id", name="_name", pipelineid="_pipelineid") + taskrun_event = taskrun.create_event(data={"key1": "value1"}) + assert taskrun_event is not None + assert taskrun_event._attributes["type"] == TaskRunType.TaskRunFinishedEventV1.value + assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} + assert taskrun_event.data == {"key1": "value1"} From efd47a65218f59d718ecb49da4256deff8b3ed15 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Thu, 4 Aug 2022 12:01:40 +0200 Subject: [PATCH 27/34] Update def __init__ --- cli/cdevents/cli/artifact.py | 6 ++--- cli/cdevents/cli/branch.py | 6 ++--- cli/cdevents/cli/build.py | 9 +++----- cli/cdevents/cli/env.py | 8 +++---- cli/cdevents/cli/pipelinerun.py | 9 +++----- cli/cdevents/cli/repository.py | 9 +++----- cli/cdevents/cli/service.py | 12 ++++------ cli/cdevents/cli/taskrun.py | 6 ++--- core/cdevents/core/artifact.py | 12 +++------- core/cdevents/core/branch.py | 12 +++------- core/cdevents/core/build.py | 12 +++------- core/cdevents/core/env.py | 12 +++------- core/cdevents/core/events.py | 37 ++++++++----------------------- core/cdevents/core/pipelinerun.py | 11 +++------ core/cdevents/core/repository.py | 12 +++------- core/cdevents/core/service.py | 13 ++++------- core/cdevents/core/taskrun.py | 17 +++++--------- core/tests/test_artifact.py | 6 ++--- core/tests/test_branch.py | 6 ++--- core/tests/test_build.py | 9 +++----- core/tests/test_environment.py | 9 +++----- core/tests/test_events.py | 3 ++- core/tests/test_pipelinerun.py | 9 +++----- core/tests/test_repository.py | 9 +++----- core/tests/test_service.py | 12 ++++------ core/tests/test_taskrun.py | 6 ++--- 26 files changed, 82 insertions(+), 190 deletions(-) diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 94f4538..b228ef1 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -53,8 +53,7 @@ def packaged( data: List[str] = None, ): print_function_args() - artifact = Artifact(ArtifactType.ArtifactPackagedEventV1, id, name, version) - artifact_event = artifact.create_event(data) + artifact_event = Artifact(ArtifactType.ArtifactPackagedEventV1, id, name, version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) @@ -68,7 +67,6 @@ def published( data: List[str] = None, ): print_function_args() - artifact = Artifact(ArtifactType.ArtifactPublishedEventV1, id, name, version) - artifact_event = artifact.create_event(data) + artifact_event = Artifact(ArtifactType.ArtifactPublishedEventV1, id, name, version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index c25e620..144a09b 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -53,8 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - branch = Branch(branch_type=BranchType.BranchCreatedEventV1, id=id, name=name, repoid=repoid) - branch_event = branch.create_event(data) + branch_event = Branch(branch_type=BranchType.BranchCreatedEventV1, id=id, name=name, repoid=repoid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(branch_event) @@ -68,7 +67,6 @@ def deleted( data: List[str] = None, ): print_function_args() - branch = Branch(branch_type=BranchType.BranchDeletedEventV1, id=id, name=name, repoid=repoid) - branch_event = branch.create_event(data) + branch_event = Branch(branch_type=BranchType.BranchDeletedEventV1, id=id, name=name, repoid=repoid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(branch_event) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index ee9a621..6265f1b 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -54,8 +54,7 @@ def started( data: List[str] = None, ): print_function_args() - build = Build(build_type=BuildType.BuildStartedEventV1, id=id, name=name, artifact=artifact) - build_event = build.create_event(data) + build_event = Build(build_type=BuildType.BuildStartedEventV1, id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) @@ -68,8 +67,7 @@ def finished( data: List[str] = None, ): print_function_args() - build = Build(build_type=BuildType.BuildFinishedEventV1, id=id, name=name, artifact=artifact) - build_event = build.create_event(data) + build_event = Build(build_type=BuildType.BuildFinishedEventV1, id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) @@ -82,7 +80,6 @@ def queued( data: List[str] = None, ): print_function_args() - build = Build(build_type=BuildType.BuildQueuedEventV1, id=id, name=name, artifact=artifact) - build_event = build.create_event(data) + build_event = Build(build_type=BuildType.BuildQueuedEventV1, id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index 6eeb8f9..6006f32 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -53,7 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - env = Env(build_type=EnvType.EnvironmentCreatedEventV1, id=id, name=name, repo=repo) + env = Env(build_type=EnvType.EnvironmentCreatedEventV1, id=id, name=name, repo=repo, data=data) env_event = env.create_event(data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) @@ -68,8 +68,7 @@ def deleted( data: List[str] = None, ): print_function_args() - env = Env(env_type=EnvType.EnvironmentDeletedEventV1, id=id, name=name, repo=repo) - env_event = env.create_event(data) + env_event = Env(env_type=EnvType.EnvironmentDeletedEventV1, id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) @@ -82,7 +81,6 @@ def modified( data: List[str] = None, ): print_function_args() - env = Env(env_type=EnvType.EnvironmentModifiedEventV1, id=id, name=name, repo=repo) - env_event = env.create_event(data) + env_event = Env(env_type=EnvType.EnvironmentModifiedEventV1, id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) \ No newline at end of file diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 33eba34..60f5ac5 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -69,8 +69,7 @@ def started( data: List[str] = None, ): print_function_args() - pipelinerun = Pipelinerun(PipelinerunType.PipelineRunStartedEventV1, id=id, name=name, status=status, url=url, errors=errors) - pipelinerun_event = pipelinerun.create_event(data) + pipelinerun_event = Pipelinerun(PipelinerunType.PipelineRunStartedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) @@ -85,8 +84,7 @@ def finished( data: List[str] = None, ): print_function_args() - pipelinerun = Pipelinerun(PipelinerunType.PipelineRunFinishedEventV1, id=id, name=name, status=status, url=url, errors=errors) - pipelinerun_event = pipelinerun.create_event(data) + pipelinerun_event = Pipelinerun(PipelinerunType.PipelineRunFinishedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) @@ -102,8 +100,7 @@ def queued( data: List[str] = None, ): print_function_args() - pipelinerun = Pipelinerun(PipelinerunType.PipelineRunQueuedEventV1, id=id, name=name, status=status, url=url, errors=errors) - pipelinerun_event = pipelinerun.create_event(data) + pipelinerun_event = Pipelinerun(PipelinerunType.PipelineRunQueuedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) diff --git a/cli/cdevents/cli/repository.py b/cli/cdevents/cli/repository.py index 99db8f8..e0583b0 100644 --- a/cli/cdevents/cli/repository.py +++ b/cli/cdevents/cli/repository.py @@ -53,8 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - repository = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url) - repository_event = repository.create_event(data) + repository_event = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) @@ -68,8 +67,7 @@ def modified( data: List[str] = None, ): print_function_args() - repository = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url) - repository_event = repository.create_event(data) + repository_event = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) @@ -83,8 +81,7 @@ def deleted( data: List[str] = None, ): print_function_args() - repository = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url) - repository_event = repository.create_event(data) + repository_event = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index 1c3cbf2..cb8ecfa 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -53,8 +53,7 @@ def deployed( data: List[str] = None, ): print_function_args() - service = Service(service_type=ServiceType.ServiceDeployedEventV1, envid=envid, name=name, version=version) - service_event = service.create_event(data) + service_event = Service(service_type=ServiceType.ServiceDeployedEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -67,8 +66,7 @@ def upgraded( data: List[str] = None, ): print_function_args() - service = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid=envid, name=name, version=version) - service_event = service.create_event(data) + service_event = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -82,8 +80,7 @@ def removed( data: List[str] = None, ): print_function_args() - service = Service(service_type=ServiceType.ServiceRemovedEventV1, envid=envid, name=name, version=version) - service_event = service.create_event(data) + service_event = Service(service_type=ServiceType.ServiceRemovedEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -97,7 +94,6 @@ def rolledback( data: List[str] = None, ): print_function_args() - service = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid=envid, name=name, version=version) - service_event = service.create_event(data) + service_event = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index 4605386..0df6cae 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -53,8 +53,7 @@ def started( data: List[str] = None, ): print_function_args() - taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1, id=id, name=name, pipelineid=pipelineid) - taskrun_event = taskrun.create_event(data) + taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(taskrun_event) @@ -67,8 +66,7 @@ def finished( data: List[str] = None, ): print_function_args() - taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id=id, name=name, pipelineid=pipelineid) - taskrun_event = taskrun.create_event(data) + taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(taskrun_event) diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py index 1b5ede1..4a207ce 100644 --- a/core/cdevents/core/artifact.py +++ b/core/cdevents/core/artifact.py @@ -11,15 +11,16 @@ class ArtifactType(Enum): class Artifact(Events): """Artifact.""" - def __init__(self, artifact_type: ArtifactType, id: str, name: str, version: str): + def __init__(self, artifact_type: ArtifactType, id: str, name: str, version: str, data: dict = {}): """Initializes class. """ self._event_type = artifact_type self._id = id self._name = name self._version = version + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -28,10 +29,3 @@ def create_extensions(self): "artifactversion": self._version, } return extensions - - def create_event(self, data: dict={}): - """Create artifact event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index 4b603f1..29b9a61 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -11,15 +11,16 @@ class BranchType(Enum): class Branch(Events): """Brach.""" - def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str): + def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str, data: dict = {}): """Initializes class. """ self._event_type = branch_type self._id = id self._name = name self._repoid = repoid + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -28,10 +29,3 @@ def create_extensions(self): "branchrepositoryid": self._repoid, } return extensions - - def create_event(self, data: dict={}): - """Create branch event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event diff --git a/core/cdevents/core/build.py b/core/cdevents/core/build.py index e8b1f13..4b89b78 100644 --- a/core/cdevents/core/build.py +++ b/core/cdevents/core/build.py @@ -12,15 +12,16 @@ class BuildType(Enum): class Build(Events): """build.""" - def __init__(self, build_type: BuildType, id: str, name: str, artifact: str): + def __init__(self, build_type: BuildType, id: str, name: str, artifact: str, data: dict = {}): """Initializes class. """ self._event_type = build_type self._id = id self._name = name self._artifact = artifact + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -29,10 +30,3 @@ def create_extensions(self): "buildartifactid": self._artifact, } return extensions - - def create_event(self, data: dict={}): - """Create build event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event diff --git a/core/cdevents/core/env.py b/core/cdevents/core/env.py index aaf8733..58573d8 100644 --- a/core/cdevents/core/env.py +++ b/core/cdevents/core/env.py @@ -12,15 +12,16 @@ class EnvType(Enum): class Env(Events): """Env.""" - def __init__(self, env_type: EnvType, id: str, name: str, repo: str): + def __init__(self, env_type: EnvType, id: str, name: str, repo: str,data: dict = {}): """Initializes class. """ self._event_type = env_type self._id = id self._name = name self._repo = repo + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -29,10 +30,3 @@ def create_extensions(self): "envrepourl": self._repo, } return extensions - - def create_event(self, data: dict={}): - """Create env event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index 05e0fac..5872c21 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -2,38 +2,19 @@ from cloudevents.http import CloudEvent -class Events(): +class Events(CloudEvent): """Events.""" - def __init__(self): + def __init__(self, event_type: str, extensions: dict, data = {}): """Initializes class. """ + self._event_type = event_type + self._extensions = extensions + self._data = data - def create_event(self, event_type: str, extensions:dict, data = {}) -> CloudEvent: - """Create event. - """ - attributes = { - "type": event_type, + self._attributes = { + "type": self._event_type, "source": "cde-cli", - "extensions": extensions, + "extensions": self._extensions, } - - event = CloudEvent(attributes, dict(data)) - - return event - - - def create_taskrun_event(self, event_type: str, id: str, name: str, pipelineid: str, data = {}) -> CloudEvent: - """Create taskrun event. - """ - - extensions = { - "taskrunid": id, - "taskrunname": name, - "taskrunpipelineid": pipelineid, - } - - event = self.create_event(event_type, extensions, data) - - return event - + super().__init__(self._attributes, dict(self._data)) diff --git a/core/cdevents/core/pipelinerun.py b/core/cdevents/core/pipelinerun.py index c74562e..8fed548 100644 --- a/core/cdevents/core/pipelinerun.py +++ b/core/cdevents/core/pipelinerun.py @@ -12,7 +12,7 @@ class PipelinerunType(Enum): class Pipelinerun(Events): """Pipelinerun.""" - def __init__(self, pipelinerun_type: PipelinerunType, id: str, name: str, status: str, url: str, errors: str): + def __init__(self, pipelinerun_type: PipelinerunType, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): """Initializes class. """ self._event_type = pipelinerun_type @@ -21,8 +21,9 @@ def __init__(self, pipelinerun_type: PipelinerunType, id: str, name: str, status self._status = status self._url = url self._errors = errors + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -34,9 +35,3 @@ def create_extensions(self): } return extensions - def create_event(self, data: dict={}): - """Create pipelinerun event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event diff --git a/core/cdevents/core/repository.py b/core/cdevents/core/repository.py index 973fc05..aa00165 100644 --- a/core/cdevents/core/repository.py +++ b/core/cdevents/core/repository.py @@ -12,15 +12,16 @@ class RepositoryType(Enum): class Repository(Events): """Repository.""" - def __init__(self, repository_type: RepositoryType, id: str, name: str, url: str): + def __init__(self, repository_type: RepositoryType, id: str, name: str, url: str, data: dict = {}): """Initializes class. """ self._event_type = repository_type self._id = id self._name = name self._url = url + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -29,10 +30,3 @@ def create_extensions(self): "repositoryurl": self._url, } return extensions - - def create_event(self, data: dict={}): - """Create Repository event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event diff --git a/core/cdevents/core/service.py b/core/cdevents/core/service.py index 705a9f4..d8acb70 100644 --- a/core/cdevents/core/service.py +++ b/core/cdevents/core/service.py @@ -13,15 +13,16 @@ class ServiceType(Enum): class Service(Events): """Service.""" - def __init__(self, service_type: ServiceType, envid: str, name: str, version: str): + def __init__(self, service_type: ServiceType, envid: str, name: str, version: str, data: dict = {}): """Initializes class. """ self._event_type = service_type self._envid = envid self._name = name self._version = version + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - def create_extensions(self): + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -30,10 +31,4 @@ def create_extensions(self): "serviceversion": self._version, } return extensions - - def create_event(self, data: dict={}): - """Create Service event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event + diff --git a/core/cdevents/core/taskrun.py b/core/cdevents/core/taskrun.py index d0eaf38..14d8199 100644 --- a/core/cdevents/core/taskrun.py +++ b/core/cdevents/core/taskrun.py @@ -11,16 +11,16 @@ class TaskRunType(Enum): class TaskRun(Events): """Taskrun.""" - def __init__(self, taskrun_type: TaskRunType, id: str, name: str, pipelineid: str): + def __init__(self, taskrun_type: TaskRunType, id: str, name: str, pipelineid: str, data: dict = {}): """Initializes class. """ self._event_type = taskrun_type self._id= id self._name = name self._pipelineid = pipelineid - - - def create_extensions(self): + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) + + def create_extensions(self) -> dict: """Create extensions. """ extensions = { @@ -28,11 +28,4 @@ def create_extensions(self): "taskrunname": self._name, "taskrunpipelineid": self._pipelineid, } - return extensions - - def create_event(self, data: dict={}): - """Create taskrun event. - """ - extensions = self.create_extensions() - event = super().create_event(event_type=self._event_type.value, extensions=extensions, data=data) - return event + return extensions \ No newline at end of file diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py index 6200b71..ecb8d12 100644 --- a/core/tests/test_artifact.py +++ b/core/tests/test_artifact.py @@ -4,8 +4,7 @@ @pytest.mark.unit def test_artifact_packaged_v1(): - artifact = Artifact(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version") - artifact_event = artifact.create_event(data={"key1": "value1"}) + artifact_event = Artifact(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} @@ -13,8 +12,7 @@ def test_artifact_packaged_v1(): @pytest.mark.unit def test_artifact_published_v1(): - artifact = Artifact(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version") - artifact_event = artifact.create_event(data={"key1": "value1"}) + artifact_event = Artifact(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None assert artifact_event._attributes["type"] ==ArtifactType.ArtifactPublishedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py index 8fdbe28..95a56e9 100644 --- a/core/tests/test_branch.py +++ b/core/tests/test_branch.py @@ -4,8 +4,7 @@ @pytest.mark.unit def test_repository_branch_created(): - branch = Branch(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid") - branch_event = branch.create_event(data={"key1": "value1"}) + branch_event = Branch(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} @@ -13,8 +12,7 @@ def test_repository_branch_created(): @pytest.mark.unit def test_repository_branch_deleted(): - branch = Branch(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid") - branch_event = branch.create_event(data={"key1": "value1"}) + branch_event = Branch(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None assert branch_event._attributes["type"] == BranchType.BranchDeletedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} diff --git a/core/tests/test_build.py b/core/tests/test_build.py index 0a1875d..168fc08 100644 --- a/core/tests/test_build.py +++ b/core/tests/test_build.py @@ -4,8 +4,7 @@ @pytest.mark.unit def test_build_started(): - build = Build(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact") - build_event = build.create_event(data={"key1": "value1"}) + build_event = Build(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} @@ -13,8 +12,7 @@ def test_build_started(): @pytest.mark.unit def test_build_queued(): - build = Build(build_type=BuildType.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact") - build_event = build.create_event(data={"key1": "value1"}) + build_event = Build(build_type=BuildType.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildQueuedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} @@ -22,8 +20,7 @@ def test_build_queued(): @pytest.mark.unit def test_build_finished(): - build = Build(build_type=BuildType.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact") - build_event = build.create_event(data={"key1": "value1"}) + build_event = Build(build_type=BuildType.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildFinishedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py index 0114535..ed0e201 100644 --- a/core/tests/test_environment.py +++ b/core/tests/test_environment.py @@ -4,8 +4,7 @@ @pytest.mark.unit def test_environment_created(): - env = Env(env_type=EnvType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo") - env_event = env.create_event(data={"key1": "value1"}) + env_event = Env(env_type=EnvType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentCreatedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} @@ -14,8 +13,7 @@ def test_environment_created(): @pytest.mark.unit def test_environment_modified(): - env = Env(env_type=EnvType.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo") - env_event = env.create_event(data={"key1": "value1"}) + env_event = Env(env_type=EnvType.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentModifiedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} @@ -23,8 +21,7 @@ def test_environment_modified(): @pytest.mark.unit def test_environment_deleted(): - env = Env(env_type=EnvType.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo") - env_event = env.create_event(data={"key1": "value1"}) + env_event = Env(env_type=EnvType.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentDeletedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} diff --git a/core/tests/test_events.py b/core/tests/test_events.py index daeaa10..580977d 100644 --- a/core/tests/test_events.py +++ b/core/tests/test_events.py @@ -4,7 +4,8 @@ @pytest.mark.unit def test_create_event(): - event = Events().create_event(event_type="event_type", extensions={"test": "test"}) + event = Events(event_type="event_type", extensions={"test": "test"}, data={"key1": "value1"}) assert event is not None assert event._attributes["type"] == "event_type" assert event._attributes["extensions"] == {"test": "test"} + assert event.data == {"key1": "value1"} diff --git a/core/tests/test_pipelinerun.py b/core/tests/test_pipelinerun.py index 4825311..30a2b41 100644 --- a/core/tests/test_pipelinerun.py +++ b/core/tests/test_pipelinerun.py @@ -4,8 +4,7 @@ @pytest.mark.unit def test_pipelinerun_started(): - pipelinerun = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors") - pipelinerun_event = pipelinerun.create_event(data={"key1": "value1"}) + pipelinerun_event = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} @@ -13,8 +12,7 @@ def test_pipelinerun_started(): @pytest.mark.unit def test_pipelinerun_finished(): - pipelinerun = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors") - pipelinerun_event = pipelinerun.create_event(data={"key1": "value1"}) + pipelinerun_event = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunFinishedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} @@ -22,8 +20,7 @@ def test_pipelinerun_finished(): @pytest.mark.unit def test_pipelinerun_queued(): - pipelinerun = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors") - pipelinerun_event = pipelinerun.create_event(data={"key1": "value1"}) + pipelinerun_event = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunQueuedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} diff --git a/core/tests/test_repository.py b/core/tests/test_repository.py index 50a3be8..7b77efc 100644 --- a/core/tests/test_repository.py +++ b/core/tests/test_repository.py @@ -5,8 +5,7 @@ @pytest.mark.unit def test_repository_created(): - repository = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url") - repository_event = repository.create_event(data={"key1": "value1"}) + repository_event = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryCreatedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} @@ -15,8 +14,7 @@ def test_repository_created(): @pytest.mark.unit def test_repository_modified(): - repository = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id="_id", name="_name", url="_url") - repository_event = repository.create_event(data={"key1": "value1"}) + repository_event = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryModifiedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} @@ -25,8 +23,7 @@ def test_repository_modified(): @pytest.mark.unit def test_repository_deleted(): - repository = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id="_id", name="_name", url="_url") - repository_event = repository.create_event(data={"key1": "value1"}) + repository_event = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryDeletedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} diff --git a/core/tests/test_service.py b/core/tests/test_service.py index 64c8cf0..235f8e2 100644 --- a/core/tests/test_service.py +++ b/core/tests/test_service.py @@ -5,8 +5,7 @@ @pytest.mark.unit def test_service_deployed(): - service = Service(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version") - service_event = service.create_event(data={"key1": "value1"}) + service_event = Service(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -15,8 +14,7 @@ def test_service_deployed(): @pytest.mark.unit def test_service_upgraded(): - service = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version") - service_event = service.create_event(data={"key1": "value1"}) + service_event = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceUpgradedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -25,8 +23,7 @@ def test_service_upgraded(): @pytest.mark.unit def test_service_rolledback(): - service = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version") - service_event = service.create_event(data={"key1": "value1"}) + service_event = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceRolledbackEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -35,8 +32,7 @@ def test_service_rolledback(): @pytest.mark.unit def test_service_removed(): - service = Service(service_type=ServiceType.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version") - service_event = service.create_event(data={"key1": "value1"}) + service_event = Service(service_type=ServiceType.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceRemovedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} diff --git a/core/tests/test_taskrun.py b/core/tests/test_taskrun.py index 0dc9fac..808aadb 100644 --- a/core/tests/test_taskrun.py +++ b/core/tests/test_taskrun.py @@ -4,8 +4,7 @@ @pytest.mark.unit def test_taskrun_started(): - taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1,id="_id", name="_name", pipelineid="_pipelineid") - taskrun_event = taskrun.create_event(data={"key1": "value1"}) + taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} @@ -14,8 +13,7 @@ def test_taskrun_started(): @pytest.mark.unit def test_taskrun_finished(): - taskrun = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1,id="_id", name="_name", pipelineid="_pipelineid") - taskrun_event = taskrun.create_event(data={"key1": "value1"}) + taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None assert taskrun_event._attributes["type"] == TaskRunType.TaskRunFinishedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} From d6d5791cbefe5788dbd37f74b3c7cb034cccd352 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Fri, 5 Aug 2022 13:41:32 +0200 Subject: [PATCH 28/34] update setup --- pypi_packaging.py | 57 ---------------------------------------- requirements/docs.txt | 1 - requirements/publish.txt | 2 -- requirements/test.txt | 8 ------ setup.py | 49 ---------------------------------- 5 files changed, 117 deletions(-) delete mode 100644 pypi_packaging.py delete mode 100644 requirements/docs.txt delete mode 100644 requirements/publish.txt delete mode 100644 requirements/test.txt delete mode 100644 setup.py diff --git a/pypi_packaging.py b/pypi_packaging.py deleted file mode 100644 index 71dd7d4..0000000 --- a/pypi_packaging.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Packaging and release utilities.""" - -import codecs -import os - -import pkg_resources - - -def _read(rel_path): - here = os.path.abspath(os.path.dirname(__file__)) - with codecs.open(os.path.join(here, rel_path), "r") as fp: - return fp.read() - - -def _get_version(rel_path): - for line in _read(rel_path).splitlines(): - if line.startswith("__version__"): - delim = '"' if '"' in line else "'" - return line.split(delim)[1] - else: - raise RuntimeError("Unable to find version string.") - - -# FORMAT: 1.x.x -pypi_config = { - "version_target": _get_version("cdevents/__init__.py"), - "package_name": "cdevents", -} - - -def _createTag(): - from git import Repo - - # Get local pypi cloudevents version - published_pypi_version = pkg_resources.get_distribution(pypi_config["package_name"]).version - - # Ensure pypi and local package versions match - if pypi_config["version_target"] == published_pypi_version: - # Create local git tag - repo = Repo(os.getcwd()) - repo.create_tag(pypi_config["version_target"]) - - # Push git tag to remote master - origin = repo.remote() - origin.push(pypi_config["version_target"]) - - else: - # PyPI publish likely failed - print( - f"Expected {pypi_config['package_name']}=={pypi_config['version_target']} " - f"but found {pypi_config['package_name']}=={published_pypi_version}" - ) - exit(1) - - -if __name__ == "__main__": - _createTag() diff --git a/requirements/docs.txt b/requirements/docs.txt deleted file mode 100644 index 2806c16..0000000 --- a/requirements/docs.txt +++ /dev/null @@ -1 +0,0 @@ -Sphinx diff --git a/requirements/publish.txt b/requirements/publish.txt deleted file mode 100644 index 103a961..0000000 --- a/requirements/publish.txt +++ /dev/null @@ -1,2 +0,0 @@ -GitPython -cdevents diff --git a/requirements/test.txt b/requirements/test.txt deleted file mode 100644 index c962aa3..0000000 --- a/requirements/test.txt +++ /dev/null @@ -1,8 +0,0 @@ -flake8==4.0.1 -pep8-naming -flake8-import-order -flake8-print -flake8-strict -pytest==7.1.2 -pytest-mock==3.7.0 -pytest-cov diff --git a/setup.py b/setup.py deleted file mode 100644 index 9b29cf9..0000000 --- a/setup.py +++ /dev/null @@ -1,49 +0,0 @@ -# All Rights Reserved. -# -# 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. - -"""Project settings.""" - -import pathlib - -from setuptools import find_packages, setup - -from pypi_packaging import pypi_config - -here = pathlib.Path(__file__).parent.resolve() -long_description = (here / "README.md").read_text(encoding="utf-8") - -setup( - name=pypi_config["package_name"], - summary="CDEvents SDK Python", - long_description_content_type="text/markdown", - long_description=long_description, - author="The CDEvents Contributors", - author_email="TODO", - home_page="https://cdevents.dev", - classifiers=[ - "Intended Audience :: Information Technology", - "Intended Audience :: System Administrators", - "License :: OSI Approved :: Apache Software License", - "Operating System :: POSIX :: Linux", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - ], - packages=find_packages(exclude=["cdevents.tests"]), - version=pypi_config["version_target"], - install_requires=["cloudevents>=1.2.0,<2.0"], -) From 342cdecf25a7e0c421616283a7768f23109421a4 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Mon, 8 Aug 2022 14:05:52 +0200 Subject: [PATCH 29/34] update abstractmethod --- core/cdevents/core/branch.py | 2 +- core/cdevents/core/event_type.py | 3 ++- core/cdevents/core/events.py | 14 ++++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index 29b9a61..27d0c3a 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -9,7 +9,7 @@ class BranchType(Enum): class Branch(Events): - """Brach.""" + """Branch.""" def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str, data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index 52e6f45..58cf2a0 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -9,11 +9,12 @@ ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" -# Test Events +# TestCase Events TestCaseStartedEventV1 :str = "cd.test.case.started.v1" TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" TestCaseFinishedEventV1 :str = "cd.test.case.finished.v1" +# TestSuite Events TestSuiteStartedEventV1 :str = "cd.test.suite.started.v1" TestSuiteQueuedEventV1 :str = "cd.test.suite.queued.v1" TestSuiteFinishedEventV1 :str = "cd.test.suite.finished.v1" diff --git a/core/cdevents/core/events.py b/core/cdevents/core/events.py index 5872c21..d5a93a4 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/events.py @@ -1,5 +1,6 @@ """Core events.""" +from abc import abstractmethod from cloudevents.http import CloudEvent class Events(CloudEvent): @@ -18,3 +19,16 @@ def __init__(self, event_type: str, extensions: dict, data = {}): "extensions": self._extensions, } super().__init__(self._attributes, dict(self._data)) + + @abstractmethod + def create_extensions(self) -> dict: + """Create extensions. + """ + extensions = {} + return extensions + + # @abstractmethod + # def event_from_json(json_obj: dict) -> Events: + # """Create event from json. + # """ + # pass \ No newline at end of file From 4e6b4f5111add19f0fad85f84ba5bf90f1c04269 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Tue, 9 Aug 2022 14:15:44 +0200 Subject: [PATCH 30/34] update events -> event --- cli/cdevents/cli/artifact.py | 6 +++--- cli/cdevents/cli/branch.py | 6 +++--- cli/cdevents/cli/build.py | 8 +++---- cli/cdevents/cli/env.py | 8 +++---- cli/cdevents/cli/pipelinerun.py | 8 +++---- cli/cdevents/cli/repository.py | 8 +++---- cli/cdevents/cli/service.py | 10 ++++----- cli/cdevents/cli/taskrun.py | 6 +++--- core/cdevents/core/artifact.py | 6 +++--- core/cdevents/core/branch.py | 25 +++++++++++++++++++--- core/cdevents/core/build.py | 6 +++--- core/cdevents/core/env.py | 6 +++--- core/cdevents/core/{events.py => event.py} | 4 ++-- core/cdevents/core/pipelinerun.py | 6 +++--- core/cdevents/core/repository.py | 6 +++--- core/cdevents/core/service.py | 6 +++--- core/cdevents/core/taskrun.py | 6 +++--- core/tests/test_artifact.py | 6 +++--- core/tests/test_branch.py | 6 +++--- core/tests/test_build.py | 8 +++---- core/tests/test_environment.py | 8 +++---- core/tests/test_events.py | 4 ++-- core/tests/test_pipelinerun.py | 8 +++---- core/tests/test_repository.py | 8 +++---- core/tests/test_service.py | 10 ++++----- core/tests/test_taskrun.py | 6 +++--- 26 files changed, 107 insertions(+), 88 deletions(-) rename core/cdevents/core/{events.py => event.py} (94%) diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index b228ef1..f48df2c 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.artifact import Artifact, ArtifactType +from cdevents.core.artifact import ArtifactEvent, ArtifactType # pylint: disable=unused-argument def common_artifact_options(function): @@ -53,7 +53,7 @@ def packaged( data: List[str] = None, ): print_function_args() - artifact_event = Artifact(ArtifactType.ArtifactPackagedEventV1, id, name, version, data=data) + artifact_event = ArtifactEvent(ArtifactType.ArtifactPackagedEventV1, id, name, version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) @@ -67,6 +67,6 @@ def published( data: List[str] = None, ): print_function_args() - artifact_event = Artifact(ArtifactType.ArtifactPublishedEventV1, id, name, version, data=data) + artifact_event = ArtifactEvent(ArtifactType.ArtifactPublishedEventV1, id, name, version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index 144a09b..8f04db2 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.branch import Branch, BranchType +from cdevents.core.branch import BranchEvent, BranchType # pylint: disable=unused-argument def common_branch_options(function): @@ -53,7 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - branch_event = Branch(branch_type=BranchType.BranchCreatedEventV1, id=id, name=name, repoid=repoid, data=data) + branch_event = BranchEvent(branch_type=BranchType.BranchCreatedEventV1, id=id, name=name, repoid=repoid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(branch_event) @@ -67,6 +67,6 @@ def deleted( data: List[str] = None, ): print_function_args() - branch_event = Branch(branch_type=BranchType.BranchDeletedEventV1, id=id, name=name, repoid=repoid, data=data) + branch_event = BranchEvent(branch_type=BranchType.BranchDeletedEventV1, id=id, name=name, repoid=repoid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(branch_event) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 6265f1b..23fdc61 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.build import Build, BuildType +from cdevents.core.build import BuildEvent, BuildType # pylint: disable=unused-argument def common_build_options(function): @@ -54,7 +54,7 @@ def started( data: List[str] = None, ): print_function_args() - build_event = Build(build_type=BuildType.BuildStartedEventV1, id=id, name=name, artifact=artifact, data=data) + build_event = BuildEvent(build_type=BuildType.BuildStartedEventV1, id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) @@ -67,7 +67,7 @@ def finished( data: List[str] = None, ): print_function_args() - build_event = Build(build_type=BuildType.BuildFinishedEventV1, id=id, name=name, artifact=artifact, data=data) + build_event = BuildEvent(build_type=BuildType.BuildFinishedEventV1, id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) @@ -80,6 +80,6 @@ def queued( data: List[str] = None, ): print_function_args() - build_event = Build(build_type=BuildType.BuildQueuedEventV1, id=id, name=name, artifact=artifact, data=data) + build_event = BuildEvent(build_type=BuildType.BuildQueuedEventV1, id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index 6006f32..c6e8f56 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.env import Env, EnvType +from cdevents.core.env import EnvEvent, EnvType # pylint: disable=unused-argument def common_env_options(function): @@ -53,7 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - env = Env(build_type=EnvType.EnvironmentCreatedEventV1, id=id, name=name, repo=repo, data=data) + env = EnvEvent(build_type=EnvType.EnvironmentCreatedEventV1, id=id, name=name, repo=repo, data=data) env_event = env.create_event(data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) @@ -68,7 +68,7 @@ def deleted( data: List[str] = None, ): print_function_args() - env_event = Env(env_type=EnvType.EnvironmentDeletedEventV1, id=id, name=name, repo=repo, data=data) + env_event = EnvEvent(env_type=EnvType.EnvironmentDeletedEventV1, id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) @@ -81,6 +81,6 @@ def modified( data: List[str] = None, ): print_function_args() - env_event = Env(env_type=EnvType.EnvironmentModifiedEventV1, id=id, name=name, repo=repo, data=data) + env_event = EnvEvent(env_type=EnvType.EnvironmentModifiedEventV1, id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) \ No newline at end of file diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 60f5ac5..63897d4 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.pipelinerun import Pipelinerun, PipelinerunType +from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunType # pylint: disable=unused-argument def common_pipelinerun_options(function): @@ -69,7 +69,7 @@ def started( data: List[str] = None, ): print_function_args() - pipelinerun_event = Pipelinerun(PipelinerunType.PipelineRunStartedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) + pipelinerun_event = PipelinerunEvent(PipelinerunType.PipelineRunStartedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) @@ -84,7 +84,7 @@ def finished( data: List[str] = None, ): print_function_args() - pipelinerun_event = Pipelinerun(PipelinerunType.PipelineRunFinishedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) + pipelinerun_event = PipelinerunEvent(PipelinerunType.PipelineRunFinishedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) @@ -100,7 +100,7 @@ def queued( data: List[str] = None, ): print_function_args() - pipelinerun_event = Pipelinerun(PipelinerunType.PipelineRunQueuedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) + pipelinerun_event = PipelinerunEvent(PipelinerunType.PipelineRunQueuedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) diff --git a/cli/cdevents/cli/repository.py b/cli/cdevents/cli/repository.py index e0583b0..327234c 100644 --- a/cli/cdevents/cli/repository.py +++ b/cli/cdevents/cli/repository.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.repository import Repository, RepositoryType +from cdevents.core.repository import RepositoryEvent, RepositoryType # pylint: disable=unused-argument def common_repository_options(function): @@ -53,7 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - repository_event = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url, data=data) + repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) @@ -67,7 +67,7 @@ def modified( data: List[str] = None, ): print_function_args() - repository_event = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url, data=data) + repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) @@ -81,7 +81,7 @@ def deleted( data: List[str] = None, ): print_function_args() - repository_event = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url, data=data) + repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index cb8ecfa..fb70310 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.service import Service, ServiceType +from cdevents.core.service import ServiceEvent, ServiceType # pylint: disable=unused-argument def common_service_options(function): @@ -53,7 +53,7 @@ def deployed( data: List[str] = None, ): print_function_args() - service_event = Service(service_type=ServiceType.ServiceDeployedEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceEvent(service_type=ServiceType.ServiceDeployedEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -66,7 +66,7 @@ def upgraded( data: List[str] = None, ): print_function_args() - service_event = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceEvent(service_type=ServiceType.ServiceUpgradedEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -80,7 +80,7 @@ def removed( data: List[str] = None, ): print_function_args() - service_event = Service(service_type=ServiceType.ServiceRemovedEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceEvent(service_type=ServiceType.ServiceRemovedEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -94,6 +94,6 @@ def rolledback( data: List[str] = None, ): print_function_args() - service_event = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceEvent(service_type=ServiceType.ServiceRolledbackEventV1, envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index 0df6cae..be9a343 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.taskrun import TaskRun, TaskRunType +from cdevents.core.taskrun import TaskRunEvent, TaskRunType # pylint: disable=unused-argument def common_taskrun_options(function): @@ -53,7 +53,7 @@ def started( data: List[str] = None, ): print_function_args() - taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) + taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunStartedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(taskrun_event) @@ -66,7 +66,7 @@ def finished( data: List[str] = None, ): print_function_args() - taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) + taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(taskrun_event) diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py index 4a207ce..443dcbe 100644 --- a/core/cdevents/core/artifact.py +++ b/core/cdevents/core/artifact.py @@ -1,15 +1,15 @@ """artifact""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class ArtifactType(Enum): ArtifactPackagedEventV1: str = "cd.artifact.packaged.v1" ArtifactPublishedEventV1: str = "cd.artifact.published.v1" -class Artifact(Events): - """Artifact.""" +class ArtifactEvent(Event): + """Artifact Event.""" def __init__(self, artifact_type: ArtifactType, id: str, name: str, version: str, data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index 27d0c3a..c3cee46 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -1,15 +1,15 @@ """branch""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class BranchType(Enum): BranchCreatedEventV1: str = "cd.repository.branch.created.v1" BranchDeletedEventV1: str = "cd.repository.branch.deleted.v1" -class Branch(Events): - """Branch.""" +class BranchEvent(Event): + """Branch Event.""" def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str, data: dict = {}): """Initializes class. @@ -29,3 +29,22 @@ def create_extensions(self) -> dict: "branchrepositoryid": self._repoid, } return extensions + +# TODO: Add tests for this class. +class BranchCreatedEvent(BranchEvent): + + def __init__(self, id: str, name: str, repoid: str, data: dict = {}): + """Initializes class. + """ + self._event_type : str = "cd.repository.branch.created.v1" + + super().__init__(event_type=self._event_type, id=id, name=name, repoid=repoid, data=data) + +class BranchDeletedEvent(BranchEvent): + + def __init__(self, id: str, name: str, repoid: str, data: dict = {}): + """Initializes class. + """ + self._event_type : str = "cd.repository.branch.deleted.v1" + + super().__init__(event_type=self._event_type, id=id, name=name, repoid=repoid, data=data) diff --git a/core/cdevents/core/build.py b/core/cdevents/core/build.py index 4b89b78..b80f162 100644 --- a/core/cdevents/core/build.py +++ b/core/cdevents/core/build.py @@ -1,7 +1,7 @@ """build""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class BuildType(Enum): BuildStartedEventV1 :str = "cd.build.started.v1" @@ -9,8 +9,8 @@ class BuildType(Enum): BuildFinishedEventV1 :str = "cd.build.finished.v1" -class Build(Events): - """build.""" +class BuildEvent(Event): + """Build Event.""" def __init__(self, build_type: BuildType, id: str, name: str, artifact: str, data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/env.py b/core/cdevents/core/env.py index 58573d8..2b47cb8 100644 --- a/core/cdevents/core/env.py +++ b/core/cdevents/core/env.py @@ -1,7 +1,7 @@ """env""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class EnvType(Enum): EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" @@ -9,8 +9,8 @@ class EnvType(Enum): EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" -class Env(Events): - """Env.""" +class EnvEvent(Event): + """Env Event.""" def __init__(self, env_type: EnvType, id: str, name: str, repo: str,data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/events.py b/core/cdevents/core/event.py similarity index 94% rename from core/cdevents/core/events.py rename to core/cdevents/core/event.py index d5a93a4..2f9eed2 100644 --- a/core/cdevents/core/events.py +++ b/core/cdevents/core/event.py @@ -3,8 +3,8 @@ from abc import abstractmethod from cloudevents.http import CloudEvent -class Events(CloudEvent): - """Events.""" +class Event(CloudEvent): + """Event.""" def __init__(self, event_type: str, extensions: dict, data = {}): """Initializes class. diff --git a/core/cdevents/core/pipelinerun.py b/core/cdevents/core/pipelinerun.py index 8fed548..bc34fe2 100644 --- a/core/cdevents/core/pipelinerun.py +++ b/core/cdevents/core/pipelinerun.py @@ -1,7 +1,7 @@ """pipelinerun""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class PipelinerunType(Enum): PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" @@ -9,8 +9,8 @@ class PipelinerunType(Enum): PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" -class Pipelinerun(Events): - """Pipelinerun.""" +class PipelinerunEvent(Event): + """Pipelinerun Event.""" def __init__(self, pipelinerun_type: PipelinerunType, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/repository.py b/core/cdevents/core/repository.py index aa00165..52e9b46 100644 --- a/core/cdevents/core/repository.py +++ b/core/cdevents/core/repository.py @@ -1,7 +1,7 @@ """repository""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class RepositoryType(Enum): RepositoryCreatedEventV1 :str = "cd.repository.created.v1" @@ -9,8 +9,8 @@ class RepositoryType(Enum): RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" -class Repository(Events): - """Repository.""" +class RepositoryEvent(Event): + """Repository Event.""" def __init__(self, repository_type: RepositoryType, id: str, name: str, url: str, data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/service.py b/core/cdevents/core/service.py index d8acb70..dcccb62 100644 --- a/core/cdevents/core/service.py +++ b/core/cdevents/core/service.py @@ -1,7 +1,7 @@ """service""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class ServiceType(Enum): ServiceDeployedEventV1 :str = "cd.service.deployed.v1" @@ -10,8 +10,8 @@ class ServiceType(Enum): ServiceRemovedEventV1 :str = "cd.service.removed.v1" -class Service(Events): - """Service.""" +class ServiceEvent(Event): + """Service Event.""" def __init__(self, service_type: ServiceType, envid: str, name: str, version: str, data: dict = {}): """Initializes class. diff --git a/core/cdevents/core/taskrun.py b/core/cdevents/core/taskrun.py index 14d8199..462f4d1 100644 --- a/core/cdevents/core/taskrun.py +++ b/core/cdevents/core/taskrun.py @@ -1,15 +1,15 @@ """taskrun""" from enum import Enum -from cdevents.core.events import Events +from cdevents.core.event import Event class TaskRunType(Enum): TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" -class TaskRun(Events): - """Taskrun.""" +class TaskRunEvent(Event): + """Taskrun Event.""" def __init__(self, taskrun_type: TaskRunType, id: str, name: str, pipelineid: str, data: dict = {}): """Initializes class. diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py index ecb8d12..c8b4acd 100644 --- a/core/tests/test_artifact.py +++ b/core/tests/test_artifact.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.artifact import Artifact, ArtifactType +from cdevents.core.artifact import ArtifactEvent, ArtifactType @pytest.mark.unit def test_artifact_packaged_v1(): - artifact_event = Artifact(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) + artifact_event = ArtifactEvent(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} @@ -12,7 +12,7 @@ def test_artifact_packaged_v1(): @pytest.mark.unit def test_artifact_published_v1(): - artifact_event = Artifact(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) + artifact_event = ArtifactEvent(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None assert artifact_event._attributes["type"] ==ArtifactType.ArtifactPublishedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py index 95a56e9..bbdbfde 100644 --- a/core/tests/test_branch.py +++ b/core/tests/test_branch.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.branch import Branch, BranchType +from cdevents.core.branch import BranchEvent, BranchType @pytest.mark.unit def test_repository_branch_created(): - branch_event = Branch(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) + branch_event = BranchEvent(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} @@ -12,7 +12,7 @@ def test_repository_branch_created(): @pytest.mark.unit def test_repository_branch_deleted(): - branch_event = Branch(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) + branch_event = BranchEvent(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None assert branch_event._attributes["type"] == BranchType.BranchDeletedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} diff --git a/core/tests/test_build.py b/core/tests/test_build.py index 168fc08..28218cd 100644 --- a/core/tests/test_build.py +++ b/core/tests/test_build.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.build import Build, BuildType +from cdevents.core.build import BuildEvent, BuildType @pytest.mark.unit def test_build_started(): - build_event = Build(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) + build_event = BuildEvent(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} @@ -12,7 +12,7 @@ def test_build_started(): @pytest.mark.unit def test_build_queued(): - build_event = Build(build_type=BuildType.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) + build_event = BuildEvent(build_type=BuildType.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildQueuedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} @@ -20,7 +20,7 @@ def test_build_queued(): @pytest.mark.unit def test_build_finished(): - build_event = Build(build_type=BuildType.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) + build_event = BuildEvent(build_type=BuildType.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildFinishedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py index ed0e201..c0a5ce9 100644 --- a/core/tests/test_environment.py +++ b/core/tests/test_environment.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.env import Env, EnvType +from cdevents.core.env import EnvEvent, EnvType @pytest.mark.unit def test_environment_created(): - env_event = Env(env_type=EnvType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) + env_event = EnvEvent(env_type=EnvType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentCreatedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} @@ -13,7 +13,7 @@ def test_environment_created(): @pytest.mark.unit def test_environment_modified(): - env_event = Env(env_type=EnvType.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) + env_event = EnvEvent(env_type=EnvType.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentModifiedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} @@ -21,7 +21,7 @@ def test_environment_modified(): @pytest.mark.unit def test_environment_deleted(): - env_event = Env(env_type=EnvType.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) + env_event = EnvEvent(env_type=EnvType.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentDeletedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} diff --git a/core/tests/test_events.py b/core/tests/test_events.py index 580977d..b37d1eb 100644 --- a/core/tests/test_events.py +++ b/core/tests/test_events.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.events import Events +from cdevents.core.event import Event @pytest.mark.unit def test_create_event(): - event = Events(event_type="event_type", extensions={"test": "test"}, data={"key1": "value1"}) + event = Event(event_type="event_type", extensions={"test": "test"}, data={"key1": "value1"}) assert event is not None assert event._attributes["type"] == "event_type" assert event._attributes["extensions"] == {"test": "test"} diff --git a/core/tests/test_pipelinerun.py b/core/tests/test_pipelinerun.py index 30a2b41..90e364b 100644 --- a/core/tests/test_pipelinerun.py +++ b/core/tests/test_pipelinerun.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.pipelinerun import Pipelinerun, PipelinerunType +from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunType @pytest.mark.unit def test_pipelinerun_started(): - pipelinerun_event = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) + pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} @@ -12,7 +12,7 @@ def test_pipelinerun_started(): @pytest.mark.unit def test_pipelinerun_finished(): - pipelinerun_event = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) + pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunFinishedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} @@ -20,7 +20,7 @@ def test_pipelinerun_finished(): @pytest.mark.unit def test_pipelinerun_queued(): - pipelinerun_event = Pipelinerun(pipelinerun_type=PipelinerunType.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) + pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunQueuedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} diff --git a/core/tests/test_repository.py b/core/tests/test_repository.py index 7b77efc..e254400 100644 --- a/core/tests/test_repository.py +++ b/core/tests/test_repository.py @@ -1,11 +1,11 @@ from cdevents.core import event_type import pytest -from cdevents.core.repository import Repository, RepositoryType +from cdevents.core.repository import RepositoryEvent, RepositoryType @pytest.mark.unit def test_repository_created(): - repository_event = Repository(repository_type=RepositoryType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) + repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryCreatedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} @@ -14,7 +14,7 @@ def test_repository_created(): @pytest.mark.unit def test_repository_modified(): - repository_event = Repository(repository_type=RepositoryType.RepositoryModifiedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) + repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryModifiedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryModifiedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} @@ -23,7 +23,7 @@ def test_repository_modified(): @pytest.mark.unit def test_repository_deleted(): - repository_event = Repository(repository_type=RepositoryType.RepositoryDeletedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) + repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryDeletedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryDeletedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} diff --git a/core/tests/test_service.py b/core/tests/test_service.py index 235f8e2..da2ba20 100644 --- a/core/tests/test_service.py +++ b/core/tests/test_service.py @@ -1,11 +1,11 @@ from cdevents.core import event_type import pytest -from cdevents.core.service import Service, ServiceType +from cdevents.core.service import ServiceEvent, ServiceType @pytest.mark.unit def test_service_deployed(): - service_event = Service(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) + service_event = ServiceEvent(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -14,7 +14,7 @@ def test_service_deployed(): @pytest.mark.unit def test_service_upgraded(): - service_event = Service(service_type=ServiceType.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) + service_event = ServiceEvent(service_type=ServiceType.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceUpgradedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -23,7 +23,7 @@ def test_service_upgraded(): @pytest.mark.unit def test_service_rolledback(): - service_event = Service(service_type=ServiceType.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) + service_event = ServiceEvent(service_type=ServiceType.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceRolledbackEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -32,7 +32,7 @@ def test_service_rolledback(): @pytest.mark.unit def test_service_removed(): - service_event = Service(service_type=ServiceType.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) + service_event = ServiceEvent(service_type=ServiceType.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceRemovedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} diff --git a/core/tests/test_taskrun.py b/core/tests/test_taskrun.py index 808aadb..332aea1 100644 --- a/core/tests/test_taskrun.py +++ b/core/tests/test_taskrun.py @@ -1,10 +1,10 @@ import pytest -from cdevents.core.taskrun import TaskRun, TaskRunType +from cdevents.core.taskrun import TaskRunEvent, TaskRunType @pytest.mark.unit def test_taskrun_started(): - taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) + taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} @@ -13,7 +13,7 @@ def test_taskrun_started(): @pytest.mark.unit def test_taskrun_finished(): - taskrun_event = TaskRun(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) + taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None assert taskrun_event._attributes["type"] == TaskRunType.TaskRunFinishedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} From 2e3b7ae717be216a846e14e60e7ba1ace291c359 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Thu, 11 Aug 2022 14:01:57 +0200 Subject: [PATCH 31/34] update execute method --- cli/cdevents/cli/artifact.py | 6 +++--- cli/cdevents/cli/branch.py | 6 +++--- cli/cdevents/cli/build.py | 8 +++---- cli/cdevents/cli/env.py | 12 +++++------ cli/cdevents/cli/pipelinerun.py | 8 +++---- cli/cdevents/cli/repository.py | 8 +++---- cli/cdevents/cli/service.py | 20 ++++++++--------- cli/cdevents/cli/taskrun.py | 6 +++--- core/cdevents/core/artifact.py | 18 ++++++++++++++++ core/cdevents/core/branch.py | 9 ++++---- core/cdevents/core/build.py | 27 +++++++++++++++++++++++ core/cdevents/core/env.py | 31 +++++++++++++++++++++++++- core/cdevents/core/pipelinerun.py | 26 ++++++++++++++++++++++ core/cdevents/core/repository.py | 28 ++++++++++++++++++++++++ core/cdevents/core/service.py | 36 +++++++++++++++++++++++++++++++ core/cdevents/core/taskrun.py | 20 ++++++++++++++++- core/tests/test_artifact.py | 18 +++++++++++----- core/tests/test_branch.py | 16 ++++++++++---- core/tests/test_build.py | 20 +++++++++++------ core/tests/test_environment.py | 19 +++++++++++----- core/tests/test_pipelinerun.py | 20 +++++++++++------ core/tests/test_repository.py | 19 ++++++++++------ core/tests/test_service.py | 26 ++++++++++++++-------- core/tests/test_taskrun.py | 17 +++++++++++---- 24 files changed, 332 insertions(+), 92 deletions(-) diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index f48df2c..820c2cf 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.artifact import ArtifactEvent, ArtifactType +from cdevents.core.artifact import ArtifactPackagedEvent, ArtifactPublishedEvent # pylint: disable=unused-argument def common_artifact_options(function): @@ -53,7 +53,7 @@ def packaged( data: List[str] = None, ): print_function_args() - artifact_event = ArtifactEvent(ArtifactType.ArtifactPackagedEventV1, id, name, version, data=data) + artifact_event = ArtifactPackagedEvent(id, name, version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) @@ -67,6 +67,6 @@ def published( data: List[str] = None, ): print_function_args() - artifact_event = ArtifactEvent(ArtifactType.ArtifactPublishedEventV1, id, name, version, data=data) + artifact_event = ArtifactPublishedEvent(id, name, version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) diff --git a/cli/cdevents/cli/branch.py b/cli/cdevents/cli/branch.py index 8f04db2..22cc5db 100644 --- a/cli/cdevents/cli/branch.py +++ b/cli/cdevents/cli/branch.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.branch import BranchEvent, BranchType +from cdevents.core.branch import BranchCreatedEvent, BranchDeletedEvent # pylint: disable=unused-argument def common_branch_options(function): @@ -53,7 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - branch_event = BranchEvent(branch_type=BranchType.BranchCreatedEventV1, id=id, name=name, repoid=repoid, data=data) + branch_event = BranchCreatedEvent(id=id, name=name, repoid=repoid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(branch_event) @@ -67,6 +67,6 @@ def deleted( data: List[str] = None, ): print_function_args() - branch_event = BranchEvent(branch_type=BranchType.BranchDeletedEventV1, id=id, name=name, repoid=repoid, data=data) + branch_event = BranchDeletedEvent(id=id, name=name, repoid=repoid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(branch_event) diff --git a/cli/cdevents/cli/build.py b/cli/cdevents/cli/build.py index 23fdc61..f850e4b 100644 --- a/cli/cdevents/cli/build.py +++ b/cli/cdevents/cli/build.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.build import BuildEvent, BuildType +from cdevents.core.build import BuildStartedEvent, BuildQueuedEvent, BuildFinishedEvent # pylint: disable=unused-argument def common_build_options(function): @@ -54,7 +54,7 @@ def started( data: List[str] = None, ): print_function_args() - build_event = BuildEvent(build_type=BuildType.BuildStartedEventV1, id=id, name=name, artifact=artifact, data=data) + build_event = BuildStartedEvent(id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) @@ -67,7 +67,7 @@ def finished( data: List[str] = None, ): print_function_args() - build_event = BuildEvent(build_type=BuildType.BuildFinishedEventV1, id=id, name=name, artifact=artifact, data=data) + build_event = BuildQueuedEvent(id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) @@ -80,6 +80,6 @@ def queued( data: List[str] = None, ): print_function_args() - build_event = BuildEvent(build_type=BuildType.BuildQueuedEventV1, id=id, name=name, artifact=artifact, data=data) + build_event = BuildFinishedEvent(id=id, name=name, artifact=artifact, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(build_event) diff --git a/cli/cdevents/cli/env.py b/cli/cdevents/cli/env.py index c6e8f56..1d63481 100644 --- a/cli/cdevents/cli/env.py +++ b/cli/cdevents/cli/env.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.env import EnvEvent, EnvType +from cdevents.core.env import EnvEventCreatedEvent, EnvEventModifiedEvent, EnvEventDeletedEvent # pylint: disable=unused-argument def common_env_options(function): @@ -53,12 +53,10 @@ def created( data: List[str] = None, ): print_function_args() - env = EnvEvent(build_type=EnvType.EnvironmentCreatedEventV1, id=id, name=name, repo=repo, data=data) - env_event = env.create_event(data) + env_event = EnvEventCreatedEvent(id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) - @click.command(help=add_disclaimer_text("Environment Deleted CloudEvent.")) @common_env_options def deleted( @@ -68,7 +66,7 @@ def deleted( data: List[str] = None, ): print_function_args() - env_event = EnvEvent(env_type=EnvType.EnvironmentDeletedEventV1, id=id, name=name, repo=repo, data=data) + env_event = EnvEventModifiedEvent(id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(env_event) @@ -81,6 +79,6 @@ def modified( data: List[str] = None, ): print_function_args() - env_event = EnvEvent(env_type=EnvType.EnvironmentModifiedEventV1, id=id, name=name, repo=repo, data=data) + env_event = EnvEventDeletedEvent(id=id, name=name, repo=repo, data=data) cdevents_command = CDeventsCommand() - cdevents_command.run(env_event) \ No newline at end of file + cdevents_command.run(env_event) diff --git a/cli/cdevents/cli/pipelinerun.py b/cli/cdevents/cli/pipelinerun.py index 63897d4..dd732aa 100644 --- a/cli/cdevents/cli/pipelinerun.py +++ b/cli/cdevents/cli/pipelinerun.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunType +from cdevents.core.pipelinerun import PipelinerunStartedEvent, PipelinerunFinishedEvent, PipelinerunQueuedEvent # pylint: disable=unused-argument def common_pipelinerun_options(function): @@ -69,7 +69,7 @@ def started( data: List[str] = None, ): print_function_args() - pipelinerun_event = PipelinerunEvent(PipelinerunType.PipelineRunStartedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) + pipelinerun_event = PipelinerunStartedEvent(id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) @@ -84,7 +84,7 @@ def finished( data: List[str] = None, ): print_function_args() - pipelinerun_event = PipelinerunEvent(PipelinerunType.PipelineRunFinishedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) + pipelinerun_event = PipelinerunFinishedEvent(id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) @@ -100,7 +100,7 @@ def queued( data: List[str] = None, ): print_function_args() - pipelinerun_event = PipelinerunEvent(PipelinerunType.PipelineRunQueuedEventV1, id=id, name=name, status=status, url=url, errors=errors, data=data) + pipelinerun_event = PipelinerunQueuedEvent(id=id, name=name, status=status, url=url, errors=errors, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(pipelinerun_event) diff --git a/cli/cdevents/cli/repository.py b/cli/cdevents/cli/repository.py index 327234c..96404d4 100644 --- a/cli/cdevents/cli/repository.py +++ b/cli/cdevents/cli/repository.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.repository import RepositoryEvent, RepositoryType +from cdevents.core.repository import RepositoryCreatedEvent, RepositoryModifiedEvent, RepositoryDeletedEvent # pylint: disable=unused-argument def common_repository_options(function): @@ -53,7 +53,7 @@ def created( data: List[str] = None, ): print_function_args() - repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryCreatedEventV1, id=id, name=name, url=url, data=data) + repository_event = RepositoryCreatedEvent(id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) @@ -67,7 +67,7 @@ def modified( data: List[str] = None, ): print_function_args() - repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryModifiedEventV1, id=id, name=name, url=url, data=data) + repository_event = RepositoryModifiedEvent(id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) @@ -81,7 +81,7 @@ def deleted( data: List[str] = None, ): print_function_args() - repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryDeletedEventV1, id=id, name=name, url=url, data=data) + repository_event = RepositoryDeletedEvent(id=id, name=name, url=url, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(repository_event) diff --git a/cli/cdevents/cli/service.py b/cli/cdevents/cli/service.py index fb70310..6085200 100644 --- a/cli/cdevents/cli/service.py +++ b/cli/cdevents/cli/service.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.service import ServiceEvent, ServiceType +from cdevents.core.service import ServiceDeployedEvent, ServiceUpgradedEvent, ServiceRolledbackEvent, ServiceRemovedEvent # pylint: disable=unused-argument def common_service_options(function): @@ -53,7 +53,7 @@ def deployed( data: List[str] = None, ): print_function_args() - service_event = ServiceEvent(service_type=ServiceType.ServiceDeployedEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceDeployedEvent(envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) @@ -66,34 +66,32 @@ def upgraded( data: List[str] = None, ): print_function_args() - service_event = ServiceEvent(service_type=ServiceType.ServiceUpgradedEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceUpgradedEvent(envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) - -@click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) +@click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) @common_service_options -def removed( +def rolledback( envid: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - service_event = ServiceEvent(service_type=ServiceType.ServiceRemovedEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceRolledbackEvent(envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) - -@click.command(help=add_disclaimer_text("Service Rolledback CloudEvent.")) +@click.command(help=add_disclaimer_text("Service Removed CloudEvent.")) @common_service_options -def rolledback( +def removed( envid: str, name: str = None, version: str = None, data: List[str] = None, ): print_function_args() - service_event = ServiceEvent(service_type=ServiceType.ServiceRolledbackEventV1, envid=envid, name=name, version=version, data=data) + service_event = ServiceRemovedEvent(envid=envid, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(service_event) diff --git a/cli/cdevents/cli/taskrun.py b/cli/cdevents/cli/taskrun.py index be9a343..50757c0 100644 --- a/cli/cdevents/cli/taskrun.py +++ b/cli/cdevents/cli/taskrun.py @@ -6,7 +6,7 @@ from cdevents.cli.utils import add_disclaimer_text, print_function_args from cdevents.cli.cdevents_command import CDeventsCommand -from cdevents.core.taskrun import TaskRunEvent, TaskRunType +from cdevents.core.taskrun import TaskRunStartedEvent, TaskRunFinishedEvent # pylint: disable=unused-argument def common_taskrun_options(function): @@ -53,7 +53,7 @@ def started( data: List[str] = None, ): print_function_args() - taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunStartedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) + taskrun_event = TaskRunStartedEvent(id=id, name=name, pipelineid=pipelineid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(taskrun_event) @@ -66,7 +66,7 @@ def finished( data: List[str] = None, ): print_function_args() - taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id=id, name=name, pipelineid=pipelineid, data=data) + taskrun_event = TaskRunFinishedEvent(id=id, name=name, pipelineid=pipelineid, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(taskrun_event) diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py index 443dcbe..9bbc431 100644 --- a/core/cdevents/core/artifact.py +++ b/core/cdevents/core/artifact.py @@ -29,3 +29,21 @@ def create_extensions(self) -> dict: "artifactversion": self._version, } return extensions + +class ArtifactPackagedEvent(ArtifactEvent): + + def __init__(self, id: str, name: str, version: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = ArtifactType.ArtifactPackagedEventV1 + + super().__init__(artifact_type=self._event_type, id=id, name=name, version=version, data=data) + +class ArtifactPublishedEvent(ArtifactEvent): + + def __init__(self, id: str, name: str, version: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = ArtifactType.ArtifactPublishedEventV1 + + super().__init__(artifact_type=self._event_type, id=id, name=name, version=version, data=data) diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index c3cee46..494b6e8 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -30,21 +30,20 @@ def create_extensions(self) -> dict: } return extensions -# TODO: Add tests for this class. class BranchCreatedEvent(BranchEvent): def __init__(self, id: str, name: str, repoid: str, data: dict = {}): """Initializes class. """ - self._event_type : str = "cd.repository.branch.created.v1" + self._event_type: str = BranchType.BranchCreatedEventV1 - super().__init__(event_type=self._event_type, id=id, name=name, repoid=repoid, data=data) + super().__init__(branch_type=self._event_type, id=id, name=name, repoid=repoid, data=data) class BranchDeletedEvent(BranchEvent): def __init__(self, id: str, name: str, repoid: str, data: dict = {}): """Initializes class. """ - self._event_type : str = "cd.repository.branch.deleted.v1" + self._event_type: str = BranchType.BranchDeletedEventV1 - super().__init__(event_type=self._event_type, id=id, name=name, repoid=repoid, data=data) + super().__init__(branch_type=self._event_type, id=id, name=name, repoid=repoid, data=data) diff --git a/core/cdevents/core/build.py b/core/cdevents/core/build.py index b80f162..07cc8df 100644 --- a/core/cdevents/core/build.py +++ b/core/cdevents/core/build.py @@ -30,3 +30,30 @@ def create_extensions(self) -> dict: "buildartifactid": self._artifact, } return extensions + +class BuildStartedEvent(BuildEvent): + + def __init__(self, id: str, name: str, artifact: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = BuildType.BuildStartedEventV1 + + super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, data=data) + +class BuildQueuedEvent(BuildEvent): + + def __init__(self, id: str, name: str, artifact: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = BuildType.BuildQueuedEventV1 + + super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, data=data) + +class BuildFinishedEvent(BuildEvent): + + def __init__(self, id: str, name: str, artifact: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = BuildType.BuildFinishedEventV1 + + super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, data=data) diff --git a/core/cdevents/core/env.py b/core/cdevents/core/env.py index 2b47cb8..75fdb11 100644 --- a/core/cdevents/core/env.py +++ b/core/cdevents/core/env.py @@ -12,7 +12,7 @@ class EnvType(Enum): class EnvEvent(Event): """Env Event.""" - def __init__(self, env_type: EnvType, id: str, name: str, repo: str,data: dict = {}): + def __init__(self, env_type: EnvType, id: str, name: str, repo: str, data: dict = {}): """Initializes class. """ self._event_type = env_type @@ -30,3 +30,32 @@ def create_extensions(self) -> dict: "envrepourl": self._repo, } return extensions + +class EnvEventCreatedEvent(EnvEvent): + + def __init__(self, id: str, name: str, repo: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = EnvType.EnvironmentCreatedEventV1 + + super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, data=data) + +class EnvEventModifiedEvent(EnvEvent): + + def __init__(self, id: str, name: str, repo: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = EnvType.EnvironmentModifiedEventV1 + + super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, data=data) + + +class EnvEventDeletedEvent(EnvEvent): + + def __init__(self, id: str, name: str, repo: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = EnvType.EnvironmentDeletedEventV1 + + super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, data=data) + diff --git a/core/cdevents/core/pipelinerun.py b/core/cdevents/core/pipelinerun.py index bc34fe2..56d4df8 100644 --- a/core/cdevents/core/pipelinerun.py +++ b/core/cdevents/core/pipelinerun.py @@ -35,3 +35,29 @@ def create_extensions(self) -> dict: } return extensions +class PipelinerunStartedEvent(PipelinerunEvent): + + def __init__(self, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = PipelinerunType.PipelineRunStartedEventV1 + + super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, data=data) + +class PipelinerunFinishedEvent(PipelinerunEvent): + + def __init__(self, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = PipelinerunType.PipelineRunFinishedEventV1 + + super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, data=data) + +class PipelinerunQueuedEvent(PipelinerunEvent): + + def __init__(self, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = PipelinerunType.PipelineRunQueuedEventV1 + + super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, data=data) diff --git a/core/cdevents/core/repository.py b/core/cdevents/core/repository.py index 52e9b46..51cbc50 100644 --- a/core/cdevents/core/repository.py +++ b/core/cdevents/core/repository.py @@ -30,3 +30,31 @@ def create_extensions(self) -> dict: "repositoryurl": self._url, } return extensions + +class RepositoryCreatedEvent(RepositoryEvent): + + def __init__(self, id: str, name: str, url: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = RepositoryType.RepositoryCreatedEventV1 + + super().__init__(repository_type=self._event_type, id=id, name=name, url=url, data=data) + +class RepositoryModifiedEvent(RepositoryEvent): + + def __init__(self, id: str, name: str, url: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = RepositoryType.RepositoryModifiedEventV1 + + super().__init__(repository_type=self._event_type, id=id, name=name, url=url, data=data) + +class RepositoryDeletedEvent(RepositoryEvent): + + def __init__(self, id: str, name: str, url: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = RepositoryType.RepositoryDeletedEventV1 + + super().__init__(repository_type=self._event_type, id=id, name=name, url=url, data=data) + diff --git a/core/cdevents/core/service.py b/core/cdevents/core/service.py index dcccb62..b294ff4 100644 --- a/core/cdevents/core/service.py +++ b/core/cdevents/core/service.py @@ -32,3 +32,39 @@ def create_extensions(self) -> dict: } return extensions +class ServiceDeployedEvent(ServiceEvent): + + def __init__(self, envid: str, name: str, version: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = ServiceType.ServiceDeployedEventV1 + + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + +class ServiceUpgradedEvent(ServiceEvent): + + def __init__(self, envid: str, name: str, version: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = ServiceType.ServiceUpgradedEventV1 + + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + +class ServiceRolledbackEvent(ServiceEvent): + + def __init__(self, envid: str, name: str, version: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = ServiceType.ServiceRolledbackEventV1 + + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + +class ServiceRemovedEvent(ServiceEvent): + + def __init__(self, envid: str, name: str, version: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = ServiceType.ServiceRemovedEventV1 + + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + diff --git a/core/cdevents/core/taskrun.py b/core/cdevents/core/taskrun.py index 462f4d1..92594db 100644 --- a/core/cdevents/core/taskrun.py +++ b/core/cdevents/core/taskrun.py @@ -28,4 +28,22 @@ def create_extensions(self) -> dict: "taskrunname": self._name, "taskrunpipelineid": self._pipelineid, } - return extensions \ No newline at end of file + return extensions + +class TaskRunStartedEvent(TaskRunEvent): + + def __init__(self, id: str, name: str, pipelineid: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = TaskRunType.TaskRunStartedEventV1 + + super().__init__(taskrun_type=self._event_type, id=id, name=name, pipelineid=pipelineid, data=data) + +class TaskRunFinishedEvent(TaskRunEvent): + + def __init__(self, id: str, name: str, pipelineid: str, data: dict = {}): + """Initializes class. + """ + self._event_type: str = TaskRunType.TaskRunFinishedEventV1 + + super().__init__(taskrun_type=self._event_type, id=id, name=name, pipelineid=pipelineid, data=data) diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py index c8b4acd..d936e30 100644 --- a/core/tests/test_artifact.py +++ b/core/tests/test_artifact.py @@ -1,9 +1,9 @@ import pytest -from cdevents.core.artifact import ArtifactEvent, ArtifactType +from cdevents.core.artifact import ArtifactEvent, ArtifactType, ArtifactPackagedEvent, ArtifactPublishedEvent @pytest.mark.unit -def test_artifact_packaged_v1(): +def test_artifact_created(): artifact_event = ArtifactEvent(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value @@ -11,10 +11,18 @@ def test_artifact_packaged_v1(): assert artifact_event.data == {"key1": "value1"} @pytest.mark.unit -def test_artifact_published_v1(): - artifact_event = ArtifactEvent(artifact_type=ArtifactType.ArtifactPublishedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) +def test_artifact_type_packaged_v1(): + artifact_event = ArtifactPackagedEvent(id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None - assert artifact_event._attributes["type"] ==ArtifactType.ArtifactPublishedEventV1.value + assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value + assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} + assert artifact_event.data == {"key1": "value1"} + +@pytest.mark.unit +def test_artifact_type_published_v1(): + artifact_event = ArtifactPublishedEvent(id="_id", name="_name", version="_version",data={"key1": "value1"}) + assert artifact_event is not None + assert artifact_event._attributes["type"] == ArtifactType.ArtifactPublishedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} assert artifact_event.data == {"key1": "value1"} diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py index bbdbfde..c81e851 100644 --- a/core/tests/test_branch.py +++ b/core/tests/test_branch.py @@ -1,9 +1,9 @@ import pytest -from cdevents.core.branch import BranchEvent, BranchType +from cdevents.core.branch import BranchEvent, BranchType, BranchCreatedEvent, BranchDeletedEvent @pytest.mark.unit -def test_repository_branch_created(): +def test_branch_created(): branch_event = BranchEvent(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value @@ -11,8 +11,16 @@ def test_repository_branch_created(): assert branch_event.data == {"key1": "value1"} @pytest.mark.unit -def test_repository_branch_deleted(): - branch_event = BranchEvent(branch_type=BranchType.BranchDeletedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) +def test_branch_type_created_v1(): + branch_event = BranchCreatedEvent(id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) + assert branch_event is not None + assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value + assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} + assert branch_event.data == {"key1": "value1"} + +@pytest.mark.unit +def test_branch_type_deleted_v1(): + branch_event = BranchDeletedEvent(id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None assert branch_event._attributes["type"] == BranchType.BranchDeletedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} diff --git a/core/tests/test_build.py b/core/tests/test_build.py index 28218cd..2b23b0f 100644 --- a/core/tests/test_build.py +++ b/core/tests/test_build.py @@ -1,9 +1,9 @@ import pytest -from cdevents.core.build import BuildEvent, BuildType +from cdevents.core.build import BuildEvent, BuildType, BuildStartedEvent, BuildQueuedEvent, BuildFinishedEvent @pytest.mark.unit -def test_build_started(): +def test_build_created(): build_event = BuildEvent(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value @@ -11,16 +11,24 @@ def test_build_started(): assert build_event.data == {"key1": "value1"} @pytest.mark.unit -def test_build_queued(): - build_event = BuildEvent(build_type=BuildType.BuildQueuedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) +def test_build_type_started_v1(): + build_event = BuildStartedEvent(id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) + assert build_event is not None + assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value + assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} + assert build_event.data == {"key1": "value1"} + +@pytest.mark.unit +def test_build_type_queued_v1(): + build_event = BuildQueuedEvent(id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildQueuedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} assert build_event.data == {"key1": "value1"} @pytest.mark.unit -def test_build_finished(): - build_event = BuildEvent(build_type=BuildType.BuildFinishedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) +def test_build_type_finished_v1(): + build_event = BuildFinishedEvent(id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None assert build_event._attributes["type"] == BuildType.BuildFinishedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py index c0a5ce9..ebec2fd 100644 --- a/core/tests/test_environment.py +++ b/core/tests/test_environment.py @@ -1,6 +1,6 @@ import pytest -from cdevents.core.env import EnvEvent, EnvType +from cdevents.core.env import EnvEvent, EnvType, EnvEventCreatedEvent, EnvEventModifiedEvent, EnvEventDeletedEvent @pytest.mark.unit def test_environment_created(): @@ -12,16 +12,25 @@ def test_environment_created(): @pytest.mark.unit -def test_environment_modified(): - env_event = EnvEvent(env_type=EnvType.EnvironmentModifiedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) +def test_environment_type_created_v1(): + env_event = EnvEventCreatedEvent(id="_id", name="_name", repo="_repo", data={"key1": "value1"}) + assert env_event is not None + assert env_event._attributes["type"] == EnvType.EnvironmentCreatedEventV1.value + assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} + assert env_event.data == {"key1": "value1"} + + +@pytest.mark.unit +def test_environment_type_modified_v1(): + env_event = EnvEventModifiedEvent(id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentModifiedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} assert env_event.data == {"key1": "value1"} @pytest.mark.unit -def test_environment_deleted(): - env_event = EnvEvent(env_type=EnvType.EnvironmentDeletedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) +def test_environment_type_deleted_v1(): + env_event = EnvEventDeletedEvent(id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None assert env_event._attributes["type"] == EnvType.EnvironmentDeletedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} diff --git a/core/tests/test_pipelinerun.py b/core/tests/test_pipelinerun.py index 90e364b..f7f4a9d 100644 --- a/core/tests/test_pipelinerun.py +++ b/core/tests/test_pipelinerun.py @@ -1,9 +1,9 @@ import pytest -from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunType +from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunType, PipelinerunStartedEvent, PipelinerunFinishedEvent, PipelinerunQueuedEvent @pytest.mark.unit -def test_pipelinerun_started(): +def test_pipelinerun_created(): pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value @@ -11,16 +11,24 @@ def test_pipelinerun_started(): assert pipelinerun_event.data == {"key1": "value1"} @pytest.mark.unit -def test_pipelinerun_finished(): - pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunFinishedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) +def test_pipelinerun_type_started_v1(): + pipelinerun_event = PipelinerunStartedEvent(id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) + assert pipelinerun_event is not None + assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value + assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} + assert pipelinerun_event.data == {"key1": "value1"} + +@pytest.mark.unit +def test_pipelinerun_type_finished_v1(): + pipelinerun_event = PipelinerunFinishedEvent( id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunFinishedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} assert pipelinerun_event.data == {"key1": "value1"} @pytest.mark.unit -def test_pipelinerun_queued(): - pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunQueuedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) +def test_pipelinerun_type_queued_v1(): + pipelinerun_event = PipelinerunQueuedEvent(id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunQueuedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} diff --git a/core/tests/test_repository.py b/core/tests/test_repository.py index e254400..153efc7 100644 --- a/core/tests/test_repository.py +++ b/core/tests/test_repository.py @@ -1,7 +1,6 @@ -from cdevents.core import event_type import pytest -from cdevents.core.repository import RepositoryEvent, RepositoryType +from cdevents.core.repository import RepositoryEvent, RepositoryType, RepositoryCreatedEvent, RepositoryModifiedEvent, RepositoryDeletedEvent @pytest.mark.unit def test_repository_created(): @@ -11,19 +10,25 @@ def test_repository_created(): assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} assert repository_event.data == {"key1": "value1"} +@pytest.mark.unit +def test_repository_type_created_v1(): + repository_event = RepositoryCreatedEvent(id="_id", name="_name", url="_url", data={"key1": "value1"}) + assert repository_event is not None + assert repository_event._attributes["type"] == RepositoryType.RepositoryCreatedEventV1.value + assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} + assert repository_event.data == {"key1": "value1"} @pytest.mark.unit -def test_repository_modified(): - repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryModifiedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) +def test_repository_type_modified_v1(): + repository_event = RepositoryModifiedEvent(id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryModifiedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} assert repository_event.data == {"key1": "value1"} - @pytest.mark.unit -def test_repository_deleted(): - repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryDeletedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) +def test_repository_type_deleted_v1(): + repository_event = RepositoryDeletedEvent(id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None assert repository_event._attributes["type"] == RepositoryType.RepositoryDeletedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} diff --git a/core/tests/test_service.py b/core/tests/test_service.py index da2ba20..3c71086 100644 --- a/core/tests/test_service.py +++ b/core/tests/test_service.py @@ -1,10 +1,9 @@ -from cdevents.core import event_type import pytest -from cdevents.core.service import ServiceEvent, ServiceType +from cdevents.core.service import ServiceEvent, ServiceType, ServiceDeployedEvent, ServiceUpgradedEvent, ServiceRolledbackEvent, ServiceRemovedEvent @pytest.mark.unit -def test_service_deployed(): +def test_service_created(): service_event = ServiceEvent(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value @@ -13,8 +12,17 @@ def test_service_deployed(): @pytest.mark.unit -def test_service_upgraded(): - service_event = ServiceEvent(service_type=ServiceType.ServiceUpgradedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) +def test_service_type_deployed_v1(): + service_event = ServiceDeployedEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) + assert service_event is not None + assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value + assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} + assert service_event.data == {"key1": "value1"} + + +@pytest.mark.unit +def test_service_type_upgraded_v1(): + service_event = ServiceUpgradedEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceUpgradedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -22,8 +30,8 @@ def test_service_upgraded(): @pytest.mark.unit -def test_service_rolledback(): - service_event = ServiceEvent(service_type=ServiceType.ServiceRolledbackEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) +def test_service_type_rolledback_v1(): + service_event = ServiceRolledbackEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceRolledbackEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} @@ -31,8 +39,8 @@ def test_service_rolledback(): @pytest.mark.unit -def test_service_removed(): - service_event = ServiceEvent(service_type=ServiceType.ServiceRemovedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) +def test_service_type_removed_v1(): + service_event = ServiceRemovedEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None assert service_event._attributes["type"] == ServiceType.ServiceRemovedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} diff --git a/core/tests/test_taskrun.py b/core/tests/test_taskrun.py index 332aea1..76171d6 100644 --- a/core/tests/test_taskrun.py +++ b/core/tests/test_taskrun.py @@ -1,9 +1,9 @@ import pytest -from cdevents.core.taskrun import TaskRunEvent, TaskRunType +from cdevents.core.taskrun import TaskRunEvent, TaskRunType, TaskRunStartedEvent, TaskRunFinishedEvent @pytest.mark.unit -def test_taskrun_started(): +def test_taskrun_created(): taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value @@ -12,8 +12,17 @@ def test_taskrun_started(): @pytest.mark.unit -def test_taskrun_finished(): - taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunFinishedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) +def test_taskrun_type_started_v1(): + taskrun_event = TaskRunStartedEvent(id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) + assert taskrun_event is not None + assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value + assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} + assert taskrun_event.data == {"key1": "value1"} + + +@pytest.mark.unit +def test_taskrun_type_finished_v1(): + taskrun_event = TaskRunFinishedEvent(id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None assert taskrun_event._attributes["type"] == TaskRunType.TaskRunFinishedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} From 6a72aaec546500f5cc30643836f231029e96d2f4 Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Wed, 17 Aug 2022 13:53:45 +0200 Subject: [PATCH 32/34] add receiver --- .gitignore | 3 + cli/cdevents/cli/artifact.py | 4 +- cli/cdevents/cli/cdevents_command.py | 1 - core/cdevents/core/artifact.py | 43 +++++----- core/cdevents/core/branch.py | 43 +++++----- core/cdevents/core/build.py | 60 ++++++------- core/cdevents/core/env.py | 48 ++++++----- core/cdevents/core/event.py | 29 +++---- core/cdevents/core/event_type.py | 75 +++++++++++++---- core/cdevents/core/http_handlar.py | 121 +++++++++++++++++++++++++++ core/cdevents/core/pipelinerun.py | 54 ++++++------ core/cdevents/core/repository.py | 48 ++++++----- core/cdevents/core/service.py | 55 ++++++------ core/cdevents/core/taskrun.py | 43 +++++----- core/tests/test_artifact.py | 11 +-- core/tests/test_branch.py | 11 +-- core/tests/test_build.py | 13 +-- core/tests/test_environment.py | 13 +-- core/tests/test_pipelinerun.py | 13 +-- core/tests/test_repository.py | 13 +-- core/tests/test_service.py | 15 ++-- core/tests/test_taskrun.py | 11 +-- receiver/cdevents/api/app.py | 25 ++++++ 23 files changed, 492 insertions(+), 260 deletions(-) create mode 100644 core/cdevents/core/http_handlar.py create mode 100644 receiver/cdevents/api/app.py diff --git a/.gitignore b/.gitignore index b6e4761..58710ec 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,6 @@ dmypy.json # Pyre type checker .pyre/ + +# VS Code +.vscode \ No newline at end of file diff --git a/cli/cdevents/cli/artifact.py b/cli/cdevents/cli/artifact.py index 820c2cf..7febb6f 100644 --- a/cli/cdevents/cli/artifact.py +++ b/cli/cdevents/cli/artifact.py @@ -53,7 +53,7 @@ def packaged( data: List[str] = None, ): print_function_args() - artifact_event = ArtifactPackagedEvent(id, name, version, data=data) + artifact_event = ArtifactPackagedEvent(id=id, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) @@ -67,6 +67,6 @@ def published( data: List[str] = None, ): print_function_args() - artifact_event = ArtifactPublishedEvent(id, name, version, data=data) + artifact_event = ArtifactPublishedEvent(id=id, name=name, version=version, data=data) cdevents_command = CDeventsCommand() cdevents_command.run(artifact_event) diff --git a/cli/cdevents/cli/cdevents_command.py b/cli/cdevents/cli/cdevents_command.py index 2365ae7..633226d 100644 --- a/cli/cdevents/cli/cdevents_command.py +++ b/cli/cdevents/cli/cdevents_command.py @@ -1,7 +1,6 @@ """Module for cli common command code.""" import logging from abc import ABC -import requests from cloudevents.http import CloudEvent diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py index 9bbc431..256d9cd 100644 --- a/core/cdevents/core/artifact.py +++ b/core/cdevents/core/artifact.py @@ -1,25 +1,30 @@ """artifact""" -from enum import Enum from cdevents.core.event import Event - -class ArtifactType(Enum): - ArtifactPackagedEventV1: str = "cd.artifact.packaged.v1" - ArtifactPublishedEventV1: str = "cd.artifact.published.v1" - +from cdevents.core.event_type import EventType class ArtifactEvent(Event): """Artifact Event.""" - def __init__(self, artifact_type: ArtifactType, id: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = artifact_type - self._id = id - self._name = name - self._version = version - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - + self._event_type : EventType = kwargs['artifact_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'version' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._version :str = kwargs['version'] + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + + elif 'extensions' in kwargs: + self._id = kwargs['extensions'].get('artifactid') + self._name = kwargs['extensions'].get('artifactname') + self._version = kwargs['extensions'].get('artifactversion') + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + def create_extensions(self) -> dict: """Create extensions. """ @@ -32,18 +37,18 @@ def create_extensions(self) -> dict: class ArtifactPackagedEvent(ArtifactEvent): - def __init__(self, id: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = ArtifactType.ArtifactPackagedEventV1 + self._event_type: str = EventType.ArtifactPackagedEventV1 - super().__init__(artifact_type=self._event_type, id=id, name=name, version=version, data=data) + super().__init__(artifact_type=self._event_type, **kwargs) class ArtifactPublishedEvent(ArtifactEvent): - def __init__(self, id: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = ArtifactType.ArtifactPublishedEventV1 + self._event_type: str = EventType.ArtifactPublishedEventV1 - super().__init__(artifact_type=self._event_type, id=id, name=name, version=version, data=data) + super().__init__(artifact_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index 494b6e8..f02aca8 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -1,25 +1,30 @@ """branch""" -from enum import Enum from cdevents.core.event import Event - -class BranchType(Enum): - BranchCreatedEventV1: str = "cd.repository.branch.created.v1" - BranchDeletedEventV1: str = "cd.repository.branch.deleted.v1" - +from cdevents.core.event_type import EventType class BranchEvent(Event): """Branch Event.""" - def __init__(self, branch_type: BranchType, id: str, name: str, repoid: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = branch_type - self._id = id - self._name = name - self._repoid = repoid - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - + self._event_type : EventType = kwargs['branch_type'] + + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'repoid' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._repoid :str = kwargs['repoid'] + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + elif 'extensions' in kwargs: + self._id = kwargs['extensions'].get('branchid') + self._name = kwargs['extensions'].get('branchname') + self._repoid = kwargs['extensions'].get('branchrepositoryid') + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + def create_extensions(self) -> dict: """Create extensions. """ @@ -32,18 +37,18 @@ def create_extensions(self) -> dict: class BranchCreatedEvent(BranchEvent): - def __init__(self, id: str, name: str, repoid: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = BranchType.BranchCreatedEventV1 + self._event_type: str = EventType.BranchCreatedEventV1 - super().__init__(branch_type=self._event_type, id=id, name=name, repoid=repoid, data=data) + super().__init__(branch_type=self._event_type, **kwargs) class BranchDeletedEvent(BranchEvent): - def __init__(self, id: str, name: str, repoid: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = BranchType.BranchDeletedEventV1 + self._event_type: str = EventType.BranchDeletedEventV1 - super().__init__(branch_type=self._event_type, id=id, name=name, repoid=repoid, data=data) + super().__init__(branch_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/build.py b/core/cdevents/core/build.py index 07cc8df..c700983 100644 --- a/core/cdevents/core/build.py +++ b/core/cdevents/core/build.py @@ -1,26 +1,30 @@ """build""" -from enum import Enum -from cdevents.core.event import Event - -class BuildType(Enum): - BuildStartedEventV1 :str = "cd.build.started.v1" - BuildQueuedEventV1 :str = "cd.build.queued.v1" - BuildFinishedEventV1 :str = "cd.build.finished.v1" - +from cdevents.core.event import Event +from cdevents.core.event_type import EventType class BuildEvent(Event): """Build Event.""" - def __init__(self, build_type: BuildType, id: str, name: str, artifact: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = build_type - self._id = id - self._name = name - self._artifact = artifact - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - + self._event_type : EventType = kwargs['build_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'artifact' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._artifact :str = kwargs['artifact'] + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + + elif 'extensions' in kwargs: + self._id = kwargs['extensions'].get('buildid'), + self._name = kwargs['extensions'].get('buildname') + self._artifact = kwargs['extensions'].get('buildartifactid') + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=kwargs['attrs'], data=self._data) + def create_extensions(self) -> dict: """Create extensions. """ @@ -32,28 +36,28 @@ def create_extensions(self) -> dict: return extensions class BuildStartedEvent(BuildEvent): - - def __init__(self, id: str, name: str, artifact: str, data: dict = {}): + """Build Started Event.""" + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = BuildType.BuildStartedEventV1 + self._event_type: str = EventType.BuildStartedEventV1 - super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, data=data) - -class BuildQueuedEvent(BuildEvent): + super().__init__(build_type=self._event_type, **kwargs) - def __init__(self, id: str, name: str, artifact: str, data: dict = {}): +class BuildQueuedEvent(BuildEvent): + """Build Queued Event.""" + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = BuildType.BuildQueuedEventV1 + self._event_type: str = EventType.BuildQueuedEventV1 - super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, data=data) + super().__init__(build_type=self._event_type, **kwargs) class BuildFinishedEvent(BuildEvent): - - def __init__(self, id: str, name: str, artifact: str, data: dict = {}): + """Build Finished Event.""" + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = BuildType.BuildFinishedEventV1 + self._event_type: str = EventType.BuildFinishedEventV1 - super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, data=data) + super().__init__(build_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/env.py b/core/cdevents/core/env.py index 75fdb11..29db00f 100644 --- a/core/cdevents/core/env.py +++ b/core/cdevents/core/env.py @@ -1,25 +1,29 @@ """env""" -from enum import Enum from cdevents.core.event import Event - -class EnvType(Enum): - EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" - EnvironmentModifiedEventV1 :str = "cd.environment.modified.v1" - EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" - +from cdevents.core.event_type import EventType class EnvEvent(Event): """Env Event.""" - def __init__(self, env_type: EnvType, id: str, name: str, repo: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = env_type - self._id = id - self._name = name - self._repo = repo - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) + self._event_type : EventType = kwargs['env_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'repo' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._repo :str = kwargs['repo'] + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + + elif 'extensions' in kwargs: + self._id = kwargs['extensions'].get('envId') + self._name = kwargs['extensions'].get('envname') + self._repo = kwargs['extensions'].get('envrepourl') + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) def create_extensions(self) -> dict: """Create extensions. @@ -33,29 +37,29 @@ def create_extensions(self) -> dict: class EnvEventCreatedEvent(EnvEvent): - def __init__(self, id: str, name: str, repo: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = EnvType.EnvironmentCreatedEventV1 + self._event_type: str = EventType.EnvironmentCreatedEventV1 - super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, data=data) + super().__init__(env_type=self._event_type, **kwargs) class EnvEventModifiedEvent(EnvEvent): - def __init__(self, id: str, name: str, repo: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = EnvType.EnvironmentModifiedEventV1 + self._event_type: str = EventType.EnvironmentModifiedEventV1 - super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, data=data) + super().__init__(env_type=self._event_type, **kwargs) class EnvEventDeletedEvent(EnvEvent): - def __init__(self, id: str, name: str, repo: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = EnvType.EnvironmentDeletedEventV1 + self._event_type: str = EventType.EnvironmentDeletedEventV1 - super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, data=data) + super().__init__(env_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/event.py b/core/cdevents/core/event.py index 2f9eed2..4217e43 100644 --- a/core/cdevents/core/event.py +++ b/core/cdevents/core/event.py @@ -6,19 +6,22 @@ class Event(CloudEvent): """Event.""" - def __init__(self, event_type: str, extensions: dict, data = {}): + def __init__(self, event_type: str, extensions: dict, attrs=None, data = {}): """Initializes class. """ - self._event_type = event_type - self._extensions = extensions - self._data = data + if attrs: + super().__init__(attributes=attrs, data=data) + else: + self._event_type = event_type + self._extensions = extensions + self._data = data - self._attributes = { - "type": self._event_type, - "source": "cde-cli", - "extensions": self._extensions, - } - super().__init__(self._attributes, dict(self._data)) + self._attributes = { + "type": self._event_type, + "source": "cde-cli", + "extensions": self._extensions, + } + super().__init__(self._attributes, dict(self._data)) @abstractmethod def create_extensions(self) -> dict: @@ -26,9 +29,3 @@ def create_extensions(self) -> dict: """ extensions = {} return extensions - - # @abstractmethod - # def event_from_json(json_obj: dict) -> Events: - # """Create event from json. - # """ - # pass \ No newline at end of file diff --git a/core/cdevents/core/event_type.py b/core/cdevents/core/event_type.py index 58cf2a0..6b43dd1 100644 --- a/core/cdevents/core/event_type.py +++ b/core/cdevents/core/event_type.py @@ -1,20 +1,63 @@ """Constants Event types.""" +from enum import Enum + # pylint: TODO: -# Change Events -ChangeCreatedEventV1 :str = "cd.repository.change.created.v1" -ChangeUpdatedEventV1 :str = "cd.repository.change.updated.v1" -ChangeReviewedEventV1 :str = "cd.repository.change.reviewed.v1" -ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" -ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" - -# TestCase Events -TestCaseStartedEventV1 :str = "cd.test.case.started.v1" -TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" -TestCaseFinishedEventV1 :str = "cd.test.case.finished.v1" - -# TestSuite Events -TestSuiteStartedEventV1 :str = "cd.test.suite.started.v1" -TestSuiteQueuedEventV1 :str = "cd.test.suite.queued.v1" -TestSuiteFinishedEventV1 :str = "cd.test.suite.finished.v1" +# # Change Events +# ChangeCreatedEventV1 :str = "cd.repository.change.created.v1" +# ChangeUpdatedEventV1 :str = "cd.repository.change.updated.v1" +# ChangeReviewedEventV1 :str = "cd.repository.change.reviewed.v1" +# ChangeMergedEventV1 :str = "cd.repository.change.merged.v1" +# ChangeAbandonedEventV1 :str = "cd.repository.change.abandoned.v1" + +# # TestCase Events +# TestCaseStartedEventV1 :str = "cd.test.case.started.v1" +# TestCaseQueuedEventV1 :str = "cd.test.case.queued.v1" +# TestCaseFinishedEventV1 :str = "cd.test.case.finished.v1" + +# # TestSuite Events +# TestSuiteStartedEventV1 :str = "cd.test.suite.started.v1" +# TestSuiteQueuedEventV1 :str = "cd.test.suite.queued.v1" +# TestSuiteFinishedEventV1 :str = "cd.test.suite.finished.v1" + +class EventType(Enum): + """Constants Event types.""" + + # Artifact Events + ArtifactPackagedEventV1: str = "cd.artifact.packaged.v1" + ArtifactPublishedEventV1: str = "cd.artifact.published.v1" + + # Branch Events + BranchCreatedEventV1: str = "cd.repository.branch.created.v1" + BranchDeletedEventV1: str = "cd.repository.branch.deleted.v1" + + # Build Events + BuildStartedEventV1 :str = "cd.build.started.v1" + BuildQueuedEventV1 :str = "cd.build.queued.v1" + BuildFinishedEventV1 :str = "cd.build.finished.v1" + + # Environment Events + EnvironmentCreatedEventV1 :str = "cd.environment.created.v1" + EnvironmentModifiedEventV1 :str = "cd.environment.modified.v1" + EnvironmentDeletedEventV1 :str = "cd.environment.deleted.v1" + + # PipelineRun Events + PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" + PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" + PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" + + # Repository Events + RepositoryCreatedEventV1 :str = "cd.repository.created.v1" + RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" + RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" + + # Service Events + ServiceDeployedEventV1 :str = "cd.service.deployed.v1" + ServiceUpgradedEventV1 :str = "cd.service.upgraded.v1" + ServiceRolledbackEventV1 :str = "cd.service.rolledback.v1" + ServiceRemovedEventV1 :str = "cd.service.removed.v1" + + # TaskRun Events + TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" + TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" diff --git a/core/cdevents/core/http_handlar.py b/core/cdevents/core/http_handlar.py new file mode 100644 index 0000000..753eb07 --- /dev/null +++ b/core/cdevents/core/http_handlar.py @@ -0,0 +1,121 @@ +import typing +import json + +# from cloudevents.http import from_http +import cloudevents.exceptions as cloud_exceptions +from cloudevents.http.event import CloudEvent +from cloudevents.http.event_type import is_binary +from cloudevents.http.mappings import _obj_by_version +from cloudevents.http.util import _json_or_string +from cloudevents.sdk import marshaller, types + + +from cdevents.core.event import Event +from cdevents.core.event_type import EventType + +from cdevents.core.artifact import ArtifactPackagedEvent, ArtifactPublishedEvent +from cdevents.core.build import BuildStartedEvent, BuildFinishedEvent, BuildQueuedEvent + +class HttpHandlar(): + """Http Handlar.""" + + def get_attrs( + headers: typing.Dict[str, str], + data: typing.Union[str, bytes, None], + data_unmarshaller: types.UnmarshallerType = None, + ): + """ + Unwrap a CD_evnets (binary or structured) from an HTTP request. + :param headers: the HTTP headers + :type headers: typing.Dict[str, str] + :param data: the HTTP request body. If set to None, "" or b'', the returned + event's data field will be set to None + :type data: typing.IO + :param data_unmarshaller: Callable function to map data to a python object + e.g. lambda x: x or lambda x: json.loads(x) + :type data_unmarshaller: types.UnmarshallerType + """ + if data is None or data == b"": + # Empty string will cause data to be marshalled into None + data = "" + + if not isinstance(data, (str, bytes, bytearray)): + raise cloud_exceptions.InvalidStructuredJSON( + "Expected json of type (str, bytes, bytearray), " + f"but instead found type {type(data)}" + ) + + headers = {key.lower(): value for key, value in headers.items()} + if data_unmarshaller is None: + data_unmarshaller = _json_or_string + + marshall = marshaller.NewDefaultHTTPMarshaller() + + if is_binary(headers): + specversion = headers.get("ce-specversion", None) + else: + try: + raw_ce = json.loads(data) + except json.decoder.JSONDecodeError: + raise cloud_exceptions.MissingRequiredFields( + "Failed to read specversion from both headers and data. " + f"The following can not be parsed as json: {data}" + ) + if hasattr(raw_ce, "get"): + specversion = raw_ce.get("specversion", None) + else: + raise cloud_exceptions.MissingRequiredFields( + "Failed to read specversion from both headers and data. " + f"The following deserialized data has no 'get' method: {raw_ce}" + ) + + if specversion is None: + raise cloud_exceptions.MissingRequiredFields( + "Failed to find specversion in HTTP request" + ) + + event_handler = _obj_by_version.get(specversion, None) + + if event_handler is None: + raise cloud_exceptions.InvalidRequiredFields( + f"Found invalid specversion {specversion}" + ) + + event = marshall.FromRequest( + event_handler(), headers, data, data_unmarshaller=data_unmarshaller + ) + # if event.data == "" or event.data == b"": + # # TODO: Check binary unmarshallers to debug why setting data to "" + # # returns an event with data set to None, but structured will return "" + # data = None + attrs = event.Properties() + return attrs + + + def event_from_http(headers: typing.Dict[str, str], + data: typing.Union[str, bytes, None], + data_unmarshaller: types.UnmarshallerType = None + ): + attrs = HttpHandlar.get_attrs(headers, data, data_unmarshaller) + + event_data=attrs.pop("data", None) + extensions=attrs.pop("extensions", None) + + etype = EventType(attrs.get("type")) + if etype.value == "" or etype.value is None: + raise cloud_exceptions.MissingRequiredFields( + "Failed to find type in HTTP request" + ) + elif etype.value == EventType.ArtifactPackagedEventV1.value: + return ArtifactPackagedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.ArtifactPublishedEventV1.value: + return ArtifactPublishedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.BuildStartedEventV1.value: + return BuildStartedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.BuildQueuedEventV1.value: + return BuildQueuedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.BuildFinishedEventV1.value: + return BuildFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) + + # e = BuildStartedEvent.create_from_event(event) + # return e \ No newline at end of file diff --git a/core/cdevents/core/pipelinerun.py b/core/cdevents/core/pipelinerun.py index 56d4df8..3ae8a2f 100644 --- a/core/cdevents/core/pipelinerun.py +++ b/core/cdevents/core/pipelinerun.py @@ -1,27 +1,33 @@ """pipelinerun""" -from enum import Enum from cdevents.core.event import Event - -class PipelinerunType(Enum): - PipelineRunStartedEventV1 :str = "cd.pipelinerun.started.v1" - PipelineRunFinishedEventV1 :str = "cd.pipelinerun.finished.v1" - PipelineRunQueuedEventV1 :str = "cd.pipelinerun.queued.v1" - +from cdevents.core.event_type import EventType class PipelinerunEvent(Event): """Pipelinerun Event.""" - def __init__(self, pipelinerun_type: PipelinerunType, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = pipelinerun_type - self._id = id - self._name = name - self._status = status - self._url = url - self._errors = errors - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) + self._event_type : EventType = kwargs['pipelinerun_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'status' in kwargs and 'url' in kwargs and 'errors' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._status :str = kwargs['status'] + self._url :str = kwargs['url'] + self._errors :str = kwargs['errors'] + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + + elif 'extensions' in kwargs: + self._id = kwargs['extensions'].get('pipelinerunid') + self._name = kwargs['extensions'].get('pipelinerunname') + self._status = kwargs['extensions'].get('pipelinerunstatus') + self._url = kwargs['extensions'].get('pipelinerunurl') + self._errors = kwargs['extensions'].get('pipelinerunerrors') + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) def create_extensions(self) -> dict: """Create extensions. @@ -37,27 +43,27 @@ def create_extensions(self) -> dict: class PipelinerunStartedEvent(PipelinerunEvent): - def __init__(self, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = PipelinerunType.PipelineRunStartedEventV1 + self._event_type: str = EventType.PipelineRunStartedEventV1 - super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, data=data) + super().__init__(pipelinerun_type=self._event_type, **kwargs) class PipelinerunFinishedEvent(PipelinerunEvent): - def __init__(self, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = PipelinerunType.PipelineRunFinishedEventV1 + self._event_type: str = EventType.PipelineRunFinishedEventV1 - super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, data=data) + super().__init__(pipelinerun_type=self._event_type, **kwargs) class PipelinerunQueuedEvent(PipelinerunEvent): - def __init__(self, id: str, name: str, status: str, url: str, errors: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = PipelinerunType.PipelineRunQueuedEventV1 + self._event_type: str = EventType.PipelineRunQueuedEventV1 - super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, data=data) + super().__init__(pipelinerun_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/repository.py b/core/cdevents/core/repository.py index 51cbc50..fb654e6 100644 --- a/core/cdevents/core/repository.py +++ b/core/cdevents/core/repository.py @@ -1,26 +1,30 @@ """repository""" -from enum import Enum from cdevents.core.event import Event - -class RepositoryType(Enum): - RepositoryCreatedEventV1 :str = "cd.repository.created.v1" - RepositoryModifiedEventV1 :str = "cd.repository.modified.v1" - RepositoryDeletedEventV1 :str = "cd.repository.deleted.v1" - +from cdevents.core.event_type import EventType class RepositoryEvent(Event): """Repository Event.""" - def __init__(self, repository_type: RepositoryType, id: str, name: str, url: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = repository_type - self._id = id - self._name = name - self._url = url - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) + self._event_type :EventType = kwargs['repository_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'url' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._url :str = kwargs['url'] + elif 'extensions' in kwargs: + self._id = kwargs['extensions']['repositoryid'] + self._name = kwargs['extensions']['repositoryname'] + self._url = kwargs['extensions']['repositoryurl'] + + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + def create_extensions(self) -> dict: """Create extensions. """ @@ -33,28 +37,28 @@ def create_extensions(self) -> dict: class RepositoryCreatedEvent(RepositoryEvent): - def __init__(self, id: str, name: str, url: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = RepositoryType.RepositoryCreatedEventV1 + self._event_type: str = EventType.RepositoryCreatedEventV1 - super().__init__(repository_type=self._event_type, id=id, name=name, url=url, data=data) + super().__init__(repository_type=self._event_type, **kwargs) class RepositoryModifiedEvent(RepositoryEvent): - def __init__(self, id: str, name: str, url: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = RepositoryType.RepositoryModifiedEventV1 + self._event_type: str = EventType.RepositoryModifiedEventV1 - super().__init__(repository_type=self._event_type, id=id, name=name, url=url, data=data) + super().__init__(repository_type=self._event_type, **kwargs) class RepositoryDeletedEvent(RepositoryEvent): - def __init__(self, id: str, name: str, url: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = RepositoryType.RepositoryDeletedEventV1 + self._event_type: str = EventType.RepositoryDeletedEventV1 - super().__init__(repository_type=self._event_type, id=id, name=name, url=url, data=data) + super().__init__(repository_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/service.py b/core/cdevents/core/service.py index b294ff4..d5b57fa 100644 --- a/core/cdevents/core/service.py +++ b/core/cdevents/core/service.py @@ -1,26 +1,29 @@ """service""" -from enum import Enum from cdevents.core.event import Event - -class ServiceType(Enum): - ServiceDeployedEventV1 :str = "cd.service.deployed.v1" - ServiceUpgradedEventV1 :str = "cd.service.upgraded.v1" - ServiceRolledbackEventV1 :str = "cd.service.rolledback.v1" - ServiceRemovedEventV1 :str = "cd.service.removed.v1" - +from cdevents.core.event_type import EventType class ServiceEvent(Event): """Service Event.""" - def __init__(self, service_type: ServiceType, envid: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = service_type - self._envid = envid - self._name = name - self._version = version - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) + self._event_type :EventType = kwargs['service_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'envid' in kwargs and 'name' in kwargs and 'version' in kwargs: + self._envid :str = kwargs['envid'] + self._name :str = kwargs['name'] + self._version :str = kwargs['version'] + + elif 'extensions' in kwargs: + self._envid = kwargs['extensions']['serviceenvid'] + self._name = kwargs['extensions']['servicename'] + self._version = kwargs['extensions']['serviceversion'] + + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) def create_extensions(self) -> dict: """Create extensions. @@ -34,37 +37,37 @@ def create_extensions(self) -> dict: class ServiceDeployedEvent(ServiceEvent): - def __init__(self, envid: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = ServiceType.ServiceDeployedEventV1 + self._event_type: str = EventType.ServiceDeployedEventV1 - super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + super().__init__(service_type=self._event_type, **kwargs) class ServiceUpgradedEvent(ServiceEvent): - def __init__(self, envid: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = ServiceType.ServiceUpgradedEventV1 + self._event_type: str = EventType.ServiceUpgradedEventV1 - super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + super().__init__(service_type=self._event_type, **kwargs) class ServiceRolledbackEvent(ServiceEvent): - def __init__(self, envid: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = ServiceType.ServiceRolledbackEventV1 + self._event_type: str = EventType.ServiceRolledbackEventV1 - super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + super().__init__(service_type=self._event_type, **kwargs) class ServiceRemovedEvent(ServiceEvent): - def __init__(self, envid: str, name: str, version: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = ServiceType.ServiceRemovedEventV1 + self._event_type: str = EventType.ServiceRemovedEventV1 - super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, data=data) + super().__init__(service_type=self._event_type, **kwargs) diff --git a/core/cdevents/core/taskrun.py b/core/cdevents/core/taskrun.py index 92594db..9b90518 100644 --- a/core/cdevents/core/taskrun.py +++ b/core/cdevents/core/taskrun.py @@ -1,25 +1,30 @@ """taskrun""" -from enum import Enum from cdevents.core.event import Event - -class TaskRunType(Enum): - TaskRunStartedEventV1 :str = "cd.taskrun.started.v1" - TaskRunFinishedEventV1 :str = "cd.taskrun.finished.v1" - +from cdevents.core.event_type import EventType class TaskRunEvent(Event): """Taskrun Event.""" - def __init__(self, taskrun_type: TaskRunType, id: str, name: str, pipelineid: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type = taskrun_type - self._id= id - self._name = name - self._pipelineid = pipelineid - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=data) - + self._event_type :EventType = kwargs['taskrun_type'] + if 'data' in kwargs: + self._data :dict = kwargs['data'] + + if 'id' in kwargs and 'name' in kwargs and 'pipelineid' in kwargs: + self._id :str = kwargs['id'] + self._name :str = kwargs['name'] + self._pipelineid :str = kwargs['pipelineid'] + + elif 'extensions' in kwargs: + self._id = kwargs['extensions']['taskrunid'] + self._name = kwargs['extensions']['taskrunname'] + self._pipelineid = kwargs['extensions']['taskrunpipelineid'] + + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + def create_extensions(self) -> dict: """Create extensions. """ @@ -32,18 +37,18 @@ def create_extensions(self) -> dict: class TaskRunStartedEvent(TaskRunEvent): - def __init__(self, id: str, name: str, pipelineid: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = TaskRunType.TaskRunStartedEventV1 + self._event_type: str = EventType.TaskRunStartedEventV1 - super().__init__(taskrun_type=self._event_type, id=id, name=name, pipelineid=pipelineid, data=data) + super().__init__(taskrun_type=self._event_type, **kwargs) class TaskRunFinishedEvent(TaskRunEvent): - def __init__(self, id: str, name: str, pipelineid: str, data: dict = {}): + def __init__(self, **kwargs): """Initializes class. """ - self._event_type: str = TaskRunType.TaskRunFinishedEventV1 + self._event_type: str = EventType.TaskRunFinishedEventV1 - super().__init__(taskrun_type=self._event_type, id=id, name=name, pipelineid=pipelineid, data=data) + super().__init__(taskrun_type=self._event_type, **kwargs) diff --git a/core/tests/test_artifact.py b/core/tests/test_artifact.py index d936e30..60fadff 100644 --- a/core/tests/test_artifact.py +++ b/core/tests/test_artifact.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.artifact import ArtifactEvent, ArtifactType, ArtifactPackagedEvent, ArtifactPublishedEvent +from cdevents.core.event_type import EventType +from cdevents.core.artifact import ArtifactEvent, ArtifactPackagedEvent, ArtifactPublishedEvent @pytest.mark.unit def test_artifact_created(): - artifact_event = ArtifactEvent(artifact_type=ArtifactType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) + artifact_event = ArtifactEvent(artifact_type=EventType.ArtifactPackagedEventV1, id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None - assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value + assert artifact_event._attributes["type"] == EventType.ArtifactPackagedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} assert artifact_event.data == {"key1": "value1"} @@ -14,7 +15,7 @@ def test_artifact_created(): def test_artifact_type_packaged_v1(): artifact_event = ArtifactPackagedEvent(id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None - assert artifact_event._attributes["type"] == ArtifactType.ArtifactPackagedEventV1.value + assert artifact_event._attributes["type"] == EventType.ArtifactPackagedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} assert artifact_event.data == {"key1": "value1"} @@ -22,7 +23,7 @@ def test_artifact_type_packaged_v1(): def test_artifact_type_published_v1(): artifact_event = ArtifactPublishedEvent(id="_id", name="_name", version="_version",data={"key1": "value1"}) assert artifact_event is not None - assert artifact_event._attributes["type"] == ArtifactType.ArtifactPublishedEventV1.value + assert artifact_event._attributes["type"] == EventType.ArtifactPublishedEventV1.value assert artifact_event._attributes["extensions"] == {"artifactid": "_id", "artifactname": "_name", "artifactversion": "_version"} assert artifact_event.data == {"key1": "value1"} diff --git a/core/tests/test_branch.py b/core/tests/test_branch.py index c81e851..c90313a 100644 --- a/core/tests/test_branch.py +++ b/core/tests/test_branch.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.branch import BranchEvent, BranchType, BranchCreatedEvent, BranchDeletedEvent +from cdevents.core.event_type import EventType +from cdevents.core.branch import BranchEvent, BranchCreatedEvent, BranchDeletedEvent @pytest.mark.unit def test_branch_created(): - branch_event = BranchEvent(branch_type=BranchType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) + branch_event = BranchEvent(branch_type=EventType.BranchCreatedEventV1, id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None - assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value + assert branch_event._attributes["type"] == EventType.BranchCreatedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} assert branch_event.data == {"key1": "value1"} @@ -14,7 +15,7 @@ def test_branch_created(): def test_branch_type_created_v1(): branch_event = BranchCreatedEvent(id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None - assert branch_event._attributes["type"] == BranchType.BranchCreatedEventV1.value + assert branch_event._attributes["type"] == EventType.BranchCreatedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} assert branch_event.data == {"key1": "value1"} @@ -22,6 +23,6 @@ def test_branch_type_created_v1(): def test_branch_type_deleted_v1(): branch_event = BranchDeletedEvent(id="_id", name="_name", repoid="_repoid", data={"key1": "value1"}) assert branch_event is not None - assert branch_event._attributes["type"] == BranchType.BranchDeletedEventV1.value + assert branch_event._attributes["type"] == EventType.BranchDeletedEventV1.value assert branch_event._attributes["extensions"] == {"branchid": "_id", "branchname": "_name", "branchrepositoryid": "_repoid"} assert branch_event.data == {"key1": "value1"} \ No newline at end of file diff --git a/core/tests/test_build.py b/core/tests/test_build.py index 2b23b0f..0b4415c 100644 --- a/core/tests/test_build.py +++ b/core/tests/test_build.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.build import BuildEvent, BuildType, BuildStartedEvent, BuildQueuedEvent, BuildFinishedEvent +from cdevents.core.event_type import EventType +from cdevents.core.build import BuildEvent, BuildStartedEvent, BuildQueuedEvent, BuildFinishedEvent @pytest.mark.unit def test_build_created(): - build_event = BuildEvent(build_type=BuildType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) + build_event = BuildEvent(build_type=EventType.BuildStartedEventV1, id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None - assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value + assert build_event._attributes["type"] == EventType.BuildStartedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} assert build_event.data == {"key1": "value1"} @@ -14,7 +15,7 @@ def test_build_created(): def test_build_type_started_v1(): build_event = BuildStartedEvent(id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None - assert build_event._attributes["type"] == BuildType.BuildStartedEventV1.value + assert build_event._attributes["type"] == EventType.BuildStartedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} assert build_event.data == {"key1": "value1"} @@ -22,7 +23,7 @@ def test_build_type_started_v1(): def test_build_type_queued_v1(): build_event = BuildQueuedEvent(id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None - assert build_event._attributes["type"] == BuildType.BuildQueuedEventV1.value + assert build_event._attributes["type"] == EventType.BuildQueuedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} assert build_event.data == {"key1": "value1"} @@ -30,6 +31,6 @@ def test_build_type_queued_v1(): def test_build_type_finished_v1(): build_event = BuildFinishedEvent(id="_id", name="_name", artifact="_artifact", data={"key1": "value1"}) assert build_event is not None - assert build_event._attributes["type"] == BuildType.BuildFinishedEventV1.value + assert build_event._attributes["type"] == EventType.BuildFinishedEventV1.value assert build_event._attributes["extensions"] == {"buildid": "_id", "buildname": "_name", "buildartifactid": "_artifact"} assert build_event.data == {"key1": "value1"} diff --git a/core/tests/test_environment.py b/core/tests/test_environment.py index ebec2fd..bb73e93 100644 --- a/core/tests/test_environment.py +++ b/core/tests/test_environment.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.env import EnvEvent, EnvType, EnvEventCreatedEvent, EnvEventModifiedEvent, EnvEventDeletedEvent +from cdevents.core.env import EnvEvent, EnvEventCreatedEvent, EnvEventModifiedEvent, EnvEventDeletedEvent +from cdevents.core.event_type import EventType @pytest.mark.unit def test_environment_created(): - env_event = EnvEvent(env_type=EnvType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) + env_event = EnvEvent(env_type=EventType.EnvironmentCreatedEventV1, id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None - assert env_event._attributes["type"] == EnvType.EnvironmentCreatedEventV1.value + assert env_event._attributes["type"] == EventType.EnvironmentCreatedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} assert env_event.data == {"key1": "value1"} @@ -15,7 +16,7 @@ def test_environment_created(): def test_environment_type_created_v1(): env_event = EnvEventCreatedEvent(id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None - assert env_event._attributes["type"] == EnvType.EnvironmentCreatedEventV1.value + assert env_event._attributes["type"] == EventType.EnvironmentCreatedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} assert env_event.data == {"key1": "value1"} @@ -24,7 +25,7 @@ def test_environment_type_created_v1(): def test_environment_type_modified_v1(): env_event = EnvEventModifiedEvent(id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None - assert env_event._attributes["type"] == EnvType.EnvironmentModifiedEventV1.value + assert env_event._attributes["type"] == EventType.EnvironmentModifiedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} assert env_event.data == {"key1": "value1"} @@ -32,6 +33,6 @@ def test_environment_type_modified_v1(): def test_environment_type_deleted_v1(): env_event = EnvEventDeletedEvent(id="_id", name="_name", repo="_repo", data={"key1": "value1"}) assert env_event is not None - assert env_event._attributes["type"] == EnvType.EnvironmentDeletedEventV1.value + assert env_event._attributes["type"] == EventType.EnvironmentDeletedEventV1.value assert env_event._attributes["extensions"] == {"envId": "_id", "envname": "_name", "envrepourl": "_repo"} assert env_event.data == {"key1": "value1"} \ No newline at end of file diff --git a/core/tests/test_pipelinerun.py b/core/tests/test_pipelinerun.py index f7f4a9d..54eb8a1 100644 --- a/core/tests/test_pipelinerun.py +++ b/core/tests/test_pipelinerun.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunType, PipelinerunStartedEvent, PipelinerunFinishedEvent, PipelinerunQueuedEvent +from cdevents.core.pipelinerun import PipelinerunEvent, PipelinerunStartedEvent, PipelinerunFinishedEvent, PipelinerunQueuedEvent +from cdevents.core.event_type import EventType @pytest.mark.unit def test_pipelinerun_created(): - pipelinerun_event = PipelinerunEvent(pipelinerun_type=PipelinerunType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) + pipelinerun_event = PipelinerunEvent(pipelinerun_type=EventType.PipelineRunStartedEventV1, id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None - assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value + assert pipelinerun_event._attributes["type"] == EventType.PipelineRunStartedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} assert pipelinerun_event.data == {"key1": "value1"} @@ -14,7 +15,7 @@ def test_pipelinerun_created(): def test_pipelinerun_type_started_v1(): pipelinerun_event = PipelinerunStartedEvent(id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None - assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunStartedEventV1.value + assert pipelinerun_event._attributes["type"] == EventType.PipelineRunStartedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} assert pipelinerun_event.data == {"key1": "value1"} @@ -22,7 +23,7 @@ def test_pipelinerun_type_started_v1(): def test_pipelinerun_type_finished_v1(): pipelinerun_event = PipelinerunFinishedEvent( id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None - assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunFinishedEventV1.value + assert pipelinerun_event._attributes["type"] == EventType.PipelineRunFinishedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} assert pipelinerun_event.data == {"key1": "value1"} @@ -30,6 +31,6 @@ def test_pipelinerun_type_finished_v1(): def test_pipelinerun_type_queued_v1(): pipelinerun_event = PipelinerunQueuedEvent(id="_id", name="_name", status="_status", url="_url", errors="_errors", data={"key1": "value1"}) assert pipelinerun_event is not None - assert pipelinerun_event._attributes["type"] == PipelinerunType.PipelineRunQueuedEventV1.value + assert pipelinerun_event._attributes["type"] == EventType.PipelineRunQueuedEventV1.value assert pipelinerun_event._attributes["extensions"] == {"pipelinerunid": "_id", "pipelinerunname": "_name", "pipelinerunstatus": "_status", "pipelinerunurl": "_url", "pipelinerunerrors": "_errors"} assert pipelinerun_event.data == {"key1": "value1"} diff --git a/core/tests/test_repository.py b/core/tests/test_repository.py index 153efc7..d8597ee 100644 --- a/core/tests/test_repository.py +++ b/core/tests/test_repository.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.repository import RepositoryEvent, RepositoryType, RepositoryCreatedEvent, RepositoryModifiedEvent, RepositoryDeletedEvent +from cdevents.core.repository import RepositoryEvent, RepositoryCreatedEvent, RepositoryModifiedEvent, RepositoryDeletedEvent +from cdevents.core.event_type import EventType @pytest.mark.unit def test_repository_created(): - repository_event = RepositoryEvent(repository_type=RepositoryType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) + repository_event = RepositoryEvent(repository_type=EventType.RepositoryCreatedEventV1, id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None - assert repository_event._attributes["type"] == RepositoryType.RepositoryCreatedEventV1.value + assert repository_event._attributes["type"] == EventType.RepositoryCreatedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} assert repository_event.data == {"key1": "value1"} @@ -14,7 +15,7 @@ def test_repository_created(): def test_repository_type_created_v1(): repository_event = RepositoryCreatedEvent(id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None - assert repository_event._attributes["type"] == RepositoryType.RepositoryCreatedEventV1.value + assert repository_event._attributes["type"] == EventType.RepositoryCreatedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} assert repository_event.data == {"key1": "value1"} @@ -22,7 +23,7 @@ def test_repository_type_created_v1(): def test_repository_type_modified_v1(): repository_event = RepositoryModifiedEvent(id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None - assert repository_event._attributes["type"] == RepositoryType.RepositoryModifiedEventV1.value + assert repository_event._attributes["type"] == EventType.RepositoryModifiedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} assert repository_event.data == {"key1": "value1"} @@ -30,7 +31,7 @@ def test_repository_type_modified_v1(): def test_repository_type_deleted_v1(): repository_event = RepositoryDeletedEvent(id="_id", name="_name", url="_url", data={"key1": "value1"}) assert repository_event is not None - assert repository_event._attributes["type"] == RepositoryType.RepositoryDeletedEventV1.value + assert repository_event._attributes["type"] == EventType.RepositoryDeletedEventV1.value assert repository_event._attributes["extensions"] == {"repositoryid": "_id", "repositoryname": "_name", "repositoryurl": "_url"} assert repository_event.data == {"key1": "value1"} diff --git a/core/tests/test_service.py b/core/tests/test_service.py index 3c71086..7830f34 100644 --- a/core/tests/test_service.py +++ b/core/tests/test_service.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.service import ServiceEvent, ServiceType, ServiceDeployedEvent, ServiceUpgradedEvent, ServiceRolledbackEvent, ServiceRemovedEvent +from cdevents.core.service import ServiceEvent, ServiceDeployedEvent, ServiceUpgradedEvent, ServiceRolledbackEvent, ServiceRemovedEvent +from cdevents.core.event_type import EventType @pytest.mark.unit def test_service_created(): - service_event = ServiceEvent(service_type=ServiceType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) + service_event = ServiceEvent(service_type=EventType.ServiceDeployedEventV1, envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None - assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value + assert service_event._attributes["type"] == EventType.ServiceDeployedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} assert service_event.data == {"key1": "value1"} @@ -15,7 +16,7 @@ def test_service_created(): def test_service_type_deployed_v1(): service_event = ServiceDeployedEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None - assert service_event._attributes["type"] == ServiceType.ServiceDeployedEventV1.value + assert service_event._attributes["type"] == EventType.ServiceDeployedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} assert service_event.data == {"key1": "value1"} @@ -24,7 +25,7 @@ def test_service_type_deployed_v1(): def test_service_type_upgraded_v1(): service_event = ServiceUpgradedEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None - assert service_event._attributes["type"] == ServiceType.ServiceUpgradedEventV1.value + assert service_event._attributes["type"] == EventType.ServiceUpgradedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} assert service_event.data == {"key1": "value1"} @@ -33,7 +34,7 @@ def test_service_type_upgraded_v1(): def test_service_type_rolledback_v1(): service_event = ServiceRolledbackEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None - assert service_event._attributes["type"] == ServiceType.ServiceRolledbackEventV1.value + assert service_event._attributes["type"] == EventType.ServiceRolledbackEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} assert service_event.data == {"key1": "value1"} @@ -42,7 +43,7 @@ def test_service_type_rolledback_v1(): def test_service_type_removed_v1(): service_event = ServiceRemovedEvent(envid="_envid", name="_name", version="_version", data={"key1": "value1"}) assert service_event is not None - assert service_event._attributes["type"] == ServiceType.ServiceRemovedEventV1.value + assert service_event._attributes["type"] == EventType.ServiceRemovedEventV1.value assert service_event._attributes["extensions"] == {"serviceenvid": "_envid", "servicename": "_name", "serviceversion": "_version"} assert service_event.data == {"key1": "value1"} diff --git a/core/tests/test_taskrun.py b/core/tests/test_taskrun.py index 76171d6..7059261 100644 --- a/core/tests/test_taskrun.py +++ b/core/tests/test_taskrun.py @@ -1,12 +1,13 @@ import pytest -from cdevents.core.taskrun import TaskRunEvent, TaskRunType, TaskRunStartedEvent, TaskRunFinishedEvent +from cdevents.core.taskrun import TaskRunEvent, TaskRunStartedEvent, TaskRunFinishedEvent +from cdevents.core.event_type import EventType @pytest.mark.unit def test_taskrun_created(): - taskrun_event = TaskRunEvent(taskrun_type=TaskRunType.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) + taskrun_event = TaskRunEvent(taskrun_type=EventType.TaskRunStartedEventV1, id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None - assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value + assert taskrun_event._attributes["type"] == EventType.TaskRunStartedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} assert taskrun_event.data == {"key1": "value1"} @@ -15,7 +16,7 @@ def test_taskrun_created(): def test_taskrun_type_started_v1(): taskrun_event = TaskRunStartedEvent(id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None - assert taskrun_event._attributes["type"] == TaskRunType.TaskRunStartedEventV1.value + assert taskrun_event._attributes["type"] == EventType.TaskRunStartedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} assert taskrun_event.data == {"key1": "value1"} @@ -24,6 +25,6 @@ def test_taskrun_type_started_v1(): def test_taskrun_type_finished_v1(): taskrun_event = TaskRunFinishedEvent(id="_id", name="_name", pipelineid="_pipelineid", data={"key1": "value1"}) assert taskrun_event is not None - assert taskrun_event._attributes["type"] == TaskRunType.TaskRunFinishedEventV1.value + assert taskrun_event._attributes["type"] == EventType.TaskRunFinishedEventV1.value assert taskrun_event._attributes["extensions"] == {"taskrunid": "_id", "taskrunname": "_name", "taskrunpipelineid": "_pipelineid"} assert taskrun_event.data == {"key1": "value1"} diff --git a/receiver/cdevents/api/app.py b/receiver/cdevents/api/app.py new file mode 100644 index 0000000..afad282 --- /dev/null +++ b/receiver/cdevents/api/app.py @@ -0,0 +1,25 @@ +from flask import Flask, request + +from cdevents.core.http_handlar import HttpHandlar + +app = Flask(__name__) + + +# create an endpoint at http://localhost:/8080/ +@app.route("/", methods=["POST"]) +def home(): + # create a CloudEvent + event = HttpHandlar.event_from_http(headers=request.headers, data=request.get_data()) + + # you can access cloudevent fields as seen below + print( + f"Found {event['id']} from {event['source']} with type " + f"{event['type']} and specversion {event['specversion']}" + ) + print() + print(event) + return "", 204 + + +if __name__ == "__main__": + app.run(port=8080) \ No newline at end of file From b90f0fd8690d49e0fda9c66cbec630972adafeee Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Mon, 22 Aug 2022 12:49:59 +0200 Subject: [PATCH 33/34] update http_handlar --- core/cdevents/core/http_handlar.py | 43 +++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/core/cdevents/core/http_handlar.py b/core/cdevents/core/http_handlar.py index 753eb07..fae4c63 100644 --- a/core/cdevents/core/http_handlar.py +++ b/core/cdevents/core/http_handlar.py @@ -14,7 +14,13 @@ from cdevents.core.event_type import EventType from cdevents.core.artifact import ArtifactPackagedEvent, ArtifactPublishedEvent +from cdevents.core.branch import BranchCreatedEvent, BranchDeletedEvent from cdevents.core.build import BuildStartedEvent, BuildFinishedEvent, BuildQueuedEvent +from cdevents.core.env import EnvEventCreatedEvent, EnvEventModifiedEvent, EnvEventDeletedEvent +from cdevents.core.pipelinerun import PipelinerunStartedEvent, PipelinerunFinishedEvent, PipelinerunQueuedEvent +from cdevents.core.repository import RepositoryCreatedEvent, RepositoryModifiedEvent, RepositoryDeletedEvent +from cdevents.core.service import ServiceDeployedEvent, ServiceUpgradedEvent, ServiceRolledbackEvent, ServiceRemovedEvent +from cdevents.core.taskrun import TaskRunStartedEvent, TaskRunFinishedEvent class HttpHandlar(): """Http Handlar.""" @@ -110,12 +116,43 @@ def event_from_http(headers: typing.Dict[str, str], return ArtifactPackagedEvent(attrs=attrs, extensions=extensions, data=event_data) elif etype.value == EventType.ArtifactPublishedEventV1.value: return ArtifactPublishedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.BranchCreatedEventV1.value: + return BranchCreatedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.BranchDeletedEventV1.value: + return BranchDeletedEvent(attrs=attrs, extensions=extensions, data=event_data) elif etype.value == EventType.BuildStartedEventV1.value: return BuildStartedEvent(attrs=attrs, extensions=extensions, data=event_data) elif etype.value == EventType.BuildQueuedEventV1.value: return BuildQueuedEvent(attrs=attrs, extensions=extensions, data=event_data) elif etype.value == EventType.BuildFinishedEventV1.value: return BuildFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) - - # e = BuildStartedEvent.create_from_event(event) - # return e \ No newline at end of file + elif etype.value == EventType.EnvironmentCreatedEventV1.value: + return EnvEventCreatedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.EnvironmentModifiedEventV1.value: + return EnvEventModifiedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.EnvironmentDeletedEventV1.value: + return EnvEventDeletedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.PipelineRunStartedEventV1.value: + return PipelinerunStartedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.PipelineRunFinishedEventV1.value: + return PipelinerunFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.PipelineRunQueuedEventV1.value: + return PipelinerunQueuedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.RepositoryCreatedEventV1.value: + return RepositoryCreatedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.RepositoryModifiedEventV1.value: + return RepositoryModifiedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.RepositoryDeletedEventV1.value: + return RepositoryDeletedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.ServiceDeployedEventV1.value: + return ServiceDeployedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.ServiceUpgradedEventV1.value: + return ServiceUpgradedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.ServiceRolledbackEventV1.value: + return ServiceRolledbackEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.ServiceRemovedEventV1.value: + return ServiceRemovedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.TaskRunStartedEventV1.value: + return TaskRunStartedEvent(attrs=attrs, extensions=extensions, data=event_data) + elif etype.value == EventType.TaskRunFinishedEventV1.value: + return TaskRunFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) From d2b0ea45820a00275c96b9cff134765813b51bce Mon Sep 17 00:00:00 2001 From: tarekbadrshalaan Date: Mon, 22 Aug 2022 16:09:08 +0200 Subject: [PATCH 34/34] Update creating http object --- core/cdevents/core/artifact.py | 31 ++++++++------------ core/cdevents/core/branch.py | 30 +++++++------------- core/cdevents/core/build.py | 34 ++++++++-------------- core/cdevents/core/env.py | 35 ++++++++--------------- core/cdevents/core/http_handlar.py | 45 +++++++++++++++--------------- core/cdevents/core/pipelinerun.py | 42 ++++++++++------------------ core/cdevents/core/repository.py | 34 ++++++++-------------- core/cdevents/core/service.py | 40 ++++++++++---------------- core/cdevents/core/taskrun.py | 30 +++++++------------- 9 files changed, 119 insertions(+), 202 deletions(-) diff --git a/core/cdevents/core/artifact.py b/core/cdevents/core/artifact.py index 256d9cd..554b1cb 100644 --- a/core/cdevents/core/artifact.py +++ b/core/cdevents/core/artifact.py @@ -6,24 +6,14 @@ class ArtifactEvent(Event): """Artifact Event.""" - def __init__(self, **kwargs): + def __init__(self, artifact_type: EventType, id: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type : EventType = kwargs['artifact_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'version' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._version :str = kwargs['version'] - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) - - elif 'extensions' in kwargs: - self._id = kwargs['extensions'].get('artifactid') - self._name = kwargs['extensions'].get('artifactname') - self._version = kwargs['extensions'].get('artifactversion') - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + self._event_type = artifact_type + self._id = id + self._name = name + self._version = version + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -37,18 +27,19 @@ def create_extensions(self) -> dict: class ArtifactPackagedEvent(ArtifactEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.ArtifactPackagedEventV1 - super().__init__(artifact_type=self._event_type, **kwargs) + super().__init__(artifact_type=self._event_type, id=id, name=name, version=version, attrs=attrs, data=data) + class ArtifactPublishedEvent(ArtifactEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.ArtifactPublishedEventV1 - super().__init__(artifact_type=self._event_type, **kwargs) + super().__init__(artifact_type=self._event_type, id=id, name=name, version=version, attrs=attrs, data=data) diff --git a/core/cdevents/core/branch.py b/core/cdevents/core/branch.py index f02aca8..f8d3b41 100644 --- a/core/cdevents/core/branch.py +++ b/core/cdevents/core/branch.py @@ -6,24 +6,14 @@ class BranchEvent(Event): """Branch Event.""" - def __init__(self, **kwargs): + def __init__(self, branch_type: EventType, id: str=None, name: str=None, repoid: str=None, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type : EventType = kwargs['branch_type'] - - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'repoid' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._repoid :str = kwargs['repoid'] - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) - elif 'extensions' in kwargs: - self._id = kwargs['extensions'].get('branchid') - self._name = kwargs['extensions'].get('branchname') - self._repoid = kwargs['extensions'].get('branchrepositoryid') - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + self._event_type = branch_type + self._id = id + self._name = name + self._repoid = repoid + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -37,18 +27,18 @@ def create_extensions(self) -> dict: class BranchCreatedEvent(BranchEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, repoid: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.BranchCreatedEventV1 - super().__init__(branch_type=self._event_type, **kwargs) + super().__init__(branch_type=self._event_type, id=id, name=name, repoid=repoid, attrs=attrs, data=data) class BranchDeletedEvent(BranchEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, repoid: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.BranchDeletedEventV1 - super().__init__(branch_type=self._event_type, **kwargs) + super().__init__(branch_type=self._event_type, id=id, name=name, repoid=repoid, attrs=attrs, data=data) diff --git a/core/cdevents/core/build.py b/core/cdevents/core/build.py index c700983..0746c33 100644 --- a/core/cdevents/core/build.py +++ b/core/cdevents/core/build.py @@ -6,24 +6,14 @@ class BuildEvent(Event): """Build Event.""" - def __init__(self, **kwargs): + def __init__(self, build_type: EventType, id: str=None, name: str=None, artifact: str=None, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type : EventType = kwargs['build_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'artifact' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._artifact :str = kwargs['artifact'] - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) - - elif 'extensions' in kwargs: - self._id = kwargs['extensions'].get('buildid'), - self._name = kwargs['extensions'].get('buildname') - self._artifact = kwargs['extensions'].get('buildartifactid') - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=kwargs['attrs'], data=self._data) + self._event_type = build_type + self._id = id + self._name = name + self._artifact = artifact + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -37,27 +27,27 @@ def create_extensions(self) -> dict: class BuildStartedEvent(BuildEvent): """Build Started Event.""" - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, artifact: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.BuildStartedEventV1 - super().__init__(build_type=self._event_type, **kwargs) + super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, attrs=attrs, data=data) class BuildQueuedEvent(BuildEvent): """Build Queued Event.""" - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, artifact: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.BuildQueuedEventV1 - super().__init__(build_type=self._event_type, **kwargs) + super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, attrs=attrs, data=data) class BuildFinishedEvent(BuildEvent): """Build Finished Event.""" - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, artifact: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.BuildFinishedEventV1 - super().__init__(build_type=self._event_type, **kwargs) + super().__init__(build_type=self._event_type, id=id, name=name, artifact=artifact, attrs=attrs, data=data) diff --git a/core/cdevents/core/env.py b/core/cdevents/core/env.py index 29db00f..d013dd4 100644 --- a/core/cdevents/core/env.py +++ b/core/cdevents/core/env.py @@ -6,24 +6,14 @@ class EnvEvent(Event): """Env Event.""" - def __init__(self, **kwargs): + def __init__(self, env_type: EventType, id: str, name: str, repo: str, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type : EventType = kwargs['env_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'repo' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._repo :str = kwargs['repo'] - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) - - elif 'extensions' in kwargs: - self._id = kwargs['extensions'].get('envId') - self._name = kwargs['extensions'].get('envname') - self._repo = kwargs['extensions'].get('envrepourl') - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + self._event_type = env_type + self._id = id + self._name = name + self._repo = repo + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -37,29 +27,28 @@ def create_extensions(self) -> dict: class EnvEventCreatedEvent(EnvEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, repo: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.EnvironmentCreatedEventV1 - super().__init__(env_type=self._event_type, **kwargs) + super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, attrs=attrs, data=data) class EnvEventModifiedEvent(EnvEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, repo: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.EnvironmentModifiedEventV1 - super().__init__(env_type=self._event_type, **kwargs) - + super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, attrs=attrs, data=data) class EnvEventDeletedEvent(EnvEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, repo: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.EnvironmentDeletedEventV1 - super().__init__(env_type=self._event_type, **kwargs) + super().__init__(env_type=self._event_type, id=id, name=name, repo=repo, attrs=attrs, data=data) diff --git a/core/cdevents/core/http_handlar.py b/core/cdevents/core/http_handlar.py index fae4c63..3e9351c 100644 --- a/core/cdevents/core/http_handlar.py +++ b/core/cdevents/core/http_handlar.py @@ -105,7 +105,6 @@ def event_from_http(headers: typing.Dict[str, str], attrs = HttpHandlar.get_attrs(headers, data, data_unmarshaller) event_data=attrs.pop("data", None) - extensions=attrs.pop("extensions", None) etype = EventType(attrs.get("type")) if etype.value == "" or etype.value is None: @@ -113,46 +112,46 @@ def event_from_http(headers: typing.Dict[str, str], "Failed to find type in HTTP request" ) elif etype.value == EventType.ArtifactPackagedEventV1.value: - return ArtifactPackagedEvent(attrs=attrs, extensions=extensions, data=event_data) + return ArtifactPackagedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.ArtifactPublishedEventV1.value: - return ArtifactPublishedEvent(attrs=attrs, extensions=extensions, data=event_data) + return ArtifactPublishedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.BranchCreatedEventV1.value: - return BranchCreatedEvent(attrs=attrs, extensions=extensions, data=event_data) + return BranchCreatedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.BranchDeletedEventV1.value: - return BranchDeletedEvent(attrs=attrs, extensions=extensions, data=event_data) + return BranchDeletedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.BuildStartedEventV1.value: - return BuildStartedEvent(attrs=attrs, extensions=extensions, data=event_data) + return BuildStartedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.BuildQueuedEventV1.value: - return BuildQueuedEvent(attrs=attrs, extensions=extensions, data=event_data) + return BuildQueuedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.BuildFinishedEventV1.value: - return BuildFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) + return BuildFinishedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.EnvironmentCreatedEventV1.value: - return EnvEventCreatedEvent(attrs=attrs, extensions=extensions, data=event_data) + return EnvEventCreatedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.EnvironmentModifiedEventV1.value: - return EnvEventModifiedEvent(attrs=attrs, extensions=extensions, data=event_data) + return EnvEventModifiedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.EnvironmentDeletedEventV1.value: - return EnvEventDeletedEvent(attrs=attrs, extensions=extensions, data=event_data) + return EnvEventDeletedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.PipelineRunStartedEventV1.value: - return PipelinerunStartedEvent(attrs=attrs, extensions=extensions, data=event_data) + return PipelinerunStartedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.PipelineRunFinishedEventV1.value: - return PipelinerunFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) + return PipelinerunFinishedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.PipelineRunQueuedEventV1.value: - return PipelinerunQueuedEvent(attrs=attrs, extensions=extensions, data=event_data) + return PipelinerunQueuedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.RepositoryCreatedEventV1.value: - return RepositoryCreatedEvent(attrs=attrs, extensions=extensions, data=event_data) + return RepositoryCreatedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.RepositoryModifiedEventV1.value: - return RepositoryModifiedEvent(attrs=attrs, extensions=extensions, data=event_data) + return RepositoryModifiedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.RepositoryDeletedEventV1.value: - return RepositoryDeletedEvent(attrs=attrs, extensions=extensions, data=event_data) + return RepositoryDeletedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.ServiceDeployedEventV1.value: - return ServiceDeployedEvent(attrs=attrs, extensions=extensions, data=event_data) + return ServiceDeployedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.ServiceUpgradedEventV1.value: - return ServiceUpgradedEvent(attrs=attrs, extensions=extensions, data=event_data) + return ServiceUpgradedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.ServiceRolledbackEventV1.value: - return ServiceRolledbackEvent(attrs=attrs, extensions=extensions, data=event_data) + return ServiceRolledbackEvent(attrs=attrs, data=event_data) elif etype.value == EventType.ServiceRemovedEventV1.value: - return ServiceRemovedEvent(attrs=attrs, extensions=extensions, data=event_data) + return ServiceRemovedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.TaskRunStartedEventV1.value: - return TaskRunStartedEvent(attrs=attrs, extensions=extensions, data=event_data) + return TaskRunStartedEvent(attrs=attrs, data=event_data) elif etype.value == EventType.TaskRunFinishedEventV1.value: - return TaskRunFinishedEvent(attrs=attrs, extensions=extensions, data=event_data) + return TaskRunFinishedEvent(attrs=attrs, data=event_data) diff --git a/core/cdevents/core/pipelinerun.py b/core/cdevents/core/pipelinerun.py index 3ae8a2f..def4f0a 100644 --- a/core/cdevents/core/pipelinerun.py +++ b/core/cdevents/core/pipelinerun.py @@ -6,28 +6,16 @@ class PipelinerunEvent(Event): """Pipelinerun Event.""" - def __init__(self, **kwargs): + def __init__(self, pipelinerun_type: EventType, id: str, name: str, status: str, url: str, errors: str, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type : EventType = kwargs['pipelinerun_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'status' in kwargs and 'url' in kwargs and 'errors' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._status :str = kwargs['status'] - self._url :str = kwargs['url'] - self._errors :str = kwargs['errors'] - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) - - elif 'extensions' in kwargs: - self._id = kwargs['extensions'].get('pipelinerunid') - self._name = kwargs['extensions'].get('pipelinerunname') - self._status = kwargs['extensions'].get('pipelinerunstatus') - self._url = kwargs['extensions'].get('pipelinerunurl') - self._errors = kwargs['extensions'].get('pipelinerunerrors') - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + self._event_type = pipelinerun_type + self._id = id + self._name = name + self._status = status + self._url = url + self._errors = errors + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -43,27 +31,27 @@ def create_extensions(self) -> dict: class PipelinerunStartedEvent(PipelinerunEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, status: str=None, url: str=None, errors: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.PipelineRunStartedEventV1 - super().__init__(pipelinerun_type=self._event_type, **kwargs) - + super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, attrs=attrs, data=data) + class PipelinerunFinishedEvent(PipelinerunEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, status: str=None, url: str=None, errors: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.PipelineRunFinishedEventV1 - super().__init__(pipelinerun_type=self._event_type, **kwargs) + super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, attrs=attrs, data=data) class PipelinerunQueuedEvent(PipelinerunEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, status: str=None, url: str=None, errors: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.PipelineRunQueuedEventV1 - super().__init__(pipelinerun_type=self._event_type, **kwargs) + super().__init__(pipelinerun_type=self._event_type, id=id, name=name, status=status, url=url, errors=errors, attrs=attrs, data=data) diff --git a/core/cdevents/core/repository.py b/core/cdevents/core/repository.py index fb654e6..4c44396 100644 --- a/core/cdevents/core/repository.py +++ b/core/cdevents/core/repository.py @@ -6,24 +6,14 @@ class RepositoryEvent(Event): """Repository Event.""" - def __init__(self, **kwargs): + def __init__(self, repository_type: EventType, id: str, name: str, url: str, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type :EventType = kwargs['repository_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'url' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._url :str = kwargs['url'] - - elif 'extensions' in kwargs: - self._id = kwargs['extensions']['repositoryid'] - self._name = kwargs['extensions']['repositoryname'] - self._url = kwargs['extensions']['repositoryurl'] - - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + self._event_type = repository_type + self._id = id + self._name = name + self._url = url + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -37,28 +27,28 @@ def create_extensions(self) -> dict: class RepositoryCreatedEvent(RepositoryEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, url: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.RepositoryCreatedEventV1 - super().__init__(repository_type=self._event_type, **kwargs) + super().__init__(repository_type=self._event_type, id=id, name=name, url=url, attrs=attrs, data=data) class RepositoryModifiedEvent(RepositoryEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, url: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.RepositoryModifiedEventV1 - super().__init__(repository_type=self._event_type, **kwargs) + super().__init__(repository_type=self._event_type, id=id, name=name, url=url, attrs=attrs, data=data) class RepositoryDeletedEvent(RepositoryEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, url: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.RepositoryDeletedEventV1 - super().__init__(repository_type=self._event_type, **kwargs) + super().__init__(repository_type=self._event_type, id=id, name=name, url=url, attrs=attrs, data=data) diff --git a/core/cdevents/core/service.py b/core/cdevents/core/service.py index d5b57fa..19a9e1d 100644 --- a/core/cdevents/core/service.py +++ b/core/cdevents/core/service.py @@ -6,25 +6,15 @@ class ServiceEvent(Event): """Service Event.""" - def __init__(self, **kwargs): + def __init__(self, service_type: EventType, envid: str, name: str, version: str, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type :EventType = kwargs['service_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'envid' in kwargs and 'name' in kwargs and 'version' in kwargs: - self._envid :str = kwargs['envid'] - self._name :str = kwargs['name'] - self._version :str = kwargs['version'] - - elif 'extensions' in kwargs: - self._envid = kwargs['extensions']['serviceenvid'] - self._name = kwargs['extensions']['servicename'] - self._version = kwargs['extensions']['serviceversion'] - - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) - + self._event_type = service_type + self._envid = envid + self._name = name + self._version = version + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) + def create_extensions(self) -> dict: """Create extensions. """ @@ -37,37 +27,37 @@ def create_extensions(self) -> dict: class ServiceDeployedEvent(ServiceEvent): - def __init__(self, **kwargs): + def __init__(self, envid: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.ServiceDeployedEventV1 - super().__init__(service_type=self._event_type, **kwargs) + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, attrs=attrs, data=data) class ServiceUpgradedEvent(ServiceEvent): - def __init__(self, **kwargs): + def __init__(self, envid: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.ServiceUpgradedEventV1 - super().__init__(service_type=self._event_type, **kwargs) + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, attrs=attrs, data=data) class ServiceRolledbackEvent(ServiceEvent): - def __init__(self, **kwargs): + def __init__(self, envid: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.ServiceRolledbackEventV1 - super().__init__(service_type=self._event_type, **kwargs) + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, attrs=attrs, data=data) class ServiceRemovedEvent(ServiceEvent): - def __init__(self, **kwargs): + def __init__(self, envid: str=None, name: str=None, version: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.ServiceRemovedEventV1 - super().__init__(service_type=self._event_type, **kwargs) + super().__init__(service_type=self._event_type, envid=envid, name=name, version=version, attrs=attrs, data=data) diff --git a/core/cdevents/core/taskrun.py b/core/cdevents/core/taskrun.py index 9b90518..661d9be 100644 --- a/core/cdevents/core/taskrun.py +++ b/core/cdevents/core/taskrun.py @@ -6,24 +6,14 @@ class TaskRunEvent(Event): """Taskrun Event.""" - def __init__(self, **kwargs): + def __init__(self,taskrun_type: EventType, id: str, name: str, pipelineid: str, attrs=None, data: dict = {}): """Initializes class. """ - self._event_type :EventType = kwargs['taskrun_type'] - if 'data' in kwargs: - self._data :dict = kwargs['data'] - - if 'id' in kwargs and 'name' in kwargs and 'pipelineid' in kwargs: - self._id :str = kwargs['id'] - self._name :str = kwargs['name'] - self._pipelineid :str = kwargs['pipelineid'] - - elif 'extensions' in kwargs: - self._id = kwargs['extensions']['taskrunid'] - self._name = kwargs['extensions']['taskrunname'] - self._pipelineid = kwargs['extensions']['taskrunpipelineid'] - - super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), data=self._data) + self._event_type = taskrun_type + self._id= id + self._name = name + self._pipelineid = pipelineid + super().__init__(event_type=self._event_type.value, extensions=self.create_extensions(), attrs=attrs, data=data) def create_extensions(self) -> dict: """Create extensions. @@ -37,18 +27,18 @@ def create_extensions(self) -> dict: class TaskRunStartedEvent(TaskRunEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, pipelineid: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.TaskRunStartedEventV1 - super().__init__(taskrun_type=self._event_type, **kwargs) + super().__init__(taskrun_type=self._event_type, id=id, name=name, pipelineid=pipelineid, attrs=attrs, data=data) class TaskRunFinishedEvent(TaskRunEvent): - def __init__(self, **kwargs): + def __init__(self, id: str=None, name: str=None, pipelineid: str=None, attrs=None, data: dict = {}): """Initializes class. """ self._event_type: str = EventType.TaskRunFinishedEventV1 - super().__init__(taskrun_type=self._event_type, **kwargs) + super().__init__(taskrun_type=self._event_type, id=id, name=name, pipelineid=pipelineid, attrs=attrs, data=data)