Completed
Pull Request — master (#2304)
by Arma
07:07
created

st2tests.mocks.MockSensorService   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 93
Duplicated Lines 0 %
Metric Value
wmc 13
dl 0
loc 93
rs 10
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
"""
17
Mock classes for use in pack testing.
18
"""
19
20
from logging import RootLogger
21
22
from mock import Mock
23
24
from st2reactor.container.sensor_wrapper import SensorService
25
from st2client.models.keyvalue import KeyValuePair
26
27
__all__ = [
28
    'MockSensorWrapper',
29
    'MockSensorService'
30
]
31
32
33
class MockSensorWrapper(object):
34
    def __init__(self, pack, class_name):
35
        self._pack = pack
36
        self._class_name = class_name
37
38
39
class MockSensorService(SensorService):
40
    """
41
    Mock SensorService for use in testing.
42
    """
43
44
    def __init__(self, sensor_wrapper):
45
        self._sensor_wrapper = sensor_wrapper
46
47
        # Holds a mock logger instance
48
        # We use a Mock class so use can assert logger was called with particular arguments
49
        self._logger = Mock(spec=RootLogger)
50
51
        # Holds mock KeyValuePair objects
52
        # Key is a KeyValuePair name and value is the KeyValuePair object
53
        self._datastore_items = {}
54
55
        # Holds a list of triggers which were dispatched
56
        self.dispatched_triggers = []
57
58
    def get_logger(self, name):
59
        """
60
        Return mock logger instance.
61
62
        Keep in mind that this method returns Mock class instance which means you can use all the
63
        usual Mock class methods to assert that a particular message has been logged / logger has
64
        been called with particular arguments.
65
        """
66
        return self._logger
67
68
    def dispatch_with_context(self, trigger, payload=None, trace_context=None):
69
        item = {
70
            'trigger': trigger,
71
            'payload': payload,
72
            'trace_context': trace_context
73
        }
74
        self.dispatched_triggers.append(item)
75
76
    def list_values(self, local=True, prefix=None):
77
        """
78
        Return a list of all values stored in a dictionary which is local to this class.
79
        """
80
        key_prefix = self._get_full_key_prefix(local=local, prefix=prefix)
81
82
        if not key_prefix:
83
            return self._datastore_items.values()
84
85
        result = []
86
        for name, kvp in self._datastore_items.items():
87
            if name.startswith(key_prefix):
88
                result.append(kvp)
89
90
        return result
91
92
    def get_value(self, name, local=True):
93
        """
94
        Return a particular value stored in a dictionary which is local to this class.
95
        """
96
        name = self._get_full_key_name(name=name, local=local)
97
98
        if name not in self._datastore_items:
99
            return None
100
101
        kvp = self._datastore_items[name]
102
        return kvp.value
103
104
    def set_value(self, name, value, ttl=None, local=True):
105
        """
106
        Store a value in a dictionary which is local to this class.
107
        """
108
        if ttl:
109
            raise ValueError('MockSensorService.set_value doesn\'t support "ttl" argument')
110
111
        name = self._get_full_key_name(name=name, local=local)
112
113
        instance = KeyValuePair()
114
        instance.id = name
115
        instance.name = name
116
        instance.value = value
117
118
        self._datastore_items[name] = instance
119
        return True
120
121
    def delete_value(self, name, local=True):
122
        """
123
        Delete a value from a dictionary which is local to this class.
124
        """
125
        name = self._get_full_key_name(name=name, local=local)
126
127
        if name not in self._datastore_items:
128
            return False
129
130
        del self._datastore_items[name]
131
        return True
132