messages.py 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
# -*- coding: utf-8 -*-

"""
This module provides the API message formats used in F-Interop.

The idea is to be able to have an
- organized and centralized way of dealing with the big amount of messages formats used in the platform;
- to be able to import (or just copy/paste) these messages formats from any component in the F-Interop platform,
- re-use this also for the integration testing;
- to have version control the messages e.g. messages_testcase_start API v1 and API v2;
- to have a direct way of exporting this as doc.

Usage:
------
>>> from messages import *
>>> m = MsgTestCaseSkip()
>>> print(m)
 -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - - -
Message representation:
 - - -
routing_key / topic : control.testcoordination
 - - -
_type : testcoordination.testcase.skip
testcase_id : TD_COAP_CORE_02_v01
 -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - - -
>>> m.routing_key
'control.testcoordination'
>>> m.testcase_id
'TD_COAP_CORE_02_v01'
# also we can modify some of the fields (rewrite the default ones)
>>> m = MsgTestCaseSkip(testcase_id = 'TD_COAP_CORE_03_v01')
>>> m
 -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - - -
Message representation:
 - - -
routing_key / topic : control.testcoordination
 - - -
_type : testcoordination.testcase.skip
testcase_id : TD_COAP_CORE_03_v01
 -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - - -
>>> m.testcase_id
'TD_COAP_CORE_03_v01'
# and even export the message in json format (for example for sending the message though the amqp event bus)
>>> m.to_json()
'{"_type": "testcoordination.testcase.skip", "testcase_id": "TD_COAP_CORE_03_v01"}'
"""

from collections import OrderedDict
import json
import uuid
import logging

53
API_VERSION = '0.1.0'
54 55

# TODO use metaclasses instead?
56
# TODO Define also a reply method which provides amessage with routig key for the reply, correlation id, reply_to,etc
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74


class NonCompliantMessageFormatError(Exception):

    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class Message:

    def __init__(self,**kwargs):
        global API_VERSION

        # hard copy the message template
        self._msg_data = {k:v for k,v in self._msg_data_template.items()}

75 76 77 78 79 80 81 82 83 84 85
        # init properties
        self._properties = dict(
                content_type='application/json',
                message_id=str(uuid.uuid4()),
        )

        #if message is a service request then add some extra props
        if self.routing_key.endswith('.service'):
            self._properties['reply_to'] = '%s.%s'%(self.routing_key,'reply')
            self._properties['correlation_id'] = self._properties['message_id']

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        # rewrite default metadata and data fields of the message instance
        self._msg_data.update(kwargs)

        # add API's version
        self._msg_data['_api_version'] = API_VERSION

        # add values as objects attributes
        for key in self._msg_data:
            setattr(self, key, self._msg_data[key])


    def to_dict(self) -> OrderedDict:
        resp = OrderedDict()
        for field in self._msg_data:
            resp[field] = getattr(self, field)
        # for readability
        resp.move_to_end('_type',False)

        return resp

    def to_json(self):
        return json.dumps(self.to_dict())

109 110
    def get_properties(self) -> dict:
        return self._properties
111

112
    def __str__(self):
113
        str = ' - '*20 + '\n'
114 115 116 117
        str += 'Message routing key: %s' %self.routing_key
        str += '\n'
        str += 'Message properties: %s'%json.dumps(self.get_properties())
        str += '\n'
118 119 120 121 122 123 124 125
        str += 'Message body: %s' %self.to_json()
        str += '\n' + ' - ' * 20
        return str

    @classmethod
    def from_json(cls, body):

        try:
126 127 128
            logging.debug('Converting json into a Message object..')
            message_dict = json.loads(body.decode('utf-8'))
            logging.debug('json: %s' %json.dumps(message_dict))
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
            message_type = message_dict['_type']
            if message_type in _message_types_dict:
                return _message_types_dict[message_type](**message_dict)
        except :
            raise NonCompliantMessageFormatError('Cannot load json message: %s'%str(body))


###### TEST COORDINATION MESSAGES ######

class MsgTestSuiteStart(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI -> Testing Tool
    """

144
    routing_key = "control.testcoordination"
145 146 147 148 149 150 151 152 153 154 155 156

    _msg_data_template = {
        '_type': "testcoordination.testsuite.start",
    }


class MsgTestCaseStart(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI -> Testing Tool
    Message used for indicating the testing tool to start the test case (the one previously selected)
    """
157
    routing_key = "control.testcoordination"
158 159 160 161 162 163 164 165 166 167 168 169 170

    _msg_data_template = {
        '_type': "testcoordination.testcase.start",
    }


class MsgTestCaseStop(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI -> Testing Tool
    Message used for indicating the testing tool to stop the test case (the one running)
    """

171
    routing_key = 'control.testcoordination'
172 173 174 175 176 177 178 179 180 181 182 183

    _msg_data_template = {
        '_type': 'testcoordination.testcase.stop',
    }


class MsgTestCaseRestart(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI -> Testing Tool
    """

184
    routing_key = 'control.testcoordination'
185 186 187 188 189 190 191 192 193 194 195 196 197

    _msg_data_template = {
        '_type': 'testcoordination.testcase.restart',
    }

#TODO step.execute event

class MsgStimuliExecuted(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI (or automated-IUT)-> Testing Tool
    """

198
    routing_key = 'control.testcoordination'
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    _msg_data_template = {
        '_type': 'testcoordination.step.stimuli.executed',
    }


class MsgCheckResponse(Message):
    """
    Testing Tools'internal call.
    In the context of IUT to IUT test execution, this message is used for indicating that the previously executed
    messages (stimuli message and its reply) CHECK or comply to what is described in the Test Description.
    Testing tools' coordinator -> Testing Tool's analyzer (TAT)
    Not used in CoAP testing Tool (analysis of traces is done post mortem)
    """

214 215
    routing_key = 'control.testcoordination'

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

    _msg_data_template = {
        '_type': 'testcoordination.step.check.response',
        'partial_verdict':'pass',
        'description':'TAT says: step complies (checks) with specification'
    }


class MsgVerifyResponse(Message):
    """
    Testing Tool MUST-implement API endpoint
    Message provided by user declaring if the IUT VERIFY the step previously executed as described in the Test
    Description.
    GUI (or automated-IUT)-> Testing Tool
    """

232
    routing_key = 'control.testcoordination'
233 234 235 236 237 238 239 240 241 242 243 244 245 246

    _msg_data_template = {
        '_type': 'testcoordination.step.verify.response',
        'verify_response': True,
        'response_type': 'bool'
    }

class MsgTestCaseFinish(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI (or automated-IUT)-> Testing Tool
    Not used in CoAP Testing Tool (test coordinator deduces it automatically by using the testcase's step sequence)
    """

247
    routing_key = 'control.testcoordination'
248 249 250 251 252 253 254 255 256 257 258

    _msg_data_template = {
        '_type': 'testcoordination.testcase.finish',
    }

class MsgTestCaseSkip(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI (or automated-IUT)-> Testing Tool
    """

259
    routing_key = 'control.testcoordination'
260 261 262 263 264 265 266 267 268 269 270 271 272

    _msg_data_template = {
        '_type': 'testcoordination.testcase.skip',
        'testcase_id': 'TD_COAP_CORE_02_v01',
    }


class MsgTestCaseSelect(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI (or automated-IUT)-> Testing Tool
    """

273
    routing_key = 'control.testcoordination'
274 275 276 277 278 279 280 281 282 283 284 285

    _msg_data_template = {
        '_type': 'testcoordination.testcase.select',
        'testcase_id': 'TD_COAP_CORE_03_v01',
    }

class MsgTestSuiteAbort(Message):
    """
    Testing Tool MUST-implement API endpoint
    GUI (or automated-IUT)-> Testing Tool
    """

286
    routing_key = 'control.testcoordination'
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

    _msg_data_template = {
        '_type': 'testcoordination.testsuite.abort',
    }

class MsgTestSuiteGetStatus(Message):
    """
    Testing Tool SHOULD-implement API entrypoint
    Describes current state of the test suite.
    Format for the response not standardised.

    GUI -> Testing Tool

    GUI MUST implement
    """

303
    routing_key = 'control.testcoordination.service'
304 305 306 307 308 309 310 311 312 313 314 315

    _msg_data_template = {
        '_type': 'testcoordination.testsuite.getstatus',
    }

class MsgTestSuiteGetTestCases(Message):
    """
    Testing Tool's MUST-implement API entrypoint
    GUI -> Testing Tool
    GUI MUST implement
    """

316
    routing_key = 'control.testcoordination.service'
317 318 319 320 321 322 323 324 325 326 327 328 329 330

    _msg_data_template = {
        '_type': 'testcoordination.testsuite.gettestcases',
    }

###### SNIFFING SERVICES REQUEST MESSAGES ######

class MsgSniffingStart(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Sniffer
    Testing Tool SHOULD implement (design recommendation)
    """

331
    routing_key = 'control.sniffing.service'
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

    _msg_data_template = {
        '_type': 'sniffing.start',
        'capture_id': 'TD_COAP_CORE_01',
        'filter_if': 'tun0',
        'filter_proto': 'udp port 5683'
    }

class MsgSniffingStop(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Sniffer
    Testing Tool SHOULD implement (design recommendation)
    """

347
    routing_key = 'control.sniffing.service'
348 349 350 351 352 353 354 355 356 357 358 359

    _msg_data_template = {
        '_type': 'sniffing.stop',
    }

class MsgSniffingGetCapture(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Sniffer
    Testing Tool SHOULD implement (design recommendation)
    """

360
    routing_key = 'control.sniffing.service'
361 362 363 364 365 366 367 368

    _msg_data_template = {
        '_type': 'sniffing.getcapture',
        "get_last": False,
        "capture_id": "TD_COAP_CORE_01",

    }

369 370 371 372 373 374 375
class MsgSniffingGetCaptureLast(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Sniffer
    Testing Tool SHOULD implement (design recommendation)
    """

376
    routing_key ='control.sniffing.service'
377 378 379 380

    _msg_data_template = {
        '_type': 'sniffing.getlastcapture',
    }
381 382 383 384 385 386 387 388 389 390 391 392

###### ANALYSIS SERVICES REQUESTS MESSAGES ######

class MsgAnalysisTestCaseAnalyze(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Analyzer
    Testing Tool SHOULD implement (design recommendation)
    """

    PCAP_empty_base64 = '1MOyoQIABAAAAAAAAAAAAMgAAAAAAAAA'

393
    routing_key = 'control.analysis.service'
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

    _msg_data_template = {
        '_type': 'analysis.testcase.analyze',
        "testcase_id": "TD_COAP_CORE_01",
        "testcase_ref": "http://f-interop.paris.inria.fr/tests/TD_COAP_CORE_01_v01",
        "file_enc": "pcap_base64",
        "filename": "TD_COAP_CORE_01.pcap",
        "value": PCAP_empty_base64,
    }

###### DISSECTION SERVICES REQUESTS MESSAGES ######
class MsgDissectionDissectCapture(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Dissector
    and
    Analyzer -> Dissector
    Testing Tool SHOULD implement (design recommendation)
    """

    PCAP_COAP_GET_OVER_TUN_INTERFACE_base64 = "1MOyoQIABAAAAAAAAAAAAMgAAABlAAAAqgl9WK8aBgA7AAAAOwAAAGADPxUAExFAu7s" \
                                              "AAAAAAAAAAAAAAAAAAbu7AAAAAAAAAAAAAAAAAALXvBYzABNZUEABcGO0dGVzdMECqg" \
                                              "l9WMcaBgCQAAAAkAAAAGAAAAAAaDr//oAAAAAAAAAAAAAAAAAAA7u7AAAAAAAAAAAAA" \
                                              "AAAAAGJAAcTAAAAALu7AAAAAAAAAAAAAAAAAAK7uwAAAAAAAAAAAAAAAAACBAgAAAAA" \
                                              "AABgAz8VABMRQLu7AAAAAAAAAAAAAAAAAAG7uwAAAAAAAAAAAAAAAAAC17wWMwATWVB" \
                                              "AAXBjtHRlc6oJfVjSGgYAOwAAADsAAABgAz8VABMRP7u7AAAAAAAAAAAAAAAAAAG7uw" \
                                              "AAAAAAAAAAAAAAAAAC17wWMwATWVBAAXBjtHRlc3TBAg=="

422
    routing_key = 'control.dissection.service'
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

    _msg_data_template = {
        '_type': 'dissection.dissectcapture',
        "file_enc": "pcap_base64",
        "filename": "TD_COAP_CORE_01.pcap",
        "value": PCAP_COAP_GET_OVER_TUN_INTERFACE_base64,
        "protocol_selection": 'coap',
    }


_message_types_dict = {
    "testcoordination.testsuite.start": MsgTestSuiteStart,
    "testcoordination.testcase.start": MsgTestCaseStart,
    "testcoordination.testcase.stop": MsgTestCaseStop,
    "testcoordination.testcase.restart": MsgTestCaseRestart,
    "testcoordination.step.stimuli.executed": MsgStimuliExecuted,
    "testcoordination.step.check.response": MsgCheckResponse,
    "testcoordination.step.verify.response": MsgVerifyResponse,
    "testcoordination.testcase.finish": MsgTestCaseFinish,
    "testcoordination.testcase.skip": MsgTestCaseSkip,
    "testcoordination.testcase.select": MsgTestCaseSelect,
    "testcoordination.testsuite.abort": MsgTestSuiteAbort,
    "testcoordination.testsuite.getstatus": MsgTestSuiteGetStatus,
    "testcoordination.testsuite.gettestcases": MsgTestSuiteGetTestCases,
    "sniffing.start": MsgSniffingStart,
    "sniffing.stop": MsgSniffingStop,
    "sniffing.getcapture": MsgSniffingGetCapture,
    "analysis.testcase.analyze": MsgAnalysisTestCaseAnalyze,
    "dissection.dissectcapture": MsgDissectionDissectCapture,
}


if __name__ == '__main__':
    # m1=MsgTestCaseStart()
    # print(json.dumps(m1.to_dict()))
    # print(m1.routing_key)
    # print(m1.to_json())
    # print(m1)

    m1 = MsgTestCaseStart( hola = 'verano')
    m2 = MsgTestCaseStart()
    #m2 = MsgTestCaseStart(routing_key = 'lolo', hola='verano')

    print(m1)
    print(m1.to_json())
    print(m1._msg_data)

    print(m2)
    print(m2.to_json())
    print(m2._msg_data)
    #
    # m2=MsgTestSuiteStart()
    # print(json.dumps(m2.to_dict()))
    # print(m2.routing_key)
    # print(m2.to_json())
    # print(m2)
    #
    # m3=MsgTestCaseStop()
    # print(json.dumps(m3.to_dict()))
    # print(m3.routing_key)
    # print(m3.to_json())
    # print(m3)

    j = json.dumps({
        '_type': 'dissection.dissectcapture',
        "file_enc": "pcap_base64",
        "filename": "TD_COAP_CORE_01.pcap",
        "protocol_selection": 'coap',
    })
    r = Message.from_json(j)
    print(type(r))
    print(r)