georgs_eventmsg #45

Merged
Ghost merged 3 commits from georgs_eventmsg into main 2024-01-08 20:51:15 +00:00
18 changed files with 1079 additions and 8 deletions

View File

@@ -12,6 +12,8 @@ from .. import sql_crud, sql_db, sql_models
from ..schemas import (
Entity,
EntityCreate,
Eventmessage,
EventmessageCreate,
Resolution,
Service,
ServiceCreate,
@@ -262,3 +264,29 @@ async def get_all_resolutions(
id=1,
)
]
#########################
# #
# Eventmessage #
# #
#########################
@router.post("/api/v1/send_msg", response_model=Eventmessage, tags=[Tags.eventmessages])
async def create_eventmessage(
eventmsg: EventmessageCreate, db: Session = Depends(sql_db.get_db)
) -> EventmessageCreate:
return sql_crud.create_eventmessage(db, eventmsg)
@router.get(
"/api/v1/event_messages",
response_model=List[Eventmessage],
tags=[Tags.eventmessages],
)
async def get_all_eventmessages(
skip: int = 0, limit: int = 100, db: Session = Depends(sql_db.get_db)
) -> List[sql_models.Eventmessage]:
eventmessages = sql_crud.get_eventmessages(db, skip=skip, limit=limit)
return eventmessages

View File

@@ -104,3 +104,30 @@ class Resolution(ResolutionCreate):
class Config:
orm_mode = True
#########################
# #
# Eventmessage #
# #
#########################
class EventmessageBase(BaseModel):
id: int = Field(..., example=123456)
timestamp: int = Field(..., example=1234123413)
group: int = Field(..., example=1) # event group type (for the label)
group_id: int = Field(
..., example=12345
) # specific to one group needed to enable visually nested groups
msg_type: int = Field(..., example=1) # message type for the label
src_did: str = Field(..., example="did:sov:test:2234")
des_did: str = Field(..., example="did:sov:test:1234")
class EventmessageCreate(EventmessageBase):
msg: dict = Field(..., example={"optinal": "values"}) # optional
pass
class Eventmessage(EventmessageCreate):
class Config:
orm_mode = True

View File

@@ -136,3 +136,26 @@ def delete_entity_by_did(db: Session, did: str) -> None:
def delete_entity_by_did_recursive(db: Session, did: str) -> None:
delete_service_by_entity_did(db, did)
delete_entity_by_did(db, did)
#########################
# #
# Eventmessage #
# #
#########################
def create_eventmessage(
db: Session, eventmsg: schemas.EventmessageCreate
) -> sql_models.Eventmessage:
db_eventmessage = sql_models.Eventmessage(**eventmsg.dict())
db.add(db_eventmessage)
db.commit()
db.refresh(db_eventmessage)
return db_eventmessage
def get_eventmessages(
db: Session, skip: int = 0, limit: int = 100
) -> List[sql_models.Eventmessage]:
return db.query(sql_models.Eventmessage).offset(skip).limit(limit).all()

View File

@@ -1,11 +1,4 @@
from sqlalchemy import (
JSON,
Boolean,
Column,
ForeignKey,
String,
Text,
)
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from .sql_db import Base
@@ -55,3 +48,23 @@ class Service(ServiceAbstract):
# One entity can have many services
entity = relationship("Entity", back_populates="services")
entity_did = Column(String, ForeignKey("entities.did"))
class Eventmessage(Base):
__tablename__ = "eventmessages"
## Queryable body ##
id = Column(Integer, primary_key=True, index=True)
timestamp = Column(Integer, unique=True, index=True)
group = Column(Integer, index=True)
group_id = Column(Integer, index=True)
msg_type = Column(Integer, index=True) # message type for the label
src_did = Column(String, index=True)
des_did = Column(String, index=True)
## Non queryable body ##
# In here we deposit: Network, Roles, Visible, etc.
msg = Column(JSON)
## Relations ##
# One entity can send many messages

View File

@@ -7,6 +7,7 @@ class Tags(Enum):
entities = "entities"
repositories = "repositories"
resolutions = "resolution"
eventmessages = "eventmessages"
def __str__(self) -> str:
return self.value
@@ -29,4 +30,8 @@ tags_metadata: List[Dict[str, Any]] = [
"name": str(Tags.resolutions),
"description": "Operations on a resolution.",
},
{
"name": str(Tags.eventmessages),
"description": "Operations for event messages.",
},
]

View File

@@ -19,6 +19,7 @@ __version__ = "1.0.0"
# import apis into sdk package
from openapi_client.api.default_api import DefaultApi
from openapi_client.api.entities_api import EntitiesApi
from openapi_client.api.eventmessages_api import EventmessagesApi
from openapi_client.api.repositories_api import RepositoriesApi
from openapi_client.api.resolution_api import ResolutionApi
from openapi_client.api.services_api import ServicesApi
@@ -37,6 +38,8 @@ from openapi_client.exceptions import ApiException
# import models into sdk package
from openapi_client.models.entity import Entity
from openapi_client.models.entity_create import EntityCreate
from openapi_client.models.eventmessage import Eventmessage
from openapi_client.models.eventmessage_create import EventmessageCreate
from openapi_client.models.http_validation_error import HTTPValidationError
from openapi_client.models.machine import Machine
from openapi_client.models.resolution import Resolution

View File

@@ -3,6 +3,7 @@
# import apis into api package
from openapi_client.api.default_api import DefaultApi
from openapi_client.api.entities_api import EntitiesApi
from openapi_client.api.eventmessages_api import EventmessagesApi
from openapi_client.api.repositories_api import RepositoriesApi
from openapi_client.api.resolution_api import ResolutionApi
from openapi_client.api.services_api import ServicesApi

View File

@@ -0,0 +1,339 @@
# coding: utf-8
"""
FastAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 0.1.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import re # noqa: F401
import io
import warnings
from pydantic import validate_arguments, ValidationError
from pydantic import StrictInt
from typing import List, Optional
from openapi_client.models.eventmessage import Eventmessage
from openapi_client.models.eventmessage_create import EventmessageCreate
from openapi_client.api_client import ApiClient
from openapi_client.api_response import ApiResponse
from openapi_client.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class EventmessagesApi:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
@validate_arguments
def create_eventmessage(self, eventmessage_create : EventmessageCreate, **kwargs) -> Eventmessage: # noqa: E501
"""Create Eventmessage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_eventmessage(eventmessage_create, async_req=True)
>>> result = thread.get()
:param eventmessage_create: (required)
:type eventmessage_create: EventmessageCreate
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _request_timeout: timeout setting for this request.
If one number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: Eventmessage
"""
kwargs['_return_http_data_only'] = True
if '_preload_content' in kwargs:
message = "Error! Please call the create_eventmessage_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501
raise ValueError(message)
return self.create_eventmessage_with_http_info(eventmessage_create, **kwargs) # noqa: E501
@validate_arguments
def create_eventmessage_with_http_info(self, eventmessage_create : EventmessageCreate, **kwargs) -> ApiResponse: # noqa: E501
"""Create Eventmessage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_eventmessage_with_http_info(eventmessage_create, async_req=True)
>>> result = thread.get()
:param eventmessage_create: (required)
:type eventmessage_create: EventmessageCreate
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _preload_content: if False, the ApiResponse.data will
be set to none and raw_data will store the
HTTP response body without reading/decoding.
Default is True.
:type _preload_content: bool, optional
:param _return_http_data_only: response data instead of ApiResponse
object with status code, headers, etc
:type _return_http_data_only: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:type _request_auth: dict, optional
:type _content_type: string, optional: force content-type for the request
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: tuple(Eventmessage, status_code(int), headers(HTTPHeaderDict))
"""
_params = locals()
_all_params = [
'eventmessage_create'
]
_all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout',
'_request_auth',
'_content_type',
'_headers'
]
)
# validate the arguments
for _key, _val in _params['kwargs'].items():
if _key not in _all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_eventmessage" % _key
)
_params[_key] = _val
del _params['kwargs']
_collection_formats = {}
# process the path parameters
_path_params = {}
# process the query parameters
_query_params = []
# process the header parameters
_header_params = dict(_params.get('_headers', {}))
# process the form parameters
_form_params = []
_files = {}
# process the body parameter
_body_params = None
if _params['eventmessage_create'] is not None:
_body_params = _params['eventmessage_create']
# set the HTTP header `Accept`
_header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# set the HTTP header `Content-Type`
_content_types_list = _params.get('_content_type',
self.api_client.select_header_content_type(
['application/json']))
if _content_types_list:
_header_params['Content-Type'] = _content_types_list
# authentication setting
_auth_settings = [] # noqa: E501
_response_types_map = {
'200': "Eventmessage",
'422': "HTTPValidationError",
}
return self.api_client.call_api(
'/api/v1/send_msg', 'POST',
_path_params,
_query_params,
_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
response_types_map=_response_types_map,
auth_settings=_auth_settings,
async_req=_params.get('async_req'),
_return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501
_preload_content=_params.get('_preload_content', True),
_request_timeout=_params.get('_request_timeout'),
collection_formats=_collection_formats,
_request_auth=_params.get('_request_auth'))
@validate_arguments
def get_all_eventmessages(self, skip : Optional[StrictInt] = None, limit : Optional[StrictInt] = None, **kwargs) -> List[Eventmessage]: # noqa: E501
"""Get All Eventmessages # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_eventmessages(skip, limit, async_req=True)
>>> result = thread.get()
:param skip:
:type skip: int
:param limit:
:type limit: int
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _request_timeout: timeout setting for this request.
If one number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: List[Eventmessage]
"""
kwargs['_return_http_data_only'] = True
if '_preload_content' in kwargs:
message = "Error! Please call the get_all_eventmessages_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501
raise ValueError(message)
return self.get_all_eventmessages_with_http_info(skip, limit, **kwargs) # noqa: E501
@validate_arguments
def get_all_eventmessages_with_http_info(self, skip : Optional[StrictInt] = None, limit : Optional[StrictInt] = None, **kwargs) -> ApiResponse: # noqa: E501
"""Get All Eventmessages # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_eventmessages_with_http_info(skip, limit, async_req=True)
>>> result = thread.get()
:param skip:
:type skip: int
:param limit:
:type limit: int
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _preload_content: if False, the ApiResponse.data will
be set to none and raw_data will store the
HTTP response body without reading/decoding.
Default is True.
:type _preload_content: bool, optional
:param _return_http_data_only: response data instead of ApiResponse
object with status code, headers, etc
:type _return_http_data_only: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:type _request_auth: dict, optional
:type _content_type: string, optional: force content-type for the request
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: tuple(List[Eventmessage], status_code(int), headers(HTTPHeaderDict))
"""
_params = locals()
_all_params = [
'skip',
'limit'
]
_all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout',
'_request_auth',
'_content_type',
'_headers'
]
)
# validate the arguments
for _key, _val in _params['kwargs'].items():
if _key not in _all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_all_eventmessages" % _key
)
_params[_key] = _val
del _params['kwargs']
_collection_formats = {}
# process the path parameters
_path_params = {}
# process the query parameters
_query_params = []
if _params.get('skip') is not None: # noqa: E501
_query_params.append(('skip', _params['skip']))
if _params.get('limit') is not None: # noqa: E501
_query_params.append(('limit', _params['limit']))
# process the header parameters
_header_params = dict(_params.get('_headers', {}))
# process the form parameters
_form_params = []
_files = {}
# process the body parameter
_body_params = None
# set the HTTP header `Accept`
_header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# authentication setting
_auth_settings = [] # noqa: E501
_response_types_map = {
'200': "List[Eventmessage]",
'422': "HTTPValidationError",
}
return self.api_client.call_api(
'/api/v1/event_messages', 'GET',
_path_params,
_query_params,
_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
response_types_map=_response_types_map,
auth_settings=_auth_settings,
async_req=_params.get('async_req'),
_return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501
_preload_content=_params.get('_preload_content', True),
_request_timeout=_params.get('_request_timeout'),
collection_formats=_collection_formats,
_request_auth=_params.get('_request_auth'))

View File

@@ -0,0 +1,34 @@
# Eventmessage
## Properties
| Name | Type | Description | Notes |
| ------------- | ---------- | ----------- | ----- |
| **id** | **int** | |
| **timestamp** | **int** | |
| **group** | **int** | |
| **group_id** | **int** | |
| **msg_type** | **int** | |
| **src_did** | **str** | |
| **des_did** | **str** | |
| **msg** | **object** | |
## Example
```python
from openapi_client.models.eventmessage import Eventmessage
# TODO update the JSON string below
json = "{}"
# create an instance of Eventmessage from a JSON string
eventmessage_instance = Eventmessage.from_json(json)
# print the JSON string representation of the object
print Eventmessage.to_json()
# convert the object into a dict
eventmessage_dict = eventmessage_instance.to_dict()
# create an instance of Eventmessage from a dict
eventmessage_form_dict = eventmessage.from_dict(eventmessage_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,34 @@
# EventmessageCreate
## Properties
| Name | Type | Description | Notes |
| ------------- | ---------- | ----------- | ----- |
| **id** | **int** | |
| **timestamp** | **int** | |
| **group** | **int** | |
| **group_id** | **int** | |
| **msg_type** | **int** | |
| **src_did** | **str** | |
| **des_did** | **str** | |
| **msg** | **object** | |
## Example
```python
from openapi_client.models.eventmessage_create import EventmessageCreate
# TODO update the JSON string below
json = "{}"
# create an instance of EventmessageCreate from a JSON string
eventmessage_create_instance = EventmessageCreate.from_json(json)
# print the JSON string representation of the object
print EventmessageCreate.to_json()
# convert the object into a dict
eventmessage_create_dict = eventmessage_create_instance.to_dict()
# create an instance of EventmessageCreate from a dict
eventmessage_create_form_dict = eventmessage_create.from_dict(eventmessage_create_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,143 @@
# openapi_client.EventmessagesApi
All URIs are relative to _http://localhost_
| Method | HTTP request | Description |
| ---------------------------------------------------------------------- | ------------------------------ | --------------------- |
| [**create_eventmessage**](EventmessagesApi.md#create_eventmessage) | **POST** /api/v1/send_msg | Create Eventmessage |
| [**get_all_eventmessages**](EventmessagesApi.md#get_all_eventmessages) | **GET** /api/v1/event_messages | Get All Eventmessages |
# **create_eventmessage**
> Eventmessage create_eventmessage(eventmessage_create)
Create Eventmessage
### Example
```python
import time
import os
import openapi_client
from openapi_client.models.eventmessage import Eventmessage
from openapi_client.models.eventmessage_create import EventmessageCreate
from openapi_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = openapi_client.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
with openapi_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = openapi_client.EventmessagesApi(api_client)
eventmessage_create = openapi_client.EventmessageCreate() # EventmessageCreate |
try:
# Create Eventmessage
api_response = api_instance.create_eventmessage(eventmessage_create)
print("The response of EventmessagesApi->create_eventmessage:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling EventmessagesApi->create_eventmessage: %s\n" % e)
```
### Parameters
| Name | Type | Description | Notes |
| ----------------------- | ----------------------------------------------- | ----------- | ----- |
| **eventmessage_create** | [**EventmessageCreate**](EventmessageCreate.md) | |
### Return type
[**Eventmessage**](Eventmessage.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
| ----------- | ------------------- | ---------------- |
| **200** | Successful Response | - |
| **422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_all_eventmessages**
> List[Eventmessage] get_all_eventmessages(skip=skip, limit=limit)
Get All Eventmessages
### Example
```python
import time
import os
import openapi_client
from openapi_client.models.eventmessage import Eventmessage
from openapi_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost
# See configuration.py for a list of all supported configuration parameters.
configuration = openapi_client.Configuration(
host = "http://localhost"
)
# Enter a context with an instance of the API client
with openapi_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = openapi_client.EventmessagesApi(api_client)
skip = 0 # int | (optional) (default to 0)
limit = 100 # int | (optional) (default to 100)
try:
# Get All Eventmessages
api_response = api_instance.get_all_eventmessages(skip=skip, limit=limit)
print("The response of EventmessagesApi->get_all_eventmessages:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling EventmessagesApi->get_all_eventmessages: %s\n" % e)
```
### Parameters
| Name | Type | Description | Notes |
| --------- | ------- | ----------- | --------------------------- |
| **skip** | **int** | | [optional] [default to 0] |
| **limit** | **int** | | [optional] [default to 100] |
### Return type
[**List[Eventmessage]**](Eventmessage.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
| ----------- | ------------------- | ---------------- |
| **200** | Successful Response | - |
| **422** | Validation Error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@@ -16,6 +16,8 @@
# import models into model package
from openapi_client.models.entity import Entity
from openapi_client.models.entity_create import EntityCreate
from openapi_client.models.eventmessage import Eventmessage
from openapi_client.models.eventmessage_create import EventmessageCreate
from openapi_client.models.http_validation_error import HTTPValidationError
from openapi_client.models.machine import Machine
from openapi_client.models.resolution import Resolution

View File

@@ -0,0 +1,85 @@
# coding: utf-8
"""
FastAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 0.1.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from typing import Any, Dict
from pydantic import BaseModel, Field, StrictInt, StrictStr
class Eventmessage(BaseModel):
"""
Eventmessage
"""
id: StrictInt = Field(...)
timestamp: StrictInt = Field(...)
group: StrictInt = Field(...)
group_id: StrictInt = Field(...)
msg_type: StrictInt = Field(...)
src_did: StrictStr = Field(...)
des_did: StrictStr = Field(...)
msg: Dict[str, Any] = Field(...)
__properties = ["id", "timestamp", "group", "group_id", "msg_type", "src_did", "des_did", "msg"]
class Config:
"""Pydantic configuration"""
allow_population_by_field_name = True
validate_assignment = True
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.dict(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Eventmessage:
"""Create an instance of Eventmessage from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self):
"""Returns the dictionary representation of the model using alias"""
_dict = self.dict(by_alias=True,
exclude={
},
exclude_none=True)
return _dict
@classmethod
def from_dict(cls, obj: dict) -> Eventmessage:
"""Create an instance of Eventmessage from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return Eventmessage.parse_obj(obj)
_obj = Eventmessage.parse_obj({
"id": obj.get("id"),
"timestamp": obj.get("timestamp"),
"group": obj.get("group"),
"group_id": obj.get("group_id"),
"msg_type": obj.get("msg_type"),
"src_did": obj.get("src_did"),
"des_did": obj.get("des_did"),
"msg": obj.get("msg")
})
return _obj

View File

@@ -0,0 +1,85 @@
# coding: utf-8
"""
FastAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 0.1.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from typing import Any, Dict
from pydantic import BaseModel, Field, StrictInt, StrictStr
class EventmessageCreate(BaseModel):
"""
EventmessageCreate
"""
id: StrictInt = Field(...)
timestamp: StrictInt = Field(...)
group: StrictInt = Field(...)
group_id: StrictInt = Field(...)
msg_type: StrictInt = Field(...)
src_did: StrictStr = Field(...)
des_did: StrictStr = Field(...)
msg: Dict[str, Any] = Field(...)
__properties = ["id", "timestamp", "group", "group_id", "msg_type", "src_did", "des_did", "msg"]
class Config:
"""Pydantic configuration"""
allow_population_by_field_name = True
validate_assignment = True
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.dict(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> EventmessageCreate:
"""Create an instance of EventmessageCreate from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self):
"""Returns the dictionary representation of the model using alias"""
_dict = self.dict(by_alias=True,
exclude={
},
exclude_none=True)
return _dict
@classmethod
def from_dict(cls, obj: dict) -> EventmessageCreate:
"""Create an instance of EventmessageCreate from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return EventmessageCreate.parse_obj(obj)
_obj = EventmessageCreate.parse_obj({
"id": obj.get("id"),
"timestamp": obj.get("timestamp"),
"group": obj.get("group"),
"group_id": obj.get("group_id"),
"msg_type": obj.get("msg_type"),
"src_did": obj.get("src_did"),
"des_did": obj.get("des_did"),
"msg": obj.get("msg")
})
return _obj

View File

@@ -0,0 +1,67 @@
# coding: utf-8
"""
FastAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 0.1.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
import datetime
from openapi_client.models.eventmessage import Eventmessage # noqa: E501
class TestEventmessage(unittest.TestCase):
"""Eventmessage unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> Eventmessage:
"""Test Eventmessage
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Eventmessage`
"""
model = Eventmessage() # noqa: E501
if include_optional:
return Eventmessage(
id = 123456,
timestamp = 1234123413,
group = 1,
group_id = 12345,
msg_type = 1,
src_did = 'did:sov:test:2234',
des_did = 'did:sov:test:1234',
msg = {optinal=values}
)
else:
return Eventmessage(
id = 123456,
timestamp = 1234123413,
group = 1,
group_id = 12345,
msg_type = 1,
src_did = 'did:sov:test:2234',
des_did = 'did:sov:test:1234',
msg = {optinal=values},
)
"""
def testEventmessage(self):
"""Test Eventmessage"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,67 @@
# coding: utf-8
"""
FastAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 0.1.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
import datetime
from openapi_client.models.eventmessage_create import EventmessageCreate # noqa: E501
class TestEventmessageCreate(unittest.TestCase):
"""EventmessageCreate unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> EventmessageCreate:
"""Test EventmessageCreate
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `EventmessageCreate`
"""
model = EventmessageCreate() # noqa: E501
if include_optional:
return EventmessageCreate(
id = 123456,
timestamp = 1234123413,
group = 1,
group_id = 12345,
msg_type = 1,
src_did = 'did:sov:test:2234',
des_did = 'did:sov:test:1234',
msg = {optinal=values}
)
else:
return EventmessageCreate(
id = 123456,
timestamp = 1234123413,
group = 1,
group_id = 12345,
msg_type = 1,
src_did = 'did:sov:test:2234',
des_did = 'did:sov:test:1234',
msg = {optinal=values},
)
"""
def testEventmessageCreate(self):
"""Test EventmessageCreate"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,45 @@
# coding: utf-8
"""
FastAPI
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
The version of the OpenAPI document: 0.1.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from openapi_client.api.eventmessages_api import EventmessagesApi # noqa: E501
class TestEventmessagesApi(unittest.TestCase):
"""EventmessagesApi unit test stubs"""
def setUp(self) -> None:
self.api = EventmessagesApi() # noqa: E501
def tearDown(self) -> None:
pass
def test_create_eventmessage(self) -> None:
"""Test case for create_eventmessage
Create Eventmessage # noqa: E501
"""
pass
def test_get_all_eventmessages(self) -> None:
"""Test case for get_all_eventmessages
Get All Eventmessages # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()

View File

@@ -1,13 +1,17 @@
import random
import time
import uuid
from openapi_client import ApiClient
from openapi_client.api import DefaultApi
from openapi_client.api.entities_api import EntitiesApi
from openapi_client.api.eventmessages_api import EventmessagesApi
from openapi_client.api.services_api import ServicesApi
from openapi_client.models import (
Entity,
EntityCreate,
Eventmessage,
EventmessageCreate,
Machine,
ServiceCreate,
Status,
@@ -70,3 +74,69 @@ def test_create_services(api_client: ApiClient) -> None:
service_obj = create_service(idx + 4 * midx, entity)
service = sapi.create_service(service_obj)
assert service.uuid == service_obj.uuid
random.seed(77)
def create_eventmessages(num: int = 2) -> list[EventmessageCreate]:
res = []
starttime = int(time.time())
for i in range(num):
group_id = i % 5 + random.getrandbits(6)
em_req_send = EventmessageCreate(
id=random.getrandbits(18),
timestamp=starttime + i * 10,
group=i % 5,
group_id=group_id,
msg_type=1,
src_did=f"did:sov:test:12{i}",
des_did=f"did:sov:test:12{i+1}",
msg={},
)
res.append(em_req_send)
em_req_rec = EventmessageCreate(
id=random.getrandbits(18),
timestamp=starttime + (i * 10) + 2,
group=i % 5,
group_id=group_id,
msg_type=2,
src_did=f"did:sov:test:12{i}",
des_did=f"did:sov:test:12{i+1}",
msg={},
)
res.append(em_req_rec)
group_id = i % 5 + random.getrandbits(6)
em_res_send = EventmessageCreate(
id=random.getrandbits(18),
timestamp=starttime + i * 10 + 4,
group=i % 5,
group_id=group_id,
msg_type=3,
src_did=f"did:sov:test:12{i+1}",
des_did=f"did:sov:test:12{i}",
msg={},
)
res.append(em_res_send)
em_res_rec = EventmessageCreate(
id=random.getrandbits(6),
timestamp=starttime + (i * 10) + 8,
group=i % 5,
group_id=group_id,
msg_type=4,
src_did=f"did:sov:test:12{i+1}",
des_did=f"did:sov:test:12{i}",
msg={},
)
res.append(em_res_rec)
return res
def test_create_eventmessages(api_client: ApiClient) -> None:
api = EventmessagesApi(api_client=api_client)
assert [] == api.get_all_eventmessages()
for own_eventmsg in create_eventmessages():
res: Eventmessage = api.create_eventmessage(own_eventmsg)
# breakpoint()
assert res.id == own_eventmsg.id
assert [] != api.get_all_eventmessages()