Debian Codegraph @

tests/autopilot/push_notifications/helpers/push_notifications_helper.py

raw
1 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
2 #
3 # Push Notifications Autopilot Test Suite
4 # Copyright (C) 2014 Canonical
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 import configparser
21 import datetime
22 import http.client as http
23 import json
24 import os
25 import subprocess
26 import systemimage.config as sys_info
27
28 from push_notifications import config as push_config
29 from push_notifications.data import (
30 PushNotificationMessage,
31 DeviceNotificationData
32 )
33
34
35 class PushClientConfig:
36 """
37 Container class to read and hold all required server config
38 - Server listener address
39 - Server device address
40 - Certificate PEM file path
41 """
42
43 @staticmethod
44 def read_config(config_file_path):
45 """
46 Return PushClientConfig object containing all test config parameters
47 which have been read from specified config file.
48 :param config_file_path: path to required config file
49 :return: PushClientConfig object containing all config parameters
50 """
51 KEY_ADDR = 'addr'
52 KEY_LISTENER_PORT = 'listener_port'
53 KEY_DEVICE_PORT = 'device_port'
54 KEY_CONFIG = 'config'
55 KEY_CERT_PEM_FILE = 'cert_pem_file'
56
57 config = PushClientConfig()
58 parser = configparser.ConfigParser()
59 parser.read(config_file_path)
60 server_addr = parser[KEY_CONFIG][KEY_ADDR]
61 device_port = parser[KEY_CONFIG][KEY_DEVICE_PORT]
62 listener_port = parser[KEY_CONFIG][KEY_LISTENER_PORT]
63 addr_fmt = '{0}:{1}'
64 http_addr_fmt = 'http://{0}:{1}/'
65 config.server_listener_addr = addr_fmt.format(
66 server_addr, listener_port)
67 config.server_device_addr = addr_fmt.format(server_addr, device_port)
68 config.server_session_url = http_addr_fmt.format(server_addr, listener_port)
69 config.server_registration_url = http_addr_fmt.format(server_addr, listener_port)
70 config.cert_pem_file = push_config.get_cert_file(
71 parser[KEY_CONFIG][KEY_CERT_PEM_FILE])
72 return config
73
74
75 class PushClientController:
76 """
77 Class used to reconfigure and re-start lomiri-push-service for testing
78 """
79
80 PUSH_CLIENT_DEFAULT_CONFIG_FILE = '/etc/xdg/lomiri-push-service/config.json'
81 PUSH_CLIENT_CONFIG_FILE = '~/.config/lomiri-push-service/config.json'
82
83 def restart_push_client_using_config(self, client_config=None):
84 """
85 Restart the push client using the config provided
86 If the config is none then revert to default client behaviour
87 :param client_config: PushClientConfig object containing
88 required config
89 """
90 if client_config is None:
91 # just delete the local custom config file
92 # client will then just use the original config
93 abs_config_file = self.get_abs_local_config_file_path()
94 if os.path.exists(abs_config_file):
95 os.remove(abs_config_file)
96 else:
97 # write the config to local config file
98 self.write_client_test_config(client_config)
99
100 # Now re-start the client
101 self.restart_push_client()
102
103 def write_client_test_config(self, client_config):
104 """
105 Write the test server address and certificate path
106 to the client config file
107 :param client_config: PushClientConfig object containing
108 required config
109 """
110 # read the original push client config file
111 with open(self.PUSH_CLIENT_DEFAULT_CONFIG_FILE) as config_file:
112 config = json.load(config_file)
113 # change server address
114 config['addr'] = client_config.server_device_addr
115 # change session_url
116 config['session_url'] = client_config.server_session_url
117 # change registration url
118 config['registration_url'] = client_config.server_registration_url
119 # add certificate file path
120 config['cert_pem_file'] = client_config.cert_pem_file
121 # write the config json out to the ~.local address
122 # creating the directory if it doesn't already exist
123 abs_config_file = self.get_abs_local_config_file_path()
124 config_dir = os.path.dirname(abs_config_file)
125 if not os.path.exists(config_dir):
126 os.makedirs(config_dir)
127 with open(abs_config_file, 'w+') as outfile:
128 json.dump(config, outfile, indent=4)
129 outfile.close()
130
131 def get_abs_local_config_file_path(self):
132 """
133 Return absolute path of ~.local config file
134 """
135 return os.path.expanduser(self.PUSH_CLIENT_CONFIG_FILE)
136
137 def control_client(self, command):
138 """
139 start/stop/restart the lomiri-push-service using systemctl
140 """
141 subprocess.call(
142 ['/usr/bin/systemctl', command, 'lomiri-push-service.service'],
143 stdout=subprocess.DEVNULL)
144
145 def stop_push_client(self):
146 """
147 Stop the push client
148 """
149 self.control_client('stop')
150
151 def start_push_client(self):
152 """
153 Start the push client
154 """
155 self.control_client('start')
156
157 def restart_push_client(self):
158 """
159 Restart the push client
160 """
161 self.stop_push_client()
162 self.start_push_client()
163
164
165 class PushNotificationHelper:
166 """
167 Utility class to create and send push notification messages
168 """
169
170 DEFAULT_BROADCAST_URL = '/broadcast'
171 UNICAST_URL = '/notify'
172
173 def get_device_info(self):
174 """
175 Discover the device's model and build info
176 - device name e.g. mako
177 - channel name e.g. ubports-touch/16.04/devel
178 - build_number e.g. 101
179 :return: DeviceNotificationData object containing device info
180 """
181 # channel info needs to be read from file
182 parser = configparser.ConfigParser()
183 channel_config_file = '/etc/system-image/channel.ini'
184 parser.read(channel_config_file)
185 channel = parser['service']['channel']
186 return DeviceNotificationData(
187 device=sys_info.config.device,
188 channel=channel,
189 build_number=sys_info.config.build_number)
190
191 def send_push_broadcast_notification(self, msg_json, server_addr,
192 url=DEFAULT_BROADCAST_URL):
193 """
194 Send the specified push message to the server broadcast url
195 using an HTTP POST command
196 :param msg_json: JSON representation of message to send
197 :param url: destination server url to send message to
198 """
199 headers = {'Content-type': 'application/json'}
200 conn = http.HTTPConnection(server_addr)
201 conn.request(
202 'POST',
203 url,
204 headers=headers,
205 body=msg_json)
206 return conn.getresponse()
207
208 def create_push_message(self, channel='system', data=None,
209 expire_after=None):
210 """
211 Return a new push message
212 If no expiry time is given, a future date will be assigned
213 :param channel: name of the channel
214 :param data: data value of the message
215 :param expire_after: expiry time for message
216 :return: PushNotificationMessage object containing specified parameters
217 """
218 if expire_after is None:
219 expire_after = self.get_future_iso_time()
220 return PushNotificationMessage(
221 channel=channel,
222 data=data,
223 expire_after=expire_after)
224
225 def get_past_iso_time(self):
226 """
227 Return time 1 year in past in ISO format
228 """
229 return self.get_iso_time(year_offset=-1)
230
231 def get_near_past_iso_time(self):
232 """
233 Return time 5 seconds in past in ISO format
234 """
235 return self.get_iso_time(sec_offset=-5)
236
237 def get_near_future_iso_time(self):
238 """
239 Return time 5 seconds in future in ISO format
240 """
241 return self.get_iso_time(sec_offset=5)
242
243 def get_future_iso_time(self):
244 """
245 Return time 1 year in future in ISO format
246 """
247 return self.get_iso_time(year_offset=1)
248
249 def get_current_iso_time(self):
250 """
251 Return current time in ISO format
252 """
253 return self.get_iso_time()
254
255 def get_iso_time(self, year_offset=0, month_offset=0, day_offset=0,
256 hour_offset=0, min_offset=0, sec_offset=0,
257 tz_hour_offset=0, tz_min_offset=0):
258 """
259 Return an ISO8601 format date-time string, including time-zone
260 offset: YYYY-MM-DDTHH:MM:SS-HH:MM
261 :param year_offset: number of years to offset
262 :param month_offset: number of months to offset
263 :param day_offset: number of days to offset
264 :param hour_offset: number of hours to offset
265 :param min_offset: number of minutes to offset
266 :param sec_offset: number of seconds to offset
267 :param tz_hour_offset: number of hours to offset time zone
268 :param tz_min_offset: number of minutes to offset time zone
269 :return: string representation of required time in ISO8601 format
270 """
271 # calulate target time based on current time and format it
272 now = datetime.datetime.now()
273 target_time = datetime.datetime(
274 year=now.year + year_offset,
275 month=now.month + month_offset,
276 day=now.day + day_offset,
277 hour=now.hour + hour_offset,
278 minute=now.minute + min_offset,
279 second=now.second + sec_offset)
280 target_time_fmt = target_time.strftime('%Y-%m-%dT%H:%M:%S')
281 # format time zone offset
282 tz = datetime.time(
283 hour=tz_hour_offset,
284 minute=tz_min_offset)
285 tz_fmt = tz.strftime('%H:%M')
286 # combine target time and time zone offset
287 iso_time = '{0}-{1}'.format(target_time_fmt, tz_fmt)
288 return iso_time
289
290 def _http_request(self, server_addr, url, method='GET',
291 body=None):
292 headers = {'Content-type': 'application/json'}
293 conn = http.HTTPConnection(server_addr)
294 conn.request(
295 method,
296 url,
297 headers=headers,
298 body=body)
299 return conn.getresponse()
300
301 def register(self, path, appid):
302 """Register the device/appid with the push server."""
303 cmd = ["gdbus", "call", "-e", "-d", "com.lomiri.PushNotifications",
304 "-o", "/com/lomiri/PushNotifications/%s" % path,
305 "-m", "com.lomiri.PushNotifications.Register", appid]
306 output = subprocess.check_output(cmd)
307 return output[2:-4].decode("utf-8")
308
309 def send_unicast(self, msg, server_addr, url=UNICAST_URL):
310 """Send a unicast notification"""
311 return self._http_request(server_addr, url, method='POST',
312 body=json.dumps(msg))