Commit 4c4d91e1 authored by Lluis Gifre Renom's avatar Lluis Gifre Renom
Browse files

NBI component:

- Added new test resources and namespaces
- Added standalone test
parent 3cbdaf3d
Loading
Loading
Loading
Loading

run_test_nbi.sh

0 → 100755
+20 −0
Original line number Diff line number Diff line
#!/bin/bash
# Copyright 2022-2024 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# 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.

export PYTHON_PATH=./src
export LOG_LEVEL=DEBUG
export FLASK_ENV=development

python -m pytest --log-level=DEBUG -o log_cli=true --verbose src/nbi/mytest/pytest_code.py
+2 −2
Original line number Diff line number Diff line
@@ -89,5 +89,5 @@ RUN mkdir -p /var/teraflow/tests/tools
COPY src/tests/tools/mock_osm/. tests/tools/mock_osm/

# Start the service
#ENTRYPOINT ["gunicorn", "-w", "4", "--worker-class", "eventlet", "-b", "0.0.0.0:8080", "nbi.service:nbi_app"]
ENTRYPOINT ["gunicorn", "-w", "4", "--worker-class", "geventwebsocket.gunicorn.workers.GeventWebSocketWorker", "-b", "0.0.0.0:8080", "nbi.service.app:app"]
ENTRYPOINT ["gunicorn", "-w", "4", "--worker-class", "eventlet", "-b", "0.0.0.0:8080", "nbi.service.app:app"]
#ENTRYPOINT ["gunicorn", "-w", "4", "--worker-class", "geventwebsocket.gunicorn.workers.GeventWebSocketWorker", "-b", "0.0.0.0:8080", "nbi.service.app:app"]
+105 −0
Original line number Diff line number Diff line
# Copyright 2022-2024 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# 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.

import eventlet, eventlet.wsgi, json, logging, os, pytest, requests, threading, time
import websockets.sync.client  # Import synchronous WebSocket client
from nbi.service.NbiApplication import NbiApplication
from nbi.service.rest_server.nbi_plugins import register_restconf
from nbi.service.restapi_resources.health_probes import register_health_probes
from nbi.service.websocket_namespaces.hearthbeat import register_heartbeat



logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

LOCAL_HOST             = '127.0.0.1'
NBI_SERVICE_PORT       = 18080
NBI_SERVICE_PREFIX_URL = ''
NBI_SERVICE_BASE_URL   = '{:s}:{:d}{:s}'.format(LOCAL_HOST, NBI_SERVICE_PORT, NBI_SERVICE_PREFIX_URL)

class ServerThread(threading.Thread):
    def __init__(self):
        super().__init__(daemon=True)

        self.nbi_app = NbiApplication(base_url=NBI_SERVICE_PREFIX_URL)
        register_health_probes(self.nbi_app)
        register_heartbeat    (self.nbi_app)
        register_restconf     (self.nbi_app)
        self.nbi_app.dump_configuration()

    def run(self):
        try:
            #eventlet.wsgi.server(
            #    eventlet.listen((LOCAL_HOST, NBI_SERVICE_PORT)),
            #    self.nbi_app.get_flask_app(),
            #    debug=True, log_output=True
            #)
            #thread = eventlet.spawn(
            #    self.nbi_app._sio.run, self.nbi_app.get_flask_app(),
            #    host=LOCAL_HOST, port=NBI_SERVICE_PORT,
            #    debug=True, use_reloader=False
            #)
            #thread.wait()
            self.nbi_app._sio.run(
                self.nbi_app.get_flask_app(),
                host=LOCAL_HOST, port=NBI_SERVICE_PORT,
                debug=True, use_reloader=False
            )
        except:
            LOGGER.exception('unhandled')

@pytest.fixture(scope='session')
def nbi_application() -> NbiApplication:
    thread = ServerThread()
    thread.start()
    time.sleep(1)
    yield thread.nbi_app
    thread.join(timeout=1)

def test_restapi_get_healthz(
    nbi_application : NbiApplication    # pylint: disable=redefined-outer-name, unused-argument
) -> None:
    request_url = 'http://' + NBI_SERVICE_BASE_URL + '/healthz'
    LOGGER.warning('Request: GET {:s}'.format(str(request_url)))
    reply = requests.request('get', request_url, timeout=10, allow_redirects=True)
    LOGGER.warning('Reply: {:s}'.format(str(reply.text)))
    assert reply.status_code == requests.codes['OK'], 'Reply failed with status code {:d}'.format(reply.status_code)
    if reply.content and len(reply.content) > 0: return reply.json()

def test_websocket_get_heartbeat(
    nbi_application : NbiApplication    # pylint: disable=redefined-outer-name, unused-argument
) -> None:
    nbi_application.dump_configuration()
    request_url = 'ws://' + NBI_SERVICE_BASE_URL + '/heartbeat'
    LOGGER.warning('Request: WS {:s}'.format(str(request_url)))

    heartbeat_count = 0
    with websockets.sync.client.connect(request_url) as ws:
        while heartbeat_count < 5:
            message = ws.recv()
            LOGGER.warning('Received message: {:s}'.format(str(message)))

            data = json.loads(message)

            # Validate uptime response
            assert "uptime_seconds" in data, "Missing 'uptime_seconds' in response"
            assert isinstance(data["uptime_seconds"], (int, float)), "'uptime_seconds' is not a number"

            heartbeat_count += 1
            LOGGER.warning('--> Heartbeat #{:d}: {:s}'.format(heartbeat_count, str(data)))

    LOGGER.warning('Test completed')
    raise Exception()
+20 −0
Original line number Diff line number Diff line
# Copyright 2022-2024 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# 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.

eventlet==0.39.0
Flask==2.1.3
Flask-HTTPAuth==4.5.0
Flask-RESTful==0.3.9
flask-socketio==5.5.1
gunicorn==23.0.0
+3 −3
Original line number Diff line number Diff line
@@ -20,9 +20,9 @@ Flask-HTTPAuth==4.5.0
Flask-RESTful==0.3.9
flask-socketio==5.5.1
jsonschema==4.4.0
gevent==24.11.1
gevent-websocket==0.10.1
greenlet==3.1.1
#gevent==24.11.1
#gevent-websocket==0.10.1
#greenlet==3.1.1
gunicorn==23.0.0
libyang==2.8.4
netaddr==0.9.0
Loading