From c7aeaea941eb959ea3b6d351c13a109134ba2778 Mon Sep 17 00:00:00 2001 From: Matthias Bodenbenner <m.bodenbenner@wzl-mq.rwth-aachen.de> Date: Thu, 14 Apr 2022 14:54:18 +0200 Subject: [PATCH] removed tests temporarily --- dev/environment.yml => environment.yml | 0 dev/requirements.txt => requirements.txt | 1 + test/Sensor.json | 1 - test/TestRequestPerformance.py | 142 ------------- test/requests.http | 243 ----------------------- test/server/__init__.py | 0 test/server/main.py | 23 --- test/server/start.py | 133 ------------- test/test.py | 108 ---------- test/test_variable.py | 54 ----- 10 files changed, 1 insertion(+), 704 deletions(-) rename dev/environment.yml => environment.yml (100%) rename dev/requirements.txt => requirements.txt (93%) delete mode 100644 test/Sensor.json delete mode 100644 test/TestRequestPerformance.py delete mode 100644 test/requests.http delete mode 100644 test/server/__init__.py delete mode 100644 test/server/main.py delete mode 100644 test/server/start.py delete mode 100644 test/test.py delete mode 100644 test/test_variable.py diff --git a/dev/environment.yml b/environment.yml similarity index 100% rename from dev/environment.yml rename to environment.yml diff --git a/dev/requirements.txt b/requirements.txt similarity index 93% rename from dev/requirements.txt rename to requirements.txt index c4ff73e..100262d 100644 --- a/dev/requirements.txt +++ b/requirements.txt @@ -3,6 +3,7 @@ Deprecated==1.2.13 docstring-parser==0.7.3 jinja2==3.0.3 nest-asyncio==1.4.3 +pytest==7.1.1 sphinx==3.5.2 sphinx-rtd-theme==1.0.0 strict-rfc3339==0.7 diff --git a/test/Sensor.json b/test/Sensor.json deleted file mode 100644 index 8b20ff9..0000000 --- a/test/Sensor.json +++ /dev/null @@ -1 +0,0 @@ -{"objects": [], "functions": [{"arguments": [], "returns": [], "uuid": "FUN-Refresh", "name": "Trigger Refresh", "description": "Manually triggers refresh of the sensors"}, {"arguments": [{"constant": false, "range": [1, null], "datatype": "int", "dimension": [], "value": 1, "uuid": "PAR-Interval", "name": "Interval (s)", "description": "Interval in seconds over which to take RMS."}], "returns": [{"constant": false, "range": [null, null], "datatype": "int", "dimension": [], "value": 0, "uuid": "PAR-Count", "name": "Count", "description": "Number of values used for RMS estimation"}, {"constant": false, "range": [null, null], "datatype": "double", "dimension": [], "value": 0, "uuid": "PAR-RMS", "name": "RMS (*C)", "description": "Estimated RMS form measurement sequence"}, {"constant": false, "range": [null, null], "datatype": "double", "dimension": [], "value": 0, "uuid": "PAR-Mean", "name": "Mean (*C)", "description": "Mean of RMS estimation sequence (*C)"}], "uuid": "FUN-MeasureRMS", "name": "Measure RMS", "description": "Measures the RMS over a given period of time for this sensor."}, {"arguments": [{"constant": false, "range": [0, 100], "datatype": "int", "dimension": [], "value": 1, "uuid": "PAR-Interval", "name": "Refresh Interval (s)", "description": "Current refresh interval in seconds."}, {"constant": false, "range": [null, 20], "datatype": "string", "dimension": [], "value": "outside", "uuid": "PAR-Location", "name": "Location", "description": "Description of the location of the sensor."}], "returns": [], "uuid": "FUN-Reset", "name": "Reset", "description": "Resets various values of the sensor."}], "variables": [{"unit": "CEL", "range": [null, null], "datatype": "double", "dimension": [], "value": 0, "uuid": "VAR-Temperature", "name": "Temperature (*C)", "description": "Most recently measured temperature in degree celsius"}, {"unit": "A97", "range": [null, null], "datatype": "double", "dimension": [], "value": 0, "uuid": "VAR-Pressure", "name": "Pressure (hPa)", "description": "Most recently measured pressure in hPa"}, {"unit": "", "range": [0, 100], "datatype": "int", "dimension": [], "value": 0, "uuid": "VAR-Battery", "name": "Batterylevel (Percent)", "description": "Estimated battery level in percent"}, {"unit": "", "range": [0, 100], "datatype": "int", "dimension": [], "value": 0, "uuid": "VAR-Signal", "name": "Signal strength", "description": "Signal strength in percent"}, {"unit": "", "range": [0, 100], "datatype": "int", "dimension": [], "value": 50, "uuid": "VAR-Humidity", "name": "Humidity (Percent)", "description": "Gives the current humidity in percent."}], "parameters": [{"constant": true, "range": [null, null], "datatype": "string", "dimension": [], "value": "AC-DE-48-00-00-80", "uuid": "PAR-Mac", "name": "MAC-Adress", "description": "Bluetooth MAC-Address of the sensor "}, {"constant": false, "range": [0, 100], "datatype": "int", "dimension": [], "value": 0, "uuid": "PAR-Interval", "name": "Refresh Interval (s)", "description": "Current refresh interval in seconds"}, {"constant": false, "range": [null, 20], "datatype": "string", "dimension": [], "value": "undefined", "uuid": "PAR-Location", "name": "Location", "description": "Description of the location of the sensor"}, {"constant": true, "range": ["False", "True"], "datatype": "bool", "dimension": [], "value": true, "uuid": "PAR-Contacted", "name": "Contacted", "description": "Flag whether the temperature is measured contacted (true) or ambient (false)"}], "uuid": "OBJ-Sensor", "name": "Sensor", "description": "An individual Sensor of the distributed system."} \ No newline at end of file diff --git a/test/TestRequestPerformance.py b/test/TestRequestPerformance.py deleted file mode 100644 index 2abf2af..0000000 --- a/test/TestRequestPerformance.py +++ /dev/null @@ -1,142 +0,0 @@ -# import asyncio -# import datetime -# import logging -# import logging.config -# from asyncio import Lock -# from concurrent.futures import ThreadPoolExecutor -# -# import aiohttp -# from autobahn.asyncio.websocket import WebSocketClientFactory, WebSocketClientProtocol -# -# -# class PerformanceController(object): -# last_message = None -# last_request = None -# tot_message_diff = datetime.timedelta() -# tot_request_diff = datetime.timedelta() -# avg_message_diff = 0 -# avg_request_diff = 0 -# nr_messages = 0 -# nr_requests = 0 -# url = 'http://localhost:8000/objects/OBJ-78da2add-0779-4c91-9f69-907348c409aa/VAR-c39505a8-b264-411a-86f1-3b55f124fec1/' -# -# def __init__(self): -# pass -# -# def logMessage(self): -# now = datetime.datetime.now() -# if self.last_message is not None: -# diff = now - self.last_message -# self.tot_message_diff += diff -# logging.getLogger(__name__).debug('Time between two messages: {} ms'.format(diff.microseconds / 1000)) -# self.last_message = now -# self.nr_messages += 1 -# -# def logRequest(self): -# now = datetime.datetime.now() -# if self.last_request is not None: -# diff = now - self.last_request -# self.tot_request_diff += diff -# logging.getLogger(__name__).debug('Time between two requests: {} ms'.format(diff.microseconds / 1000)) -# self.last_request = now -# self.nr_requests += 1 -# -# @asyncio.coroutine -# def wait(self, nr_messages): -# logging.getLogger(__name__).info('Waiting for {} messages...'.format(nr_messages)) -# while self.nr_messages < nr_messages: -# logging.getLogger(__name__).debug('Current #messages: {} '.format(self.nr_messages)) -# yield from asyncio.sleep(0.1) -# logging.getLogger(__name__).info('Enough messages have been recieved...') -# logging.getLogger(__name__).info('Number of recieved messages: {}'.format(self.nr_messages)) -# self.avg_message_diff = (self.tot_message_diff.seconds * 1000 + self.tot_message_diff.microseconds / 1000) / (self.nr_messages - 1) -# logging.getLogger(__name__).info('Average diff: {:>6.3f} ms'.format(self.avg_message_diff)) -# -# @asyncio.coroutine -# def SpamRequests(self, nr_requests, session, delta): -# self.last_message = None -# self.tot_message_diff = datetime.timedelta() -# self.nr_messages = 0 -# for id in range(nr_requests): -# yield from self.request(session) -# yield from asyncio.sleep(delta) -# logging.getLogger(__name__).info('Number of recieved messages: {}'.format(self.nr_messages)) -# self.avg_message_diff = (self.tot_message_diff.seconds * 1000 + self.tot_message_diff.microseconds / 1000) / (self.nr_messages - 1) -# logging.getLogger(__name__).info('Average diff: {:>6.3f} ms'.format(self.avg_message_diff)) -# logging.getLogger(__name__).info('Number of performed requests messages: {}'.format(self.nr_requests)) -# self.avg_request_diff = (self.tot_request_diff.seconds * 1000 + self.tot_request_diff.microseconds / 1000) / (self.nr_requests - 1) -# logging.getLogger(__name__).info('Average diff: {:>6.3f} ms'.format(self.avg_request_diff)) -# -# async def request(self, session): -# with aiohttp.Timeout(10): -# async with session.get(self.url, json={'uuid': True, 'name': True, 'description': True, 'datatype': True, 'value': True, 'dimension': True}) as response: -# # assert response.status == 200 -# data = await response.read() -# logging.getLogger(__name__).debug(data) -# self.logRequest() -# -# -# class MyClientProtocol(WebSocketClientProtocol): -# -# def __init__(self): -# global pc -# super().__init__() -# self.pc = pc -# self.lock = Lock() -# -# @asyncio.coroutine -# def onConnect(self, response): -# logging.getLogger(__name__).info("Server connected: {0}".format(response.peer)) -# -# @asyncio.coroutine -# def onOpen(self): -# logging.getLogger(__name__).info("WebSocket connection open.") -# -# @asyncio.coroutine -# def onMessage(self, payload, isBinary): -# if isBinary: -# logging.getLogger(__name__).debug("Binary message received: {0} bytes".format(len(payload))) -# else: -# logging.getLogger(__name__).debug("Text message received: {0}".format(payload.decode('utf8'))) -# self.pc.logMessage() -# -# @asyncio.coroutine -# def onClose(self, wasClean, code, reason): -# logging.getLogger(__name__).info("WebSocket connection closed: {0}".format(reason)) -# -# -# if __name__ == '__main__': -# # configure logger -# logging.config.fileConfig('../assets/logger.ini') -# logger = logging.getLogger('') -# -# fh = logging.FileHandler('../logs/testing/log_{:%Y-%m-%d_%H-%M}.txt'.format(datetime.datetime.now())) -# formatter = logging.Formatter('%(asctime)s %(name)-40s %(levelname)-8s %(message)s') -# fh.setFormatter(formatter) -# -# logger.addHandler(fh) -# -# pc = PerformanceController() -# -# # set up clients -# executor = ThreadPoolExecutor(max_workers=100) -# loop = asyncio.get_event_loop() -# loop.set_default_executor(executor) -# -# logging.getLogger(__name__).info("Register client to get updates") -# factory = WebSocketClientFactory(loop=loop, -# url="ws://127.0.0.1:8001/OBJ-78da2add-0779-4c91-9f69-907348c409aa/VAR-dc495055-7134-4055-9d72-c6b6bcb10c0e/") -# factory.protocol = MyClientProtocol -# -# coro = loop.create_connection(factory, '127.0.0.1', 8001) -# loop.run_until_complete(coro) -# -# # start performance test -# logging.getLogger(__name__).info("Starting Performance Test...") -# -# wait = loop.create_task(pc.wait(200)) -# loop.run_until_complete(wait) -# -# session = aiohttp.ClientSession(loop=loop) -# request = loop.create_task(pc.SpamRequests(200, session, 0.001)) -# loop.run_until_complete(request) diff --git a/test/requests.http b/test/requests.http deleted file mode 100644 index fb1cb22..0000000 --- a/test/requests.http +++ /dev/null @@ -1,243 +0,0 @@ -GET http://127.0.0.1:8000/objects - -### - -GET http://127.0.0.1:8015/objects/OBJ-Environment/OBJ-200ae749-2d95-452f-a27e-70ec83f440a2 - -### Test read - -GET http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-200ae749-2d95-452f-a27e-70ec83f440a2/PAR-Mac - -### Test asnyc function call -POST http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-200ae749-2d95-452f-a27e-70ec83f440a2/FUN-MeasureRMS -content-type: application/json - -{ - "arguments": [{"value": 5, "uuid": "PAR-Interval"}] -} - - -### Test not implemented write -POST http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-200ae749-2d95-452f-a27e-70ec83f440a2/PAR-Mac -content-type: application/json - -{ - "value": "AC-DE-48-00-00-88" -} - -### Test implemented write -POST http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-200ae749-2d95-452f-a27e-70ec83f440a2/PAR-Location -content-type: application/json - -{ - "value": "Aachen" -} - -### Test changed value -GET http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-200ae749-2d95-452f-a27e-70ec83f440a2/PAR-Location - - -### Test deleting a sensor -DELETE http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-836562ce-9dc5-408d-8296-8cc22c594f72 -content-type: application/json - -{ - "args": ["AE-DE-48-00-00-80"], - "kwargs": {} -} - -### Try get the new sensor -GET http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-3f4cfad3-fe41-497b-b31c-e93babf9d0c4 - - -### Try adding a new sensor -PUT http://127.0.0.1:8000/objects/OBJ-Environment/OBJ-3f4cfad3-fe41-497b-b31c-e93babf9d0c4 -content-type: application/json - -{ - "class_name": "Sensor", - "json_file": { - "uuid": "OBJ-3f4cfad3-fe41-497b-b31c-e93babf9d0c4", - "name": "Sensor 3f4cfad3-fe41-497b-b31c-e93babf9d0c4", - "description": "An individual Sensor of the distributed system with ID 3f4cfad3-fe41-497b-b31c-e93babf9d0c4.", - "variables": [ - { - "uuid": "VAR-Temperature", - "name": "Temperature (*C)", - "description": "Most recently measured temperature in degree celsius", - "datatype": "double", - "value": null, - "dimension": [], - "range": [], - "unit": "CEL" - }, - { - "uuid": "VAR-Humidity", - "name": "Humidity (Percent)", - "description": "Most recently measured humidity in percent", - "datatype": "double", - "value": null, - "range": [ - 0, - 100 - ], - "dimension": [], - "unit": "" - }, - { - "uuid": "VAR-Pressure", - "name": "Pressure (hPa)", - "description": "Most recently measured pressure in hPa", - "datatype": "double", - "value": null, - "range": [], - "dimension": [], - "unit": "A97" - }, - { - "uuid": "VAR-Battery", - "name": "Batterylevel (Percent)", - "description": "Estimated battery level in percent", - "datatype": "int", - "value": null, - "range": [ - 0, - 100 - ], - "dimension": [], - "unit": "" - }, - { - "uuid": "VAR-Signal", - "name": "Signal strength", - "description": "Signal strength in percent", - "datatype": "int", - "value": null, - "range": [ - 0, - 100 - ], - "dimension": [], - "unit": "" - } - ], - "parameters": [ - { - "uuid": "PAR-Mac", - "name": "MAC-Adress", - "description": "Bluetooth MAC-Address of the sensor ", - "datatype": "string", - "value": "AC-DE-48-00-00-80", - "dimension": [], - "range": [] - }, - { - "uuid": "PAR-Interval", - "name": "Refresh Interval (s)", - "description": "Current refresh interval in seconds", - "datatype": "int", - "value": null, - "range": [ - 0, - 100 - ], - "dimension": [] - }, - { - "uuid": "PAR-Location", - "name": "Location", - "description": "Description of the location of the sensor", - "datatype": "string", - "value": "undefined", - "range": [ - null, - 20 - ], - "dimension": [] - }, - { - "uuid": "PAR-Contacted", - "name": "Contacted", - "description": "Flag whether the temperature is measured contacted (true) or ambient (false)", - "datatype": "bool", - "value": true, - "range": [], - "dimension": [] - } - ], - "functions": [ - { - "uuid": "FUN-Refresh", - "name": "Trigger Refresh", - "description": "Manually triggers refresh of the sensors", - "arguments": [], - "returns": [] - }, - { - "uuid": "FUN-MeasureRMS", - "name": "Measure RMS", - "description": "Measures the RMS over a given period of time for this sensor.", - "arguments": [ - { - "uuid": "PAR-Interval", - "name": "Interval (s)", - "description": "Interval in seconds over which to take RMS.", - "datatype": "int", - "value": 1, - "range": [ - 1, - null - ], - "dimension": [] - } - ], - "returns": [ - { - "uuid": "PAR-Count", - "name": "Count", - "description": "Number of values used for RMS estimation", - "datatype": "int", - "value": null, - "range": [], - "dimension": [] - }, - { - "uuid": "PAR-RMS", - "name": "RMS (*C)", - "description": "Estimated RMS form measurement sequence", - "datatype": "double", - "value": null, - "range": [], - "dimension": [] - }, - { - "uuid": "PAR-Mean", - "name": "Mean (*C)", - "description": "Mean of RMS estimation sequence (*C)", - "datatype": "double", - "value": null, - "range": [], - "dimension": [] - } - ] - } - ], - "objects": [] - }, - "args": ["AC-DE-48-00-7F-80"], - "kwargs": {} -} - - -### Test implemented write -POST http://127.0.0.1:8000/objects/OBJ-Environment/FUN-StartTemperatureMeasurementJob -content-type: application/json - -{ - "arguments": [ - {"value": ["1", "2", "3", "4", "5", "6"], "uuid": "PAR-Addresses"}, - {"value": "asdf", "uuid": "PAR-MeasurementJobID"}, - {"value": 1, "uuid": "PAR-TimeInterval"}, - {"value": 0, "uuid": "PAR-NrOfCycles"} - ] -} \ No newline at end of file diff --git a/test/server/__init__.py b/test/server/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/test/server/main.py b/test/server/main.py deleted file mode 100644 index 5162fbb..0000000 --- a/test/server/main.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- -import os -import sys - -import toml as toml - -sys.path.insert(0, os.path.abspath(os.path.join('..', '..', 'examples', 'virtual_lasertracker'))) -sys.path.insert(0, os.path.abspath(os.path.join('..', '..'))) - -from start import start -from hwc.com_lasertracker import COMLasertracker -from lt_device import LTDevice - -if __name__ == "__main__": - - config = toml.load('server_config.toml') - soil_model_file = os.path.join('../..', 'examples', 'virtual_lasertracker', 'Lasertracker.json') - - device = LTDevice() - lasertracker = COMLasertracker(device) - device.start() - - start(lasertracker, config, soil_model_file) diff --git a/test/server/start.py b/test/server/start.py deleted file mode 100644 index b4c01c1..0000000 --- a/test/server/start.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -import asyncio -import sys -from concurrent.futures import ThreadPoolExecutor -from typing import Dict - -from wzl.mqtt import MQTTPublisher -from wzl.utilities import root_logger - -from src.http.server import HTTPServer -from src.soil.component import Component -from src.soil.event import Event, EventSeverity, EventTrigger -from src.soil.stream import FixedJob, EventJob, UpdateJob, StreamScheduler -from device.enums import StateEnum -from hwc.com_lasertracker import COMLasertracker - -sys.setswitchinterval(0.0005) - - -def start(com_lasertracker: COMLasertracker, config: Dict, soil_model_file: str): - # server settings - address = config['http']['address'] - port = config['http']['port'] - - # mqtt settings - mqtt_host = config['mqtt']['host'] - mqtt_port = config['mqtt']['port'] - mqtt_vhost = config['mqtt']['vhost'] - mqtt_username = config['mqtt']['username'] - mqtt_password = config['mqtt']['password'] - mqtt_ssl = config['mqtt']['ssl'] - mqtt_websockets = config['mqtt']['websockets'] - - main_logger = root_logger.get(__name__) - - # set up servers - executor = ThreadPoolExecutor(max_workers=100) - loop = asyncio.get_event_loop() - loop.set_default_executor(executor) - - # configure mqtt - mqtt = MQTTPublisher(mqtt_username, prefix=mqtt_username) - mqtt.connect(mqtt_host, mqtt_username, mqtt_password, vhost=mqtt_vhost, port=mqtt_port, ssl=mqtt_ssl, - websocket=mqtt_websockets) - - # configure messages - schedule = [] - schedule += [FixedJob("COM-Lasertracker/COM-BaseStations/COM-Base/MEA-Position", 30, - com_lasertracker._com_basestations._com_base.get_mea_position)] - for child0_uuid in com_lasertracker._com_mobileentities._com_target: - schedule += [UpdateJob("COM-Lasertracker/COM-MobileEntities/{}/MEA-Position".format(child0_uuid), - com_lasertracker._com_mobileentities._com_target[child0_uuid].get_mea_position)] - schedule += [UpdateJob("COM-Lasertracker/COM-MobileEntities/{}/MEA-Quaternion".format(child0_uuid), - com_lasertracker._com_mobileentities._com_target[child0_uuid].get_mea_quaternion)] - - # configure events - schedule += [EventJob("COM-Lasertracker/COM-BaseStations/COM-Base/MEA-Distance", 10, - com_lasertracker._com_basestations._com_base.get_mea_distance, - Event(EventSeverity.WARNING, EventTrigger.LARGER, "double", 50, - "The target is distance is large. Uncertainty might be high."))] - schedule += [EventJob("COM-Lasertracker/COM-BaseStations/COM-Base/PAR-State", 10, - com_lasertracker._com_basestations._com_base.get_par_state, - Event(EventSeverity.ERROR, EventTrigger.EQUALS, "enum", StateEnum.ERROR, - "An error occured!"))] - for child0_uuid in com_lasertracker._com_mobileentities._com_target: - schedule += [EventJob("COM-Lasertracker/COM-MobileEntities/{}/PAR-Locked".format(child0_uuid), 10, - com_lasertracker._com_mobileentities._com_target[child0_uuid].get_par_locked, - Event(EventSeverity.WARNING, EventTrigger.EQUALS, "bool", False, - "Target is not locked!"))] - - scheduler = StreamScheduler(loop, schedule, [mqtt], start_immediately=True) - - # configure model - mapping = {} - mapping['COM-Lasertracker'] = {'add': None, 'remove': None} - submapping = mapping['COM-Lasertracker'] - submapping['PAR-State'] = {'getter': com_lasertracker.get_par_state, 'setter': com_lasertracker.set_par_state} - submapping['PAR-Manufacturer'] = {'getter': com_lasertracker.get_par_manufacturer, 'setter': None} - submapping['PAR-Version'] = {'getter': com_lasertracker.get_par_version, 'setter': None} - submapping['PAR-Time'] = {'getter': com_lasertracker.get_par_time, 'setter': com_lasertracker.set_par_time} - submapping['FUN-Reset'] = {'method': com_lasertracker.fun_reset, 'signature': {'arguments': {}, 'returns': []}} - submapping['FUN-Shutdown'] = {'method': com_lasertracker.fun_shutdown, - 'signature': {'arguments': {}, 'returns': []}} - mapping['COM-Lasertracker']['COM-BaseStations'] = {'add': None, 'remove': None} - submapping = mapping['COM-Lasertracker']['COM-BaseStations'] - mapping['COM-Lasertracker']['COM-BaseStations']['COM-Base'] = {'add': None, 'remove': None} - submapping = mapping['COM-Lasertracker']['COM-BaseStations']['COM-Base'] - submapping['MEA-Position'] = com_lasertracker._com_basestations._com_base.get_mea_position - submapping['MEA-Quaternion'] = com_lasertracker._com_basestations._com_base.get_mea_quaternion - submapping['MEA-Azimuth'] = com_lasertracker._com_basestations._com_base.get_mea_azimuth - submapping['MEA-Elevation'] = com_lasertracker._com_basestations._com_base.get_mea_elevation - submapping['MEA-Distance'] = com_lasertracker._com_basestations._com_base.get_mea_distance - submapping['PAR-State'] = {'getter': com_lasertracker._com_basestations._com_base.get_par_state, 'setter': None} - submapping['PAR-Interval'] = {'getter': com_lasertracker._com_basestations._com_base.get_par_interval, - 'setter': com_lasertracker._com_basestations._com_base.set_par_interval} - submapping['FUN-Jog'] = {'method': com_lasertracker._com_basestations._com_base.fun_jog, 'signature': { - 'arguments': {'ARG-Azimuth': 'arg_azimuth', 'ARG-Elevation': 'arg_elevation'}, 'returns': []}} - submapping['FUN-PointTo'] = {'method': com_lasertracker._com_basestations._com_base.fun_pointto, - 'signature': {'arguments': {'ARG-Position': 'arg_position'}, 'returns': []}} - mapping['COM-Lasertracker']['COM-MobileEntities'] = {'add': com_lasertracker._com_mobileentities.add, - 'remove': com_lasertracker._com_mobileentities.remove} - submapping = mapping['COM-Lasertracker']['COM-MobileEntities'] - for child0_uuid in com_lasertracker._com_mobileentities._com_target: - mapping['COM-Lasertracker']['COM-MobileEntities'][child0_uuid] = {'add': None, 'remove': None} - submapping = mapping['COM-Lasertracker']['COM-MobileEntities'][child0_uuid] - submapping['MEA-Position'] = com_lasertracker._com_mobileentities._com_target[child0_uuid].get_mea_position - submapping['MEA-Quaternion'] = com_lasertracker._com_mobileentities._com_target[child0_uuid].get_mea_quaternion - submapping['PAR-State'] = { - 'getter': com_lasertracker._com_mobileentities._com_target[child0_uuid].get_par_state, 'setter': None} - submapping['PAR-Mode'] = {'getter': com_lasertracker._com_mobileentities._com_target[child0_uuid].get_par_mode, - 'setter': None} - submapping['PAR-Type'] = {'getter': com_lasertracker._com_mobileentities._com_target[child0_uuid].get_par_type, - 'setter': None} - submapping['PAR-Locked'] = { - 'getter': com_lasertracker._com_mobileentities._com_target[child0_uuid].get_par_locked, - 'setter': com_lasertracker._com_mobileentities._com_target[child0_uuid].set_par_locked} - submapping['FUN-Reset'] = {'method': com_lasertracker._com_mobileentities._com_target[child0_uuid].fun_reset, - 'signature': {'arguments': {}, 'returns': []}} - submapping['FUN-Trigger'] = { - 'method': com_lasertracker._com_mobileentities._com_target[child0_uuid].fun_trigger, - 'signature': {'arguments': {}, 'returns': []}, 'mqtt_callback': mqtt.publish} - model = Component.load(soil_model_file, mapping['COM-Lasertracker']) - - http = HTTPServer(loop, address, port, model) - - # start servers - main_logger.info("Starting main asynchronous loop") - try: - loop.run_forever() - except: - pass - finally: - loop.close() diff --git a/test/test.py b/test/test.py deleted file mode 100644 index 1ed17d2..0000000 --- a/test/test.py +++ /dev/null @@ -1,108 +0,0 @@ -import json -from typing import Callable, Dict - -import requests - - -def test(request: Callable, url: str, body: Dict = None, expect_success: bool = True): - global nr_success, nr_tests - body = {} if body is None else body - - nr_tests += 1 - if request.__name__ != 'get': - ret = request(url, data=json.dumps(body)) - else: - ret = request(url) - - print('Status-Code: {}'.format(ret.status_code)) - if (expect_success and 200 <= ret.status_code < 300) or (not expect_success and (ret.status_code < 200 or ret.status_code >= 300)): - nr_success += 1 - print('Test {} succeeded.'.format(nr_tests)) - else: - print('Test {} failed.'.format(nr_tests)) - print('\t{} {}'.format(request.__name__.upper(), url)) - print('\tExpected: {}, Got Status-Code: {}'.format('SUCCESS' if expect_success else 'FAILURE', ret.status_code)) - print('\tDescription: {}'.format(ret.text)) - - -if __name__ == '__main__': - nr_tests = 0 - nr_success = 0 - - GET = requests.get - POST = requests.post - PATCH = requests.patch - PUT = requests.put - DELETE = requests.delete - - print("\n########## Test: GET root") - test(GET, 'http://localhost:8015/') - test(GET, 'http://localhost:8015/objects/') - test(GET, 'http://localhost:8015/COM-Environment/') - - print("\n########## Test: optional trailing slash") - test(GET, 'http://localhost:8015/COM-Environment/') - test(GET, 'http://localhost:8015/COM-Environment') - - print("\n########## Test: get asynchronous variable") - test(GET, 'http://localhost:8015/objects/COM-Environment/COM-836562ce-9dc5-408d-8296-8cc22c594f72/MEA-Pressure') - - print("\n########## Test: Set Parameter with POST") - data = {'value': 'Inside'} - test(POST, 'http://localhost:8015/objects/COM-Environment/COM-836562ce-9dc5-408d-8296-8cc22c594f72/PAR-Location', data, False) - - print("\n########## Test: Set Parameter with PATCH") - data = {'value': 'Inside'} - test(PATCH, 'http://localhost:8015/objects/COM-Environment/COM-836562ce-9dc5-408d-8296-8cc22c594f72/PAR-Location', data) - - print("\n########## Test: Call function via POST") - data = {'arguments': [{'uuid': 'ARG-Interval', 'value': 1}]} - test(POST, 'http://localhost:8015/objects/COM-Environment/COM-836562ce-9dc5-408d-8296-8cc22c594f72/FUN-MeasureRMS', data) - - print("\n########## Test: Call function via PATCH") - data = {'arguments': [{'uuid': 'ARG-Interval', 'value': 1}]} - test(PATCH, 'http://localhost:8015/objects/COM-Environment/COM-836562ce-9dc5-408d-8296-8cc22c594f72/FUN-MeasureRMS', data, False) - - print("\n########## Test: Malicious URLS or not existing nodes") - test(GET, 'http://localhost:8015/COM-EnvironmentMEA-Temperature', expect_success=False) - test(GET, 'http://localhost:8015/COM-Environment/MEA-Temperature//', expect_success=False) - test(GET, 'http://localhost:8015/COM-Environment//MEA-Temperature', expect_success=False) - test(GET, 'http://localhost:8015//COM-Environment/MEA-Temperature', expect_success=False) - - print("\n########## Test: Add sensor to the system via PUT") - - with open('./devices/environmental_sensor/Sensor.json') as infile: - json_model = json.load(infile) - # add the sensor - test(PUT, 'http://localhost:8015/COM-Environment/COM-Sensor', body={'class_name': 'Sensor', 'json_file': json_model, 'args': ['AB-CD-EF-01-23'], 'kwargs': {}}) - test(GET, 'http://localhost:8015/COM-Environment/COM-Sensor') - # try to add the sensor again - test(PUT, 'http://localhost:8015/COM-Environment/COM-Sensor', - body={'class_name': 'Sensor', 'json_file': json_model, 'args': ['AB-CD-EF-01-23'], 'kwargs': {}}, expect_success=False) - # try to add a sensor without arguments - test(PUT, 'http://localhost:8015/COM-Environment/COM-Sensor2', - body={'class_name': 'Sensor', 'json_file': json_model, 'args': [], 'kwargs': {}}, expect_success=False) - test(GET, 'http://localhost:8015/COM-Environment/COM-Sensor2', expect_success=False) - - - print("\n########## Test: Deleting objects") - # deleting existing sensor with correct args - test(DELETE, 'http://localhost:8015/COM-Environment/COM-Sensor', body={'args': ['AB-CD-EF-01-23'], 'kwargs': {}}) - test(GET, 'http://localhost:8015/COM-Environment/COM-Sensor', expect_success=False) - # deleting non existing sensor - test(DELETE, 'http://localhost:8015/COM-Environment/COM-Sensor', body={'args': ['AB-CD-EF-01-23'], 'kwargs': {}}, expect_success=False) - # deleting existing sensor with incorrect args - test(DELETE, 'http://localhost:8015/COM-Environment/COM-200ae749-2d95-452f-a27e-70ec83f440a2', body={'args': ['AB-CD-EF-01-23'], 'kwargs': {}}, expect_success=False) - test(GET, 'http://localhost:8015/COM-Environment/COM-200ae749-2d95-452f-a27e-70ec83f440a2') - # deleting non existing sensor without body - test(DELETE, 'http://localhost:8015/COM-Environment/COM-200ae749-2d95-452f-a27e-70ec83f440a2', expect_success=False) - - - print('\n') - print('+------------------- Test Summary --------------------+') - print('|{0:<53}|'.format(' Overall test result: {}'.format('SUCCESS' if nr_success == nr_tests else "FAILURE"))) - print('|{0:<53}|'.format(' Executed tests: {}'.format(nr_tests))) - print('|{0:<53}|'.format(' Successful tests: {0} ({1:> 4.1f} %)'.format(nr_success, nr_success / nr_tests * 100))) - print('|{0:<53}|'.format(' Failed tests: {0} ({1:> 4.1f} %)'.format(nr_tests - nr_success, (nr_tests - nr_success) / nr_tests * 100))) - print('+-----------------------------------------------------+') - print('\n') diff --git a/test/test_variable.py b/test/test_variable.py deleted file mode 100644 index 18c78d7..0000000 --- a/test/test_variable.py +++ /dev/null @@ -1,54 +0,0 @@ -import unittest - -from soil.error import DimensionException, TypeException -from soil import Figure - - -class TestVariable(unittest.TestCase): - values = [4, - [5, 'test', 9], - [[1, [1, 0]], [0, 1]], - [[3.2, 1.4], [1.3]], - [True, False], - [['a', 'b'], ['c', 'd']], - 'test', - [2, 1], - [[[1, 2], [3, 4]], [[5, 6], [7, 8]]], - ['test'], - [5.3], - [12, 0, 0, 3], - "1985-04-12T23:20:50.525368Z", - ["1985-04-12T23:20:50.525368Z", "1985-04-12T23:20:50.525368Z"], - ["1985-04-12T23:20:50.525368Z", 3] - ] - - def test_is_scalar(self): - expectations = [True, False, False, False, False, False, True, False, False, False, False, False, True, False, False] - for value, expectation in zip(self.values, expectations): - self.assertEqual(Figure.is_scalar(value), expectation) - - def test_check_dimension(self): - dimensions = [[], [0], [2, 2], [2, 1], [2, 2], [0], [-1], [], [2, 2, 2], [[0]], 'test', [3], [], [2], [2]] - expectations = [True, True, False, False, False, False, False, False, True, False, False, False, True, True, True] - for value, dimension, expectation in zip(self.values, dimensions, expectations): - if not expectation: - self.assertRaises(DimensionException, Figure.check_dimension, dimension, value) - else: - try: - Figure.check_dimension(dimension, value) - except Exception as e: - self.fail('Check_dimension throwed Exception "{}" with value "{}" and dimension "{}"'.format(e, value, dimension)) - - def test_check_type(self): - datatypes = ['int', 'int', 'string', 'double', 'bool', 'int', 'string', 'double', 'bool', 'int', 'int', 'int', 'time', 'time', 'time'] - expectations = [True, False, False, True, True, False, True, True, False, False, False, True, True, True, False] - for value, datatype, expectation in zip(self.values, datatypes, expectations): - if not expectation: - self.assertRaises(TypeException, Figure.check_type, datatype, value) - else: - try: - Figure.check_type(datatype, value) - except Exception as e: - self.fail('Check_dimension throwed Exception "{}" with value "{}" and datatype "{}"'.format(e, value, datatype)) - - # TODO test check_range \ No newline at end of file -- GitLab