messages.py 14.9 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
# -*- 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"}'
Federico Sismondi's avatar
Federico Sismondi committed
46 47 48 49 50 51 52 53 54 55 56

# using it to import json into python objects:
>>> m=MsgTestSuiteStart()
>>> m.to_json()
'{"_type": "testcoordination.testsuite.start", "_api_version": "0.1.1"}'
>>> json_message = m.to_json()
>>> obj=Message.from_json(json_message)
>>> type(obj)
<class 'messages.MsgTestSuiteStart'>


57 58 59 60 61 62 63
"""

from collections import OrderedDict
import json
import uuid
import logging

64
API_VERSION = '0.1.1'
65 66

# TODO use metaclasses instead?
67
# TODO Define also a reply method which provides amessage with routig key for the reply, correlation id, reply_to,etc
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85


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()}

86 87 88 89 90 91 92 93 94 95 96
        # 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']

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        # 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())

120 121
    def get_properties(self) -> dict:
        return self._properties
122

123
    def __str__(self):
124
        str = ' - '*20 + '\n'
125 126 127 128
        str += 'Message routing key: %s' %self.routing_key
        str += '\n'
        str += 'Message properties: %s'%json.dumps(self.get_properties())
        str += '\n'
129 130 131 132 133 134 135 136
        str += 'Message body: %s' %self.to_json()
        str += '\n' + ' - ' * 20
        return str

    @classmethod
    def from_json(cls, body):

        try:
137
            logging.debug('Converting json into a Message object..')
138 139 140 141 142 143 144 145 146

            if type(body) is str:
                message_dict = json.loads(body)

            # Note: pika re-encodes json.dumps strings as utf-8 for some reason, the following line undoes this
            elif type(body) is bytes:
                message_dict = json.loads(body.decode('utf-8'))

            logging.debug('json: %s' % json.dumps(message_dict))
147 148 149 150 151 152
            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))

153 154 155 156 157 158 159 160
    def __repr__(self):

        ret = '%s(' %self.__class__.__name__
        for field in self._msg_data:
            ret += '%s = %s'%(field,getattr(self, field))
        ret += ')'
        return ret

161 162 163 164 165 166 167 168 169

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

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

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

    _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)
    """
183
    routing_key = "control.testcoordination"
184 185 186 187 188 189 190 191 192 193 194 195 196

    _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)
    """

197
    routing_key = 'control.testcoordination'
198 199 200 201 202 203 204 205 206 207 208 209

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


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

210
    routing_key = 'control.testcoordination'
211 212 213 214 215 216 217 218 219 220 221 222 223

    _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
    """

224
    routing_key = 'control.testcoordination'
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

    _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)
    """

240 241
    routing_key = 'control.testcoordination'

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

    _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
    """

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

    _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)
    """

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

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

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

285
    routing_key = 'control.testcoordination'
286 287 288 289 290 291 292 293 294 295 296 297 298

    _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
    """

299
    routing_key = 'control.testcoordination'
300 301 302 303 304 305 306 307 308 309 310 311

    _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
    """

312
    routing_key = 'control.testcoordination'
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

    _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
    """

329
    routing_key = 'control.testcoordination.service'
330 331 332 333 334 335 336 337 338 339 340 341

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

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

342
    routing_key = 'control.testcoordination.service'
343 344 345 346 347 348 349 350 351 352 353 354 355 356

    _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)
    """

357
    routing_key = 'control.sniffing.service'
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

    _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)
    """

373
    routing_key = 'control.sniffing.service'
374 375 376 377 378 379 380 381 382 383 384 385

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

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

386
    routing_key = 'control.sniffing.service'
387 388 389 390 391 392 393 394

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

    }

395 396 397 398 399 400 401
class MsgSniffingGetCaptureLast(Message):
    """
    Testing Tools'internal call.
    Coordinator -> Sniffer
    Testing Tool SHOULD implement (design recommendation)
    """

402
    routing_key ='control.sniffing.service'
403 404 405 406

    _msg_data_template = {
        '_type': 'sniffing.getlastcapture',
    }
407 408 409 410 411 412 413 414 415 416 417 418

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

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

    PCAP_empty_base64 = '1MOyoQIABAAAAAAAAAAAAMgAAAAAAAAA'

419
    routing_key = 'control.analysis.service'
420 421 422 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

    _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=="

448
    routing_key = 'control.dissection.service'
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

    _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._msg_data)
494 495 496 497 498
    j = m1.to_json()
    print(j)
    deco = Message.from_json(j)
    print(repr(deco))

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525

    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)