messages.py 53.4 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-

"""
4 5 6 7

About the library:
-----------------

8 9 10 11 12 13 14 15 16
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.

17 18 19 20 21 22 23 24

F-Interop conventions:
---------------------
- if event is a service request then the routing key (r_key) is control.someFunctionality.service
- a reply to a service will be on topic/r_key : control.someFunctionality.service.reply
- reply.correlation_id = request.correlation_id


25 26
Usage:
------
27
>>> from messages import * # doctest: +SKIP
28
>>> m = MsgTestCaseSkip()
29
>>> m
30
MsgTestCaseSkip(_api_version = 0.1.29, _type = testcoordination.testcase.skip, testcase_id = TD_COAP_CORE_02_v01, )
31 32
>>> m.routing_key
'control.testcoordination'
33 34
>>> m.message_id # doctest: +SKIP
'802012eb-24e3-45c4-9dcc-dc293c584f63'
35 36
>>> m.testcase_id
'TD_COAP_CORE_02_v01'
37

38 39 40
# also we can modify some of the fields (rewrite the default ones)
>>> m = MsgTestCaseSkip(testcase_id = 'TD_COAP_CORE_03_v01')
>>> m
41
MsgTestCaseSkip(_api_version = 0.1.29, _type = testcoordination.testcase.skip, testcase_id = TD_COAP_CORE_03_v01, )
42 43
>>> m.testcase_id
'TD_COAP_CORE_03_v01'
44

45 46
# and even export the message in json format (for example for sending the message though the amqp event bus)
>>> m.to_json()
47
'{"_api_version": "0.1.29", "_type": "testcoordination.testcase.skip", "testcase_id": "TD_COAP_CORE_03_v01"}'
Federico Sismondi's avatar
Federico Sismondi committed
48

49
# We can use the Message class to import json into Message objects:
Federico Sismondi's avatar
Federico Sismondi committed
50 51
>>> m=MsgTestSuiteStart()
>>> m.to_json()
52
'{"_api_version": "0.1.29", "_type": "testcoordination.testsuite.start"}'
Federico Sismondi's avatar
Federico Sismondi committed
53 54 55
>>> json_message = m.to_json()
>>> obj=Message.from_json(json_message)
>>> type(obj)
56
<class 'messages.MsgTestSuiteStart'>
57

58
# We can use the library for generating error responses:
59 60 61 62 63 64
# the request:
>>> m = MsgSniffingStart()
>>>
# the error reply (note that we pass the message of the request to build the reply):
>>> err = MsgErrorReply(m)
>>> err
65
MsgErrorReply(_api_version = 0.1.29, _type = sniffing.start, error_code = Some error code TBD, error_message = Some error message TBD, ok = False, )
66 67 68 69 70 71 72 73 74
>>> m.reply_to
'control.sniffing.service.reply'
>>> err.routing_key
'control.sniffing.service.reply'

>>> m.correlation_id # doctest: +SKIP
'360b0f67-4455-43e3-a00f-eca91f2e84da'
>>> err.correlation_id # doctest: +SKIP
'360b0f67-4455-43e3-a00f-eca91f2e84da'
Federico Sismondi's avatar
Federico Sismondi committed
75

76 77 78
"""

from collections import OrderedDict
79
import time
80 81 82
import json
import uuid

83
API_VERSION = '0.1.30'
84

85 86 87 88 89 90 91 92 93 94 95

# TODO use metaclasses instead?

class NonCompliantMessageFormatError(Exception):
    def __init__(self, value):
        self.value = value

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


96 97
class Message:
    def __init__(self, **kwargs):
98 99 100
        global API_VERSION

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

103 104
        # init properties
        self._properties = dict(
105
                content_type="application/json",
106
                message_id=str(uuid.uuid4()),
107
                timestamp=int(time.time())
108 109
        )

110
        try:
111 112 113
            if self.routing_key.endswith(".service"):
                self._properties["reply_to"] = "%s.%s" % (self.routing_key, "reply")
                self._properties["correlation_id"] = self._properties["message_id"]
114
        except AttributeError:
115
            pass
116

117
        # rewrite default data fields with the passed args
118 119 120
        self._msg_data.update(kwargs)

        # add API's version
121
        self._msg_data["_api_version"] = API_VERSION
122 123 124 125 126

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

127 128 129 130
        # add props as objects attributes
        for key in self._properties:
            setattr(self, key, self._properties[key])

131 132
    def to_dict(self):
        resp = {}
133 134
        # let's use sorted so API returns items inside always in the same order
        for field in sorted(self._msg_data.keys()):
135
            resp[field] = getattr(self, field)
136

137
        return OrderedDict(sorted(resp.items(), key=lambda t: t[0]))  # sorted by key
138 139 140 141

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

142
    def get_properties(self):
143 144 145 146
        resp = OrderedDict()
        for field in self._properties:
            resp[field] = getattr(self, field)
        return resp
147

148
    def __str__(self):
149 150 151 152 153 154 155
        s = " - " * 20 + "\n"
        s += "Message routing key: %s" % self.routing_key
        s += "\n -  -  - \n"
        s += "Message properties: %s" % json.dumps(self.get_properties(), indent=4, )
        s += "\n -  -  - \n"
        s += "Message body: %s" % json.dumps(self.to_dict(), indent=4, )
        s += "\n" + " - " * 20
156
        return s
157

158 159 160 161 162
    def update_properties(self, **kwargs):
        for key, value in kwargs.items():
            if key in self._properties:
                setattr(self, key, value)

163 164
    @classmethod
    def from_json(cls, body):
165 166 167 168 169 170 171 172 173 174
        """
        :param body: json string or string encoded as utf-8
        :return:  Message object generated from the body
        :raises NonCompliantMessageFormatError: If the message cannot be build from the provided json
        """

        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:
175
            message_dict = json.loads(body.decode("utf-8"))
176
        else:
177
            raise NonCompliantMessageFormatError("Not a Json")
178

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        # check fist if it's a response
        if "ok" in message_dict:
            # cannot build a complete reply message just from the json representation
            return

        return cls.from_dict(message_dict)

    @classmethod
    def from_dict(cls, message_dict):
        """
        :param body: dict
        :return:  Message object generated from the body
        :raises NonCompliantMessageFormatError: If the message cannot be build from the provided json
        """
        assert type(message_dict) is dict

195
        # check fist if it's a response
196
        if "ok" in message_dict:
197
            # cannot build a complete reply message just from the json representation
198
            return
199

200
        message_type = message_dict["_type"]
201

202 203 204
        if message_type in message_types_dict:
            return message_types_dict[message_type](**message_dict)
        else:
205 206
            raise NonCompliantMessageFormatError("Cannot load json message: %s" % str(message_dict))

207

208
    def __repr__(self):
209
        ret = "%s(" % self.__class__.__name__
210
        for key, value in self.to_dict().items():
211 212
            ret += "%s = %s, " % (key, value)
        ret += ")"
213 214
        return ret

215

216 217 218 219 220
class MsgReply(Message):
    """
    Auxiliary class which creates replies messages with fields based on the request.
    Routing key, corr_id and _type are generated based on the request message
    """
221

222 223 224 225 226 227 228
    def __init__(self, request_message, **kwargs):
        assert request_message

        self.routing_key = request_message.routing_key + ".reply"

        # if not data template, then let's build one for a reply
        # (possible when creating a MsgReply directly and not by using subclass)
229
        if not hasattr(self, "_msg_data_template"):
230
            self._msg_data_template = {
231 232
                "_type": request_message._type,
                "ok":    True,
233 234
            }

235
        super(MsgReply, self).__init__(**kwargs)
236

237
        # overwrite correlation id template and attribute
238
        self._properties["correlation_id"] = request_message.correlation_id
239 240 241 242 243
        self.correlation_id = request_message.correlation_id


class MsgErrorReply(MsgReply):
    """
244
    see section "F-Interop conventions" on top
245
    """
246

247 248
    def __init__(self, request_message, **kwargs):
        assert request_message
249
        # msg_data_template doesnt include _type cause this class is generic, we can only get this at init from request
250
        # so, let's copy the _type from request and let the MsgReply handle the rest of the fields
251
        self._msg_data_template["_type"] = request_message._type
252
        super(MsgErrorReply, self).__init__(request_message, **kwargs)
253 254

    _msg_data_template = {
255 256 257
        "ok":            False,
        "error_message": "Some error message TBD",
        "error_code":    "Some error code TBD"
258 259
    }

260 261

# # # # # # AGENT MESSAGES # # # # # #
Federico Sismondi's avatar
Federico Sismondi committed
262 263 264

class MsgAgentTunStart(Message):
    """
265 266 267 268
    Requirements: Testing Tool MAY implement (if IP tun needed)
    Type: Event
    Typical_use: Testing Tool -> Agent
    Description: Message for triggering start IP tun interface in OS where the agent is running
Federico Sismondi's avatar
Federico Sismondi committed
269
    """
270
    routing_key = "control.tun.toAgent.agent_TT"
Federico Sismondi's avatar
Federico Sismondi committed
271 272

    _msg_data_template = {
273 274 275 276 277 278 279 280
        "_type":              "tun.start",
        "name":               "agent_TT",
        "ipv6_prefix":        "bbbb",
        "ipv6_host":          ":3",
        "ipv6_no_forwarding": False,
        "ipv4_host":          None,
        "ipv4_network":       None,
        "ipv4_netmask":       None,
Federico Sismondi's avatar
Federico Sismondi committed
281 282 283 284 285
    }


class MsgAgentTunStarted(Message):
    """
286 287 288 289
    Description: Message for indicating that agent tun has been started
    Type: Event
    Typical_use: Testing Tool -> Agent
    Description: TBD
Federico Sismondi's avatar
Federico Sismondi committed
290
    """
291
    routing_key = "control.tun.from.agent_TT"
Federico Sismondi's avatar
Federico Sismondi committed
292 293

    _msg_data_template = {
294 295 296 297 298 299 300 301
        "_type":              "tun.started",
        "name":               "agent_TT",
        "ipv6_prefix":        "bbbb",
        "ipv6_host":          ":3",
        "ipv4_host":          None,
        "ipv4_network":       None,
        "ipv4_netmask":       None,
        "ipv6_no_forwarding": False,
Federico Sismondi's avatar
Federico Sismondi committed
302 303
    }

304

Federico Sismondi's avatar
Federico Sismondi committed
305 306 307 308 309 310 311 312
'''
TODO add packet.sniffed.raw
ROUTING_KEY: data.tun.fromAgent.coap_server_agent
 - - -
PROPS: {"delivery_mode": 2, "content_type": "application/json", "headers": {}, "priority": 0, "content_encoding": "utf-8"}
 - - -
BODY {"timestamp": "1488586183.45", "_type": "packet.sniffed.raw", "interface_name": "tun0", "data": [96, 0, 0, 0, 0, 36, 0, 1, 254, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 58, 0, 5, 2, 0, 0, 1, 0, 143, 0, 112, 7, 0, 0, 0, 1, 4, 0, 0, 0, 255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]}
'''
313

314 315

# # # # # # SESSION MESSAGES # # # # # #
316

317
class MsgTestingToolTerminate(Message):
318
    """
319 320 321 322
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI, (or Orchestrator) -> Testing Tool
    Description: Testing tool should stop all it's processes gracefully.
323
    """
324
    routing_key = "control.session"
325 326

    _msg_data_template = {
327
        "_type": "testingtool.terminate",
328 329 330 331 332
    }


class MsgTestingToolReady(Message):
    """
333 334 335 336
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typcal_use: Testing Tool -> GUI
    Description: Used to indicate to the GUI that testing is ready to start the test suite
337
    """
338
    routing_key = "control.session"
339 340

    _msg_data_template = {
341
        "_type":   "testingtool.ready",
342 343 344 345 346 347
        "message": "Testing tool ready to start test suite."
    }


class MsgTestingToolComponentReady(Message):
    """
348 349 350 351
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Event
    Typical_use: Any Testing tool's component -> Test Coordinator
    Description: Once a testing tool's component is ready, it should publish a compoennt ready message
352
    """
353
    routing_key = "control.session"
354 355

    _msg_data_template = {
356 357
        "_type":     "testingtool.component.ready",
        "component": "SomeComponent",
358
        "message":   "Component ready to start test suite."
359 360 361
    }


362
class MsgInteropSessionConfiguration(Message):
363
    """
364 365 366 367
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: Orchestrator -> Testing Tool
    Description: Testing tool MUST listen to this message and configure the testsuite correspondingly
368
    """
369
    routing_key = "control.session"
370 371

    _msg_data_template = {
372
        "_type":         "session.interop.configuration",
Federico Sismondi's avatar
Federico Sismondi committed
373
        "session_id":    "TBD",
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        "testing_tools": "f-interop/interoperability-coap",
        "users":         [
            "u1",
            "f-interop"
        ],
        "iuts":          [
            {
                "id":             "someImplementationFromAUser",
                "role":           "coap_server",
                "execution_mode": "user-assisted",
                "location":       "user-facilities",
                "owner":          "someUserName",
                "version":        "0.1"
            },
            {
                "id":             "automated_iut-coap_client-coapthon-v0.1",
                "role":           "coap_client",
                "execution_mode": "automated-iut",
                "location":       "central-server-docker",
                "owner":          "f-interop",
                "version":        "0.1"
            }
        ],
        "tests":         [
            {
                "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_01_v01",
400
                "settings":     {}
401 402 403
            },
            {
                "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_02_v01",
404
                "settings":     {}
405 406 407 408 409 410 411
            }
        ]
    }


class MsgTestingToolConfigured(Message):
    """
412 413 414 415
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typical_use: Testing Tool -> Orchestrator, GUI
    Description: The goal is to notify orchestrator and other components that the testing tool has been configured
416 417 418 419 420 421 422 423 424 425
    """

    routing_key = "control.session"

    _msg_data_template = {
        "_type":         "testingtool.configured",
        "session_id":    "8ea6b6d5-ffcc-4a0e-ba93-92ee1befea23",
        "testing_tools": "f-interop/interoperability-coap",
    }

426

427 428
class MsgTestingToolComponentShutdown(Message):
    """
429 430 431 432 433
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event) 
    Type: Event
    Typical_use: Any Testing tool's component -> Test Coordinator
    Description: tbd
    """
434 435 436 437 438
    routing_key = "control.session"

    _msg_data_template = {
        "_type":     "testingtool.component.shutdown",
        "component": "SomeComponent",
439
        "message":   "Component is shutting down. Bye!"
440 441
    }

442
    # # # # # # TEST COORDINATION MESSAGES # # # # # #
443

444 445 446

class MsgTestSuiteStart(Message):
    """
447 448 449 450
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI -> Testing Tool
    Description: tbd
451 452
    """

453
    routing_key = "control.testcoordination"
454 455

    _msg_data_template = {
456
        "_type": "testcoordination.testsuite.start",
457 458 459
    }


460 461
class MsgTestSuiteFinish(Message):
    """
462 463 464 465
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI -> Testing Tool
    Description: tbd
466 467 468 469 470
    """

    routing_key = "control.testcoordination"

    _msg_data_template = {
471
        "_type": "testcoordination.testsuite.finish",
472 473
    }

474

475 476
class MsgTestCaseReady(Message):
    """
477 478 479 480 481 482
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typical_use: GUI -> Testing Tool
    Description:
        - Used to indicate to the GUI (or automated-iut) which is the next test case to be executed.
        - This message is normally followed by a MsgTestCaseStart (from GUI-> Testing Tool)
483 484
    """

485
    routing_key = "control.testcoordination"
486 487

    _msg_data_template = {
488 489 490
        "_type":        "testcoordination.testcase.ready",
        "message":      "Next test case to be executed is TD_COAP_CORE_01_v01",
        "testcase_id":  "TD_COAP_CORE_01_v01",
491
        "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_01_v01",
492 493
        "objective":    "Perform GET transaction(CON mode)",
        "state":        None
494 495 496
    }


497 498
class MsgTestCaseStart(Message):
    """
499 500 501 502 503
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI -> Testing Tool
    Description:
        - Message used for indicating the testing tool to start the test case (the one previously selected)
504
    """
505
    routing_key = "control.testcoordination"
506 507

    _msg_data_template = {
508
        "_type": "testcoordination.testcase.start",
509 510 511
    }


512 513
class MsgTestCaseConfiguration(Message):
    """
514 515 516 517 518
    Requirements: Testing Tool MAY publish event (if needed for executing the test case)
    Type: Event
    Typical_use: Testing Tool -> GUI & automated-iut
    Description:
        - Message used to indicate GUI and/or automated-iut which configuration to use.
519 520 521 522
    """
    routing_key = "control.testcoordination"

    _msg_data_template = {
523
        "_type":            "testcoordination.testcase.configuration",
524
        "configuration_id": "COAP_CFG_01_v01",
525 526 527
        "node":             "coap_server",
        "testcase_id":      "TBD",
        "testcase_ref":     "TBD",
528
        "message":
529 530 531 532 533 534 535 536 537 538 539
                            ["CoAP servers running service at [bbbb::2]:5683",
                             "CoAP servers are requested to offer the following resources",
                             ["/test", "Default test resource", "Should not exceed 64bytes"],
                             ["/seg1/seg2/seg3", "Long path ressource", "Should not exceed 64bytes"],
                             ["/query", "Ressource accepting query parameters", "Should not exceed 64bytes"],
                             ["/separate",
                              "Ressource which cannot be served immediately and which cannot be acknowledged in a piggy-backed way",
                              "Should not exceed 64bytes"],
                             ["/large", "Large resource (>1024 bytes)", "shall not exceed 2048bytes"],
                             ["/large_update", "Large resource that can be updated using PUT method (>1024 bytes)",
                              "shall not exceed 2048bytes"],
540 541
                             ["/large_create",
                              "Large resource that can be  created using POST method (>1024 bytes)",
542 543 544 545 546
                              "shall not exceed 2048bytes"],
                             ["/obs", "Observable resource which changes every 5 seconds",
                              "shall not exceed 2048bytes"],
                             ["/.well-known/core", "CoRE Link Format", "may require usage of Block options"]
                             ]
547 548 549
    }


550 551
class MsgTestCaseStop(Message):
    """
552 553 554 555 556
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI & automated-iut -> Testing Tool
    Description:
        - Message used for indicating the testing tool to stop the test case (the one running).
557 558
    """

559
    routing_key = "control.testcoordination"
560 561

    _msg_data_template = {
562
        "_type": "testcoordination.testcase.stop",
563 564 565 566 567
    }


class MsgTestCaseRestart(Message):
    """
568 569 570 571
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI -> Testing Tool
    Description: Restart the running test cases.
572 573
    """

574
    routing_key = "control.testcoordination"
575 576

    _msg_data_template = {
577
        "_type": "testcoordination.testcase.restart",
578 579
    }

580 581 582

class MsgStepExecute(Message):
    """
583 584 585 586 587
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typical_use: Testing Tool -> GUI
    Description:
        - Used to indicate to the GUI (or automated-iut) which is the step to be executed by the user (or automated-IUT).
588 589
    """

590
    routing_key = "control.testcoordination"
591 592

    _msg_data_template = {
593 594 595 596 597
        "_type":               "testcoordination.step.execute",
        "message":             "Next test step to be executed is TD_COAP_CORE_01_v01_step_01",
        "step_id":             "TD_COAP_CORE_01_v01_step_01",
        "step_type":           "stimuli",
        "step_info":           [
598 599 600 601
            "Client is requested to send a GET request with",
            "Type = 0(CON)",
            "Code = 1(GET)"
        ],
602 603
        "step_state":          "executing",
        "node":                "coap_client",
604
        "node_execution_mode": "user_assisted",
605 606
        "testcase_id":         "TBD",
        "testcase_ref":        "TBD"
607 608
    }

609 610 611

class MsgStimuliExecuted(Message):
    """
612 613 614 615 616
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI (or automated-IUT)-> Testing Tool
    Description:
        - Used to indicate stimuli has been executed by user (and it's user-assisted iut) or by automated-iut
617 618
    """

619
    routing_key = "control.testcoordination"
620 621

    _msg_data_template = {
622
        "_type": "testcoordination.step.stimuli.executed",
623 624 625 626 627
    }


class MsgCheckResponse(Message):
    """
628 629 630 631 632 633 634
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Event
    Typical_use: test coordination -> test analysis
    Description:
        - 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.
        - Not used in CoAP testing Tool (analysis of traces is done post mortem)
635 636
    """

637
    routing_key = "control.testcoordination"
638

639
    _msg_data_template = {
640 641 642
        "_type":           "testcoordination.step.check.response",
        "partial_verdict": "pass",
        "description":     "TAT says: step complies (checks) with specification"
643 644 645 646 647
    }


class MsgVerifyResponse(Message):
    """
648 649 650 651 652 653
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI (or automated-IUT)-> Testing Tool
    Description:
        - Message provided by user declaring if the IUT VERIFY the step previously executed as described in the Test
        Description.
654 655
    """

656
    routing_key = "control.testcoordination"
657 658

    _msg_data_template = {
659 660 661
        "_type":           "testcoordination.step.verify.response",
        "verify_response": True,
        "response_type":   "bool"
662 663
    }

664

665 666
class MsgTestCaseFinish(Message):
    """
667 668 669 670 671 672 673 674 675
    TODO: TBD if needed or not

    Requirements: Testing Tool MAY listen to event
    Type: Event
    Typical_use: GUI (or automated-IUT)-> Testing Tool
    Description:
        - Used for indicating that the test case has finished.
        - Test coordinator deduces it automatically by using the testcase's step sequence
        - Not used in CoAP Testing Tool.
676 677
    """

678
    routing_key = "control.testcoordination"
679 680

    _msg_data_template = {
681
        "_type": "testcoordination.testcase.finish",
682 683
    }

684

685 686
class MsgTestCaseFinished(Message):
    """
687 688 689 690 691 692
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typical_use: Testing Tool -> GUI
    Description:
        - Used for indicating to subscribers that the test cases has finished.
        - This message is followed by a verdict.
693 694
    """

695
    routing_key = "control.testcoordination"
696 697

    _msg_data_template = {
698 699
        "_type":        "testcoordination.testcase.finished",
        "testcase_id":  "TD_COAP_CORE_01",
700
        "testcase_ref": "TBD",
701
        "message":      "Testcase finished"
702 703
    }

704

705 706
class MsgTestCaseSkip(Message):
    """
707 708 709 710 711 712
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI (or automated-IUT)-> Testing Tool
    Description:
        - Used for skipping a test cases event when was previusly selected to be executed.
        - testcase_id (optional) : if not provided then current tc is skipped
713 714
    """

715
    routing_key = "control.testcoordination"
716 717

    _msg_data_template = {
718 719
        "_type":       "testcoordination.testcase.skip",
        "testcase_id": "TD_COAP_CORE_02_v01",
720 721 722 723 724
    }


class MsgTestCaseSelect(Message):
    """
725 726 727 728 729
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI (or automated-IUT)-> Testing Tool
    Description: tbd

730 731
    """

732
    routing_key = "control.testcoordination"
733 734

    _msg_data_template = {
735 736
        "_type":       "testcoordination.testcase.select",
        "testcase_id": "TD_COAP_CORE_03_v01",
737 738
    }

739

740 741
class MsgTestSuiteAbort(Message):
    """
742 743 744 745
    Requirements: Testing Tool MUST listen to event
    Type: Event
    Typical_use: GUI (or automated-IUT)-> Testing Tool
    Description: tbd
746 747
    """

748
    routing_key = "control.testcoordination"
749 750

    _msg_data_template = {
751
        "_type": "testcoordination.testsuite.abort",
752 753
    }

754

755 756
class MsgTestSuiteGetStatus(Message):
    """
757 758 759 760 761 762
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Request (service)
    Typical_use: GUI -> Testing Tool
    Description:
        - Describes current state of the test suite.
        - Format for the response not standardised.
763 764
    """

765
    routing_key = "control.testcoordination.service"
766 767

    _msg_data_template = {
768
        "_type": "testcoordination.testsuite.getstatus",
769 770
    }

771

772
class MsgTestSuiteGetStatusReply(MsgReply):
773
    """
774 775 776 777 778 779
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Reply (service)
    Typical_use: Testing Tool -> GUI
    Description:
        - Describes current state of the test suite.
        - Format for the response not standardised.
780 781
    """

782
    routing_key = "control.testcoordination.service.reply"
783 784

    _msg_data_template = {
785 786
        "_type":          "testcoordination.testsuite.getstatus.reply",
        "ok":             True,
787 788
        "started":        True,
        "testcase_id":    "TD_COAP_CORE_01_v01",
789
        "testcase_state": "executing",
790
        "step_id":        "TD_COAP_CORE_01_v01_step_01"
791

792 793
    }

794

795 796
class MsgTestSuiteGetTestCases(Message):
    """
797 798 799 800
    Requirements: Testing Tool SHOULD (MUST?) implement (other components should not subscribe to event)
    Type: Request (service)
    Typical_use: GUI -> Testing Tool
    Description: TBD
801 802
    """

803
    routing_key = "control.testcoordination.service"
804 805

    _msg_data_template = {
806
        "_type": "testcoordination.testsuite.gettestcases",
807 808
    }

809 810 811

class MsgTestSuiteGetTestCasesReply(MsgReply):
    """
812 813 814 815
    Requirements: Testing Tool SHOULD (MUST?) implement (other components should not subscribe to event)
    Type: Reply (service)
    Typical_use: Testing Tool -> GUI
    Description: TBD
816 817
    """

818
    routing_key = "control.testcoordination.service.reply"
819 820

    _msg_data_template = {
821 822
        "_type":   "testcoordination.testsuite.gettestcases.reply",
        "ok":      True,
823 824
        "tc_list": [
            {
825
                "testcase_id":  "TD_COAP_CORE_01_v01",
826
                "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_01_v01",
827 828
                "objective":    "Perform GET transaction(CON mode)",
                "state":        None
829 830
            },
            {
831
                "testcase_id":  "TD_COAP_CORE_02_v01",
832
                "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_02_v01",
833 834
                "objective":    "Perform DELETE transaction (CON mode)",
                "state":        None
835 836
            },
            {
837
                "testcase_id":  "TD_COAP_CORE_03_v01",
838
                "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_03_v01",
839 840
                "objective":    "Perform PUT transaction (CON mode)",
                "state":        None
841 842 843 844 845 846 847
            }
        ]
    }


class MsgTestCaseVerdict(Message):
    """
848 849 850 851
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typical_use: Testing Tool -> GUI
    Description: Used to indicate to the GUI (or automated-iut) which is the final verdict of the testcase.
852 853
    """

854
    routing_key = "control.testcoordination"
855 856

    _msg_data_template = {
857 858 859
        "_type":            "testcoordination.testcase.verdict",
        "verdict":          "pass",
        "description":      "No interoperability error was detected,",
860 861 862 863 864 865 866 867 868 869 870
        "partial_verdicts": [
            ["TD_COAP_CORE_01_v01_step_02", None, "CHECK postponed", ""],
            ["TD_COAP_CORE_01_v01_step_03", None, "CHECK postponed", ""],
            ["TD_COAP_CORE_01_v01_step_04", "pass",
             "VERIFY step: User informed that the information was displayed correclty on his/her IUT", ""],
            ["CHECK_1_post_mortem_analysis", "pass",
             "<Frame   3: [bbbb::1 -> bbbb::2] CoAP [CON 43211] GET /test> Match: CoAP(type=0, code=1)"],
            ["CHECK_2_post_mortem_analysis", "pass",
             "<Frame   4: [bbbb::2 -> bbbb::1] CoAP [ACK 43211] 2.05 Content > Match: CoAP(code=69, mid=0xa8cb, tok=b'', pl=Not(b''))"],
            ["CHECK_3_post_mortem_analysis", "pass",
             "<Frame   4: [bbbb::2 -> bbbb::1] CoAP [ACK 43211] 2.05 Content > Match: CoAP(opt=Opt(CoAPOptionContentFormat()))"]],
871 872 873
        "testcase_id":      "TD_COAP_CORE_01_v01",
        "testcase_ref":     "http://f-interop.paris.inria.fr/tests/TD_COAP_CORE_01_v01",
        "objective":        "Perform GET transaction(CON mode)", "state": "finished"
874 875 876 877 878
    }


class MsgTestSuiteReport(Message):
    """
879 880 881 882
    Requirements: Testing Tool MUST publish event
    Type: Event
    Typical_use: Testing Tool -> GUI
    Description: Used to indicate to the GUI (or automated-iut) the final results of the test session.
883 884
    """

885
    routing_key = "control.testcoordination"
886 887

    _msg_data_template = {
888
        "_type": "testcoordination.testsuite.report",
889
        "TD_COAP_CORE_01_v01":
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
                 {
                     "verdict":     "pass",
                     "description": "No interoperability error was detected,",
                     "partial_verdicts":
                                    [
                                        ["TD_COAP_CORE_01_v01_step_02", None, "CHECK postponed", ""],
                                        ["TD_COAP_CORE_01_v01_step_03", None, "CHECK postponed", ""],
                                        ["TD_COAP_CORE_01_v01_step_04", "pass",
                                         "VERIFY step: User informed that the information was displayed correclty on his/her IUT",
                                         ""],
                                        ["CHECK_1_post_mortem_analysis", "pass",
                                         "<Frame   3: [bbbb::1 -> bbbb::2] CoAP [CON 43211] GET /test> Match: CoAP(type=0, code=1)"],
                                        ["CHECK_2_post_mortem_analysis", "pass",
                                         "<Frame   4: [bbbb::2 -> bbbb::1] CoAP [ACK 43211] 2.05 Content > Match: CoAP(code=69, mid=0xa8cb, tok=b'', pl=Not(b''))"],
                                        [
                                            "CHECK_3_post_mortem_analysis",
                                            "pass",
                                            "<Frame   4: [bbbb::2 -> bbbb::1] CoAP [ACK 43211] 2.05 Content > Match: CoAP(opt=Opt(CoAPOptionContentFormat()))"]
                                    ]
                 },
910 911

        "TD_COAP_CORE_02_v01":
912 913 914 915 916 917 918 919 920 921 922 923 924
                 {
                     "verdict":          "pass",
                     "description":      "No interoperability error was detected,",
                     "partial_verdicts": [
                         ["TD_COAP_CORE_02_v01_step_02", None, "CHECK postponed", ""],
                         ["TD_COAP_CORE_02_v01_step_03", None, "CHECK postponed", ""],
                         ["TD_COAP_CORE_02_v01_step_04", "pass",
                          "VERIFY step: User informed that the information was displayed correclty on his/her IUT",
                          ""], ["CHECK_1_post_mortem_analysis", "pass",
                                "<Frame   3: [bbbb::1 -> bbbb::2] CoAP [CON 43213] DELETE /test> Match: CoAP(type=0, code=4)"],
                         ["CHECK_2_post_mortem_analysis", "pass",
                          "<Frame   4: [bbbb::2 -> bbbb::1] CoAP [ACK 43213] 2.02 Deleted > Match: CoAP(code=66, mid=0xa8cd, tok=b'')"]]
                 }
925 926
    }

927
    # # # # # # SNIFFING SERVICES REQUEST MESSAGES # # # # # #
928

929 930 931

class MsgSniffingStart(Message):
    """
932 933 934 935
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event) 
    Type: Request (service)
    Typical_use: coordination -> sniffing
    Description: tbd
936 937
    """

938
    routing_key = "control.sniffing.service"
939 940

    _msg_data_template = {
941 942 943 944
        "_type":        "sniffing.start",
        "capture_id":   "TD_COAP_CORE_01",
        "filter_if":    "tun0",
        "filter_proto": "udp port 5683"
945 946
    }

947

948 949
class MsgSniffingStartReply(MsgReply):
    """
950 951 952 953
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Reply (service)
    Typical_use: sniffing -> coordination
    Description: tbd
954 955
    """

956
    routing_key = "control.sniffing.service.reply"
957 958

    _msg_data_template = {
959 960
        "_type": "sniffing.start.reply",
        "ok":    True
961 962
    }

963

964 965
class MsgSniffingStop(Message):
    """
966 967 968 969
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Request (service)
    Typical_use: coordination -> sniffing
    Description: tbd
970 971
    """

972
    routing_key = "control.sniffing.service"
973 974

    _msg_data_template = {
975
        "_type": "sniffing.stop",
976 977
    }

978

979 980
class MsgSniffingStoptReply(MsgReply):
    """
981 982 983 984
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Reply (service)
    Typical_use: sniffing -> coordination
    Description: tbd
985 986
    """

987
    routing_key = "control.sniffing.service.reply"
988 989

    _msg_data_template = {
990 991
        "_type": "sniffing.stop.reply",
        "ok":    True
992 993
    }

994

995 996
class MsgSniffingGetCapture(Message):
    """
997 998 999 1000
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event) 
    Type: Request (service)
    Typical_use: coordination -> sniffing
    Description: tbd
1001 1002
    """

1003
    routing_key = "control.sniffing.service"
1004 1005

    _msg_data_template = {
1006
        "_type":      "sniffing.getcapture",
1007 1008 1009 1010
        "capture_id": "TD_COAP_CORE_01",

    }

1011

1012
class MsgSniffingGetCaptureReply(MsgReply):
1013 1014 1015 1016 1017 1018
    """
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Reply (service)
    Typical_use: sniffing -> coordination
    Description: tbd
    """
1019
    routing_key = "control.sniffing.service.reply"
1020 1021

    _msg_data_template = {
1022 1023 1024 1025 1026
        "_type":    "sniffing.getcapture.reply",
        "ok":       True,
        "file_enc": "pcap_base64",
        "filename": "TD_COAP_CORE_01.pcap",
        "value":    "1MOyoQIABAAAAAAAAAAAAMgAAAAAAAAA",  # empty PCAP
1027 1028
    }

1029

1030 1031
class MsgSniffingGetCaptureLast(Message):
    """
1032 1033 1034 1035
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event) 
    Type: Request (service)
    Typical_use: coordination -> sniffing
    Description: tbd
1036 1037
    """

1038
    routing_key = "control.sniffing.service"
1039 1040

    _msg_data_template = {
1041
        "_type": "sniffing.getlastcapture",
1042
    }
1043

1044

1045
class MsgSniffingGetCaptureLastReply(MsgReply):
1046 1047 1048 1049 1050 1051
    """
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Reply (service)
    Typical_use: sniffing -> coordination
    Description: tbd
    """
1052
    routing_key = "control.sniffing.service.reply"
1053 1054

    _msg_data_template = {
1055 1056 1057 1058 1059
        "_type":    "sniffing.getlastcapture.reply",
        "ok":       True,
        "file_enc": "pcap_base64",
        "filename": "TD_COAP_CORE_01.pcap",
        "value":    "1MOyoQIABAAAAAAAAAAAAMgAAAAAAAAA",  # empty PCAP
1060 1061
    }

1062
    # # # # # # ANALYSIS MESSAGES # # # # # #
1063

1064

1065
class MsgInteropTestCaseAnalyze(Message):
1066
    """
1067 1068 1069 1070 1071 1072
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
    Type: Request (service)
    Typical_use: coordination -> analysis
    Description:
        - Method to launch an analysis from a pcap file or a token if the pcap file has already been provided.
        - The method need a token or a pcap_file but doesn't allow someone to provide both.
1073

1074 1075
    """

1076
    PCAP_empty_base64 = "1MOyoQIABAAAAAAAAAAAAMgAAAAAAAAA"
1077

1078
    routing_key = "control.analysis.service"
1079 1080

    _msg_data_template = {
1081
        "_type":        "analysis.interop.testcase.analyze",
1082
        "testcase_id":  "TD_COAP_CORE_01",
1083
        "testcase_ref": "http://doc.f-interop.eu/tests/TD_COAP_CORE_01_v01",
1084 1085 1086
        "file_enc":     "pcap_base64",
        "filename":     "TD_COAP_CORE_01.pcap",
        "value":        PCAP_empty_base64,
1087 1088
    }

1089

1090 1091
class MsgInteropTestCaseAnalyzeReply(MsgReply):
    """
1092
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event) 
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    Analyzer -> Coordinator
    Testing Tool SHOULD implement (design recommendation)

    The recommended structure for the partial_verdicts field is a list of partial verdicts with the following
    requirements:
     - each one of those elements of the list correspond to one CHECK or VERIFY steps of the test description
     - first value of the list MUST be a "pass", "fail", "inconclusive" or eventually "error" partial verdict (string)
     - the second value MUST be a string with a description of partial verdict (intended for the user)
     - more values elements MAY be added to the list

    """

    _msg_data_template = {
1106 1107 1108 1109 1110 1111 1112
        "_type":            "analysis.interop.testcase.analyze.reply",
        "ok":               True,
        "verdict":          "pass",
        "analysis_type":    "postmortem",
        "description":      "The test purpose has been verified without any fault detected",
        "review_frames":    [],
        "token":            "0lzzb_Bx30u8Gu-xkt1DFE1GmB4",
1113 1114
        "partial_verdicts": [
            [
1115 1116
                "pass",
                "<Frame   1: [127.0.0.1 -> 127.0.0.1] CoAP [CON 43521] GET /test> Match: CoAP(type=0, code=1)"
1117
            ],
1118 1119 1120 1121 1122

            [
                "pass",
                "<Frame   2: [127.0.0.1 -> 127.0.0.1] CoAP [ACK 43521] 2.05 Content > Match: CoAP(code=69, mid=0xaa01, \
                tok=b'b\\xda', pl=Not(b''))"
1123
            ],
1124 1125 1126 1127
            [
                "pass",
                "<Frame   2: [127.0.0.1 -> 127.0.0.1] CoAP [ACK 43521] 2.05 Content > \
                Match: CoAP(opt=Opt(CoAPOptionContentFormat()))"
1128
            ]
1129
        ],
1130 1131