Resolve "Add test to feature develop during #232"

Closes #302 (closed)

Merge request reports

Loading
+0 −1
Changes for src/ztp_server/service/rest_server/ztpServer_plugins/ztp_provisioning_api/Resources.py: 0 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -33,5 +33,4 @@ class config(_Resource):
    @HTTP_AUTH.login_required
    def get(self, config_db : str):
        content = returnConfigFile(config_db)

        return content
+2 −2
Changes for src/ztp_server/service/rest_server/ztpServer_plugins/ztp_provisioning_api/__init__.py: 2 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -14,7 +14,7 @@

from ztp_server.service.rest_server.RestServer import RestServer
from .Resources import (
    Config
    config
)

URL_PREFIX = '/provisioning'
@@ -22,7 +22,7 @@ URL_PREFIX = '/provisioning'
# Use 'path' type since some identifiers might contain char '/' and Flask is unable to recognize them in 'string' type.
RESOURCES = [
    # (endpoint_name, resource_class, resource_url)
    ('api.config',    Config,    '/config/<path:config_db>'),
    ('api.config',    config,    '/config/<path:config_db>'),
]

def register_ztp_provisioning(rest_server : RestServer):
+2 −2
Changes for src/ztp_server/service/ZtpServerServiceServicerImpl.py: 2 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -28,9 +28,9 @@ class ZtpServerServiceServicerImpl(ZtpServerServiceServicer):
        LOGGER.info('Servicer Created')

    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def GetZtpProvisioning(self, request : ProvisioningScriptName, context : grpc.ServicerContext) -> ProvisioningScript:
    def GetProvisioningScript(self, request : ProvisioningScriptName, context : grpc.ServicerContext) -> ProvisioningScript:
        try:
            provisioningPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'data', request.scriptname)
            provisioningPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', request.scriptname)
            with open(provisioningPath, 'r') as provisioning_file:
                provisioning_content = provisioning_file.read()
            return ProvisioningScript(script=provisioning_content)
+28 −0
Changes for src/ztp_server/tests/Constants.py: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Copyright 2022-2025 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.


from common.Constants import ServiceNameEnum
from common.Settings import get_service_baseurl_http, get_service_port_http


USERNAME               = 'admin'
PASSWORD               = 'admin'
LOCAL_HOST             = '127.0.0.1'
MOCKSERVICE_PORT       = 10000
ZTP_SERVICE_PORT       = get_service_port_http(ServiceNameEnum.ZTP_SERVER) + MOCKSERVICE_PORT # avoid privileged ports
ZTP_SERVICE_PREFIX_URL = get_service_baseurl_http(ServiceNameEnum.ZTP_SERVER) or ''
ZTP_SERVICE_BASE_URL   = 'http://{:s}:{:s}@{:s}:{:d}{:s}'.format(
    USERNAME, PASSWORD, LOCAL_HOST, ZTP_SERVICE_PORT, ZTP_SERVICE_PREFIX_URL
)
+132 −0
Changes for src/ztp_server/tests/PrepareTestScenario.py: 132 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Copyright 2022-2025 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 enum, logging, os, pytest, requests, time # subprocess, threading
from typing import Any, Dict, List, Optional, Set, Union

from common.Constants import ServiceNameEnum
from common.Settings import (
    ENVVAR_SUFIX_SERVICE_HOST, ENVVAR_SUFIX_SERVICE_PORT_GRPC,
    ENVVAR_SUFIX_SERVICE_PORT_HTTP, get_env_var_name
)

from common.tools.service.GenericRestServer import GenericRestServer
from ztp_server.service.rest_server.ztpServer_plugins.ztp_provisioning_api import register_ztp_provisioning
from ztp_server.client.ZtpClient import ZtpClient

from .Constants import (
    LOCAL_HOST, MOCKSERVICE_PORT, ZTP_SERVICE_BASE_URL, ZTP_SERVICE_PORT,
    USERNAME, PASSWORD
)

os.environ[get_env_var_name(ServiceNameEnum.ZTP_SERVER, ENVVAR_SUFIX_SERVICE_HOST     )] = str(LOCAL_HOST)
os.environ[get_env_var_name(ServiceNameEnum.ZTP_SERVER, ENVVAR_SUFIX_SERVICE_PORT_HTTP)] = str(ZTP_SERVICE_PORT)

@pytest.fixture(scope='session')
def ztp_server_application():
    _rest_server = GenericRestServer(ZTP_SERVICE_PORT, None, bind_address='127.0.0.1')
    register_ztp_provisioning(_rest_server)
    _rest_server.start()
    time.sleep(1)   # bring time for the server to start
    yield _rest_server
    _rest_server.shutdown()
    _rest_server.join()

@pytest.fixture(scope='session')
def ztp_client():    # pylint: disable=redefined-outer-name
    _client = ZtpClient()
    yield _client
    _client.close()

class RestRequestMethod(enum.Enum):
    GET    = 'get'
    POST   = 'post'
    PUT    = 'put'
    PATCH  = 'patch'
    DELETE = 'delete'

EXPECTED_STATUS_CODES : Set[int] = {
    requests.codes['OK'        ],
    requests.codes['CREATED'   ],
    requests.codes['ACCEPTED'  ],
    requests.codes['NO_CONTENT'],
}

def do_rest_request(
    method : RestRequestMethod, url : str, body : Optional[Any] = None, timeout : int = 10,
    allow_redirects : bool = True, expected_status_codes : Set[int] = EXPECTED_STATUS_CODES,
    logger : Optional[logging.Logger] = None
) -> Optional[Union[Dict, List]]:
    request_url = ZTP_SERVICE_BASE_URL + url
    if logger is not None:
        msg = 'Request: {:s} {:s}'.format(str(method.value).upper(), str(request_url))
        if body is not None: msg += ' body={:s}'.format(str(body))
        logger.warning(msg)
    reply = requests.request(method.value, request_url, timeout=timeout, json=body, allow_redirects=allow_redirects)
    if logger is not None:
        logger.warning('Reply: {:s}'.format(str(reply.text)))
    assert reply.status_code in expected_status_codes, 'Reply failed with status code {:d}'.format(reply.status_code)

    if reply.content and len(reply.content) > 0: return reply.json()
    return None

def do_rest_get_request(
    url : str, body : Optional[Any] = None, timeout : int = 10,
    allow_redirects : bool = True, expected_status_codes : Set[int] = EXPECTED_STATUS_CODES,
    logger : Optional[logging.Logger] = None
) -> Optional[Union[Dict, List]]:
    return do_rest_request(
        RestRequestMethod.GET, url, body=body, timeout=timeout, allow_redirects=allow_redirects,
        expected_status_codes=expected_status_codes, logger=logger
    )

def do_rest_post_request(
    url : str, body : Optional[Any] = None, timeout : int = 10,
    allow_redirects : bool = True, expected_status_codes : Set[int] = EXPECTED_STATUS_CODES,
    logger : Optional[logging.Logger] = None
) -> Optional[Union[Dict, List]]:
    return do_rest_request(
        RestRequestMethod.POST, url, body=body, timeout=timeout, allow_redirects=allow_redirects,
        expected_status_codes=expected_status_codes, logger=logger
    )

def do_rest_put_request(
    url : str, body : Optional[Any] = None, timeout : int = 10,
    allow_redirects : bool = True, expected_status_codes : Set[int] = EXPECTED_STATUS_CODES,
    logger : Optional[logging.Logger] = None
) -> Optional[Union[Dict, List]]:
    return do_rest_request(
        RestRequestMethod.PUT, url, body=body, timeout=timeout, allow_redirects=allow_redirects,
        expected_status_codes=expected_status_codes, logger=logger
    )

def do_rest_patch_request(
    url : str, body : Optional[Any] = None, timeout : int = 10,
    allow_redirects : bool = True, expected_status_codes : Set[int] = EXPECTED_STATUS_CODES,
    logger : Optional[logging.Logger] = None
) -> Optional[Union[Dict, List]]:
    return do_rest_request(
        RestRequestMethod.PATCH, url, body=body, timeout=timeout, allow_redirects=allow_redirects,
        expected_status_codes=expected_status_codes, logger=logger
    )

def do_rest_delete_request(
    url : str, body : Optional[Any] = None, timeout : int = 10,
    allow_redirects : bool = True, expected_status_codes : Set[int] = EXPECTED_STATUS_CODES,
    logger : Optional[logging.Logger] = None
) -> Optional[Union[Dict, List]]:
    return do_rest_request(
        RestRequestMethod.DELETE, url, body=body, timeout=timeout, allow_redirects=allow_redirects,
        expected_status_codes=expected_status_codes, logger=logger
    )
Loading
Loading