A1 v2.1.0
[ric-plt/a1.git] / tests / a1test_helpers.py
1 # ==================================================================================
2 #       Copyright (c) 2019-2020 Nokia
3 #       Copyright (c) 2018-2020 AT&T Intellectual Property.
4 #
5 #   Licensed under the Apache License, Version 2.0 (the "License");
6 #   you may not use this file except in compliance with the License.
7 #   You may obtain a copy of the License at
8 #
9 #          http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #   Unless required by applicable law or agreed to in writing, software
12 #   distributed under the License is distributed on an "AS IS" BASIS,
13 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 #   See the License for the specific language governing permissions and
15 #   limitations under the License.
16 # ==================================================================================
17 import msgpack
18 from ricsdl.exceptions import RejectedByBackend, NotConnected, BackendError
19
20
21 class MockSDLWrapper:
22     """
23     Mock wrapper for SDL that uses a dict so we do not rely on Redis for unit tests.
24     Would be really nice if SDL itself came with a "standalone: dictionary" mode for this purpose...
25     """
26
27     def __init__(self):
28         self.POLICY_DATA = {}
29
30     def set(self, key, value):
31         """set a key"""
32
33         # these are for unit testing that the handler works on various SDL errors
34         if key == "a1.policy_type.111":
35             raise RejectedByBackend()
36         if key == "a1.policy_type.112":
37             raise NotConnected()
38         if key == "a1.policy_type.113":
39             raise BackendError()
40
41         self.POLICY_DATA[key] = msgpack.packb(value, use_bin_type=True)
42
43     def get(self, key):
44         """get a key"""
45         if key in self.POLICY_DATA:
46             return msgpack.unpackb(self.POLICY_DATA[key], raw=False)
47         return None
48
49     def find_and_get(self, prefix):
50         """get all k v pairs that start with prefix"""
51         return {k: msgpack.unpackb(v, raw=False) for k, v in self.POLICY_DATA.items() if k.startswith(prefix)}
52
53     def delete(self, key):
54         """ delete a key"""
55         del self.POLICY_DATA[key]