Merge "Add "host_name_separator" variable to Context class"
[yardstick.git] / yardstick / common / messaging / payloads.py
1 # Copyright (c) 2018 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import abc
16
17 import six
18
19 from yardstick.common import exceptions
20
21
22 @six.add_metaclass(abc.ABCMeta)
23 class Payload(object):
24     """Base Payload class to transfer data through the MQ service"""
25
26     REQUIRED_FIELDS = {'version'}
27
28     def __init__(self, **kwargs):
29         """Init method
30
31         :param kwargs: (dictionary) attributes and values of the object
32         :returns: Payload object
33         """
34
35         if not all(req_field in kwargs for req_field in self.REQUIRED_FIELDS):
36             _attrs = set(kwargs) - self.REQUIRED_FIELDS
37             missing_attributes = ', '.join(str(_attr) for _attr in _attrs)
38             raise exceptions.PayloadMissingAttributes(
39                 missing_attributes=missing_attributes)
40
41         for name, value in kwargs.items():
42             setattr(self, name, value)
43
44         self._fields = set(kwargs.keys())
45
46     def obj_to_dict(self):
47         """Returns a dictionary with the attributes of the object"""
48         return {field: getattr(self, field) for field in self._fields}
49
50     @classmethod
51     def dict_to_obj(cls, _dict):
52         """Returns a Payload object built from the dictionary elements"""
53         return cls(**_dict)