comparison sat/test/test_plugin_misc_radiocol.py @ 2624:56f94936df1e

code style reformatting using black
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 20:14:46 +0200
parents 26edcf3a30eb
children ab2696e34d29
comparison
equal deleted inserted replaced
2623:49533de4540b 2624:56f94936df1e
37 from mutagen.oggvorbis import OggVorbis 37 from mutagen.oggvorbis import OggVorbis
38 from mutagen.mp3 import MP3 38 from mutagen.mp3 import MP3
39 from mutagen.easyid3 import EasyID3 39 from mutagen.easyid3 import EasyID3
40 from mutagen.id3 import ID3NoHeaderError 40 from mutagen.id3 import ID3NoHeaderError
41 except ImportError: 41 except ImportError:
42 raise exceptions.MissingModule(u"Missing module Mutagen, please download/install from https://bitbucket.org/lazka/mutagen") 42 raise exceptions.MissingModule(
43 u"Missing module Mutagen, please download/install from https://bitbucket.org/lazka/mutagen"
44 )
43 45
44 import uuid 46 import uuid
45 import os 47 import os
46 import copy 48 import copy
47 import shutil 49 import shutil
48 50
49 51
50 ROOM_JID = JID(Const.MUC_STR[0]) 52 ROOM_JID = JID(Const.MUC_STR[0])
51 PROFILE = Const.PROFILE[0] 53 PROFILE = Const.PROFILE[0]
52 REFEREE_FULL = JID(ROOM_JID.userhost() + '/' + Const.JID[0].user) 54 REFEREE_FULL = JID(ROOM_JID.userhost() + "/" + Const.JID[0].user)
53 PLAYERS_INDICES = [0, 1, 3] # referee included 55 PLAYERS_INDICES = [0, 1, 3] # referee included
54 OTHER_PROFILES = [Const.PROFILE[1], Const.PROFILE[3]] 56 OTHER_PROFILES = [Const.PROFILE[1], Const.PROFILE[3]]
55 OTHER_PLAYERS = [Const.JID[1], Const.JID[3]] 57 OTHER_PLAYERS = [Const.JID[1], Const.JID[3]]
56 58
57 59
58 class RadiocolTest(helpers.SatTestCase): 60 class RadiocolTest(helpers.SatTestCase):
59
60 def setUp(self): 61 def setUp(self):
61 self.host = helpers.FakeSAT() 62 self.host = helpers.FakeSAT()
62 63
63 def reinit(self): 64 def reinit(self):
64 self.host.reinit() 65 self.host.reinit()
65 self.host.plugins['ROOM-GAME'] = plugin_room_game.RoomGame(self.host) 66 self.host.plugins["ROOM-GAME"] = plugin_room_game.RoomGame(self.host)
66 self.plugin = plugin.Radiocol(self.host) # must be init after ROOM-GAME 67 self.plugin = plugin.Radiocol(self.host) # must be init after ROOM-GAME
67 self.plugin.testing = True 68 self.plugin.testing = True
68 self.plugin_0045 = self.host.plugins['XEP-0045'] = helpers_plugins.FakeXEP_0045(self.host) 69 self.plugin_0045 = self.host.plugins["XEP-0045"] = helpers_plugins.FakeXEP_0045(
69 self.plugin_0249 = self.host.plugins['XEP-0249'] = helpers_plugins.FakeXEP_0249(self.host) 70 self.host
71 )
72 self.plugin_0249 = self.host.plugins["XEP-0249"] = helpers_plugins.FakeXEP_0249(
73 self.host
74 )
70 for profile in Const.PROFILE: 75 for profile in Const.PROFILE:
71 self.host.getClient(profile) # init self.host.profiles[profile] 76 self.host.getClient(profile) # init self.host.profiles[profile]
72 self.songs = [] 77 self.songs = []
73 self.playlist = [] 78 self.playlist = []
74 self.sound_dir = self.host.memory.getConfig('', 'media_dir') + '/test/sound/' 79 self.sound_dir = self.host.memory.getConfig("", "media_dir") + "/test/sound/"
75 try: 80 try:
76 for filename in os.listdir(self.sound_dir): 81 for filename in os.listdir(self.sound_dir):
77 if filename.endswith('.ogg') or filename.endswith('.mp3'): 82 if filename.endswith(".ogg") or filename.endswith(".mp3"):
78 self.songs.append(filename) 83 self.songs.append(filename)
79 except OSError: 84 except OSError:
80 raise SkipTest('The sound samples in sat_media/test/sound were not found') 85 raise SkipTest("The sound samples in sat_media/test/sound were not found")
81 86
82 def _buildPlayers(self, players=[]): 87 def _buildPlayers(self, players=[]):
83 """@return: the "started" content built with the given players""" 88 """@return: the "started" content built with the given players"""
84 content = "<started" 89 content = "<started"
85 if not players: 90 if not players:
99 @return: the message XML built from the given recipient, message type and content 104 @return: the message XML built from the given recipient, message type and content
100 """ 105 """
101 if isinstance(content, list): 106 if isinstance(content, list):
102 new_content = copy.deepcopy(content) 107 new_content = copy.deepcopy(content)
103 for element in new_content: 108 for element in new_content:
104 if not element.hasAttribute('xmlns'): 109 if not element.hasAttribute("xmlns"):
105 element['xmlns'] = '' 110 element["xmlns"] = ""
106 content = "".join([element.toXml() for element in new_content]) 111 content = "".join([element.toXml() for element in new_content])
107 return "<message to='%s' type='%s'><%s xmlns='%s'>%s</%s></message>" % (to_jid.full(), type_, plugin.RADIOC_TAG, plugin.NC_RADIOCOL, content, plugin.RADIOC_TAG) 112 return "<message to='%s' type='%s'><%s xmlns='%s'>%s</%s></message>" % (
113 to_jid.full(),
114 type_,
115 plugin.RADIOC_TAG,
116 plugin.NC_RADIOCOL,
117 content,
118 plugin.RADIOC_TAG,
119 )
108 120
109 def _rejectSongCb(self, profile_index): 121 def _rejectSongCb(self, profile_index):
110 """Check if the message "song_rejected" has been sent by the referee 122 """Check if the message "song_rejected" has been sent by the referee
111 and process the command with the profile of the uploader 123 and process the command with the profile of the uploader
112 @param profile_index: uploader's profile""" 124 @param profile_index: uploader's profile"""
113 sent = self.host.getSentMessage(0) 125 sent = self.host.getSentMessage(0)
114 content = "<song_rejected xmlns='' reason='Too many songs in queue'/>" 126 content = "<song_rejected xmlns='' reason='Too many songs in queue'/>"
115 self.assertEqualXML(sent.toXml(), self._expectedMessage(JID(ROOM_JID.userhost() + '/' + self.plugin_0045.getNick(0, profile_index), 'normal', content))) 127 self.assertEqualXML(
116 self._roomGameCmd(sent, ['radiocolSongRejected', ROOM_JID.full(), 'Too many songs in queue']) 128 sent.toXml(),
129 self._expectedMessage(
130 JID(
131 ROOM_JID.userhost()
132 + "/"
133 + self.plugin_0045.getNick(0, profile_index),
134 "normal",
135 content,
136 )
137 ),
138 )
139 self._roomGameCmd(
140 sent, ["radiocolSongRejected", ROOM_JID.full(), "Too many songs in queue"]
141 )
117 142
118 def _noUploadCb(self): 143 def _noUploadCb(self):
119 """Check if the message "no_upload" has been sent by the referee 144 """Check if the message "no_upload" has been sent by the referee
120 and process the command with the profiles of each room users""" 145 and process the command with the profiles of each room users"""
121 sent = self.host.getSentMessage(0) 146 sent = self.host.getSentMessage(0)
122 content = "<no_upload xmlns=''/>" 147 content = "<no_upload xmlns=''/>"
123 self.assertEqualXML(sent.toXml(), self._expectedMessage(ROOM_JID, 'groupchat', content)) 148 self.assertEqualXML(
124 self._roomGameCmd(sent, ['radiocolNoUpload', ROOM_JID.full()]) 149 sent.toXml(), self._expectedMessage(ROOM_JID, "groupchat", content)
150 )
151 self._roomGameCmd(sent, ["radiocolNoUpload", ROOM_JID.full()])
125 152
126 def _uploadOkCb(self): 153 def _uploadOkCb(self):
127 """Check if the message "upload_ok" has been sent by the referee 154 """Check if the message "upload_ok" has been sent by the referee
128 and process the command with the profiles of each room users""" 155 and process the command with the profiles of each room users"""
129 sent = self.host.getSentMessage(0) 156 sent = self.host.getSentMessage(0)
130 content = "<upload_ok xmlns=''/>" 157 content = "<upload_ok xmlns=''/>"
131 self.assertEqualXML(sent.toXml(), self._expectedMessage(ROOM_JID, 'groupchat', content)) 158 self.assertEqualXML(
132 self._roomGameCmd(sent, ['radiocolUploadOk', ROOM_JID.full()]) 159 sent.toXml(), self._expectedMessage(ROOM_JID, "groupchat", content)
160 )
161 self._roomGameCmd(sent, ["radiocolUploadOk", ROOM_JID.full()])
133 162
134 def _preloadCb(self, attrs, profile_index): 163 def _preloadCb(self, attrs, profile_index):
135 """Check if the message "preload" has been sent by the referee 164 """Check if the message "preload" has been sent by the referee
136 and process the command with the profiles of each room users 165 and process the command with the profiles of each room users
137 @param attrs: information dict about the song 166 @param attrs: information dict about the song
138 @param profile_index: profile index of the uploader 167 @param profile_index: profile index of the uploader
139 """ 168 """
140 sent = self.host.getSentMessage(0) 169 sent = self.host.getSentMessage(0)
141 attrs['sender'] = self.plugin_0045.getNick(0, profile_index) 170 attrs["sender"] = self.plugin_0045.getNick(0, profile_index)
142 radiocol_elt = domish.generateElementsNamed(sent.elements(), 'radiocol').next() 171 radiocol_elt = domish.generateElementsNamed(sent.elements(), "radiocol").next()
143 preload_elt = domish.generateElementsNamed(radiocol_elt.elements(), 'preload').next() 172 preload_elt = domish.generateElementsNamed(
144 attrs['timestamp'] = preload_elt['timestamp'] # we could not guess it... 173 radiocol_elt.elements(), "preload"
145 content = "<preload xmlns='' %s/>" % " ".join(["%s='%s'" % (attr, attrs[attr]) for attr in attrs]) 174 ).next()
146 if sent.hasAttribute('from'): 175 attrs["timestamp"] = preload_elt["timestamp"] # we could not guess it...
147 del sent['from'] 176 content = "<preload xmlns='' %s/>" % " ".join(
148 self.assertEqualXML(sent.toXml(), self._expectedMessage(ROOM_JID, 'groupchat', content)) 177 ["%s='%s'" % (attr, attrs[attr]) for attr in attrs]
149 self._roomGameCmd(sent, ['radiocolPreload', ROOM_JID.full(), attrs['timestamp'], attrs['filename'], attrs['title'], attrs['artist'], attrs['album'], attrs['sender']]) 178 )
179 if sent.hasAttribute("from"):
180 del sent["from"]
181 self.assertEqualXML(
182 sent.toXml(), self._expectedMessage(ROOM_JID, "groupchat", content)
183 )
184 self._roomGameCmd(
185 sent,
186 [
187 "radiocolPreload",
188 ROOM_JID.full(),
189 attrs["timestamp"],
190 attrs["filename"],
191 attrs["title"],
192 attrs["artist"],
193 attrs["album"],
194 attrs["sender"],
195 ],
196 )
150 197
151 def _playNextSongCb(self): 198 def _playNextSongCb(self):
152 """Check if the message "play" has been sent by the referee 199 """Check if the message "play" has been sent by the referee
153 and process the command with the profiles of each room users""" 200 and process the command with the profiles of each room users"""
154 sent = self.host.getSentMessage(0) 201 sent = self.host.getSentMessage(0)
155 filename = self.playlist.pop(0) 202 filename = self.playlist.pop(0)
156 content = "<play xmlns='' filename='%s' />" % filename 203 content = "<play xmlns='' filename='%s' />" % filename
157 self.assertEqualXML(sent.toXml(), self._expectedMessage(ROOM_JID, 'groupchat', content)) 204 self.assertEqualXML(
158 self._roomGameCmd(sent, ['radiocolPlay', ROOM_JID.full(), filename]) 205 sent.toXml(), self._expectedMessage(ROOM_JID, "groupchat", content)
206 )
207 self._roomGameCmd(sent, ["radiocolPlay", ROOM_JID.full(), filename])
159 208
160 game_data = self.plugin.games[ROOM_JID] 209 game_data = self.plugin.games[ROOM_JID]
161 if len(game_data['queue']) == plugin.QUEUE_LIMIT - 1: 210 if len(game_data["queue"]) == plugin.QUEUE_LIMIT - 1:
162 self._uploadOkCb() 211 self._uploadOkCb()
163 212
164 def _addSongCb(self, d, filepath, profile_index): 213 def _addSongCb(self, d, filepath, profile_index):
165 """Check if the message "song_added" has been sent by the uploader 214 """Check if the message "song_added" has been sent by the uploader
166 and process the command with the profile of the referee 215 and process the command with the profile of the referee
172 self.fail("OGG or MP3 song could not be added!") 221 self.fail("OGG or MP3 song could not be added!")
173 222
174 game_data = self.plugin.games[ROOM_JID] 223 game_data = self.plugin.games[ROOM_JID]
175 224
176 # this is copied from the plugin 225 # this is copied from the plugin
177 if filepath.lower().endswith('.mp3'): 226 if filepath.lower().endswith(".mp3"):
178 actual_song = MP3(filepath) 227 actual_song = MP3(filepath)
179 try: 228 try:
180 song = EasyID3(filepath) 229 song = EasyID3(filepath)
181 230
182 class Info(object): 231 class Info(object):
183 def __init__(self, length): 232 def __init__(self, length):
184 self.length = length 233 self.length = length
234
185 song.info = Info(actual_song.info.length) 235 song.info = Info(actual_song.info.length)
186 except ID3NoHeaderError: 236 except ID3NoHeaderError:
187 song = actual_song 237 song = actual_song
188 else: 238 else:
189 song = OggVorbis(filepath) 239 song = OggVorbis(filepath)
190 240
191 attrs = {'filename': os.path.basename(filepath), 241 attrs = {
192 'title': song.get("title", ["Unknown"])[0], 242 "filename": os.path.basename(filepath),
193 'artist': song.get("artist", ["Unknown"])[0], 243 "title": song.get("title", ["Unknown"])[0],
194 'album': song.get("album", ["Unknown"])[0], 244 "artist": song.get("artist", ["Unknown"])[0],
195 'length': str(song.info.length) 245 "album": song.get("album", ["Unknown"])[0],
196 } 246 "length": str(song.info.length),
197 self.assertEqual(game_data['to_delete'][attrs['filename']], filepath) 247 }
198 248 self.assertEqual(game_data["to_delete"][attrs["filename"]], filepath)
199 content = "<song_added xmlns='' %s/>" % " ".join(["%s='%s'" % (attr, attrs[attr]) for attr in attrs]) 249
250 content = "<song_added xmlns='' %s/>" % " ".join(
251 ["%s='%s'" % (attr, attrs[attr]) for attr in attrs]
252 )
200 sent = self.host.getSentMessage(profile_index) 253 sent = self.host.getSentMessage(profile_index)
201 self.assertEqualXML(sent.toXml(), self._expectedMessage(REFEREE_FULL, 'normal', content)) 254 self.assertEqualXML(
202 255 sent.toXml(), self._expectedMessage(REFEREE_FULL, "normal", content)
203 reject_song = len(game_data['queue']) >= plugin.QUEUE_LIMIT 256 )
204 no_upload = len(game_data['queue']) + 1 >= plugin.QUEUE_LIMIT 257
205 play_next = not game_data['playing'] and len(game_data['queue']) + 1 == plugin.QUEUE_TO_START 258 reject_song = len(game_data["queue"]) >= plugin.QUEUE_LIMIT
259 no_upload = len(game_data["queue"]) + 1 >= plugin.QUEUE_LIMIT
260 play_next = (
261 not game_data["playing"]
262 and len(game_data["queue"]) + 1 == plugin.QUEUE_TO_START
263 )
206 264
207 self._roomGameCmd(sent, profile_index) # queue unchanged or +1 265 self._roomGameCmd(sent, profile_index) # queue unchanged or +1
208 if reject_song: 266 if reject_song:
209 self._rejectSongCb(profile_index) 267 self._rejectSongCb(profile_index)
210 return 268 return
211 if no_upload: 269 if no_upload:
212 self._noUploadCb() 270 self._noUploadCb()
213 self._preloadCb(attrs, profile_index) 271 self._preloadCb(attrs, profile_index)
214 self.playlist.append(attrs['filename']) 272 self.playlist.append(attrs["filename"])
215 if play_next: 273 if play_next:
216 self._playNextSongCb() # queue -1 274 self._playNextSongCb() # queue -1
217 275
218 def _roomGameCmd(self, sent, from_index=0, call=[]): 276 def _roomGameCmd(self, sent, from_index=0, call=[]):
219 """Process a command. It is also possible to call this method as 277 """Process a command. It is also possible to call this method as
227 """ 285 """
228 if isinstance(from_index, list): 286 if isinstance(from_index, list):
229 call = from_index 287 call = from_index
230 from_index = 0 288 from_index = 0
231 289
232 sent['from'] = ROOM_JID.full() + '/' + self.plugin_0045.getNick(0, from_index) 290 sent["from"] = ROOM_JID.full() + "/" + self.plugin_0045.getNick(0, from_index)
233 recipient = JID(sent['to']).resource 291 recipient = JID(sent["to"]).resource
234 292
235 # The message could have been sent to a room user (room_jid + '/' + nick), 293 # The message could have been sent to a room user (room_jid + '/' + nick),
236 # but when it is received, the 'to' attribute of the message has been 294 # but when it is received, the 'to' attribute of the message has been
237 # changed to the recipient own JID. We need to simulate that here. 295 # changed to the recipient own JID. We need to simulate that here.
238 if recipient: 296 if recipient:
239 room = self.plugin_0045.getRoom(0, 0) 297 room = self.plugin_0045.getRoom(0, 0)
240 sent['to'] = Const.JID_STR[0] if recipient == room.nick else room.roster[recipient].entity.full() 298 sent["to"] = (
299 Const.JID_STR[0]
300 if recipient == room.nick
301 else room.roster[recipient].entity.full()
302 )
241 303
242 for index in xrange(0, len(Const.PROFILE)): 304 for index in xrange(0, len(Const.PROFILE)):
243 nick = self.plugin_0045.getNick(0, index) 305 nick = self.plugin_0045.getNick(0, index)
244 if nick: 306 if nick:
245 if not recipient or nick == recipient: 307 if not recipient or nick == recipient:
246 if call and (self.plugin.isPlayer(ROOM_JID, nick) or call[0] == 'radiocolStarted'): 308 if call and (
309 self.plugin.isPlayer(ROOM_JID, nick)
310 or call[0] == "radiocolStarted"
311 ):
247 args = copy.deepcopy(call) 312 args = copy.deepcopy(call)
248 args.append(Const.PROFILE[index]) 313 args.append(Const.PROFILE[index])
249 self.host.bridge.expectCall(*args) 314 self.host.bridge.expectCall(*args)
250 self.plugin.room_game_cmd(sent, Const.PROFILE[index]) 315 self.plugin.room_game_cmd(sent, Const.PROFILE[index])
251 316
253 """Synchronize one player when he joins a running game. 318 """Synchronize one player when he joins a running game.
254 @param sync_data: result from self.plugin.getSyncData 319 @param sync_data: result from self.plugin.getSyncData
255 @param profile_index: index of the profile to be synchronized 320 @param profile_index: index of the profile to be synchronized
256 """ 321 """
257 for nick in sync_data: 322 for nick in sync_data:
258 expected = self._expectedMessage(JID(ROOM_JID.userhost() + '/' + nick), 'normal', sync_data[nick]) 323 expected = self._expectedMessage(
324 JID(ROOM_JID.userhost() + "/" + nick), "normal", sync_data[nick]
325 )
259 sent = self.host.getSentMessage(0) 326 sent = self.host.getSentMessage(0)
260 self.assertEqualXML(sent.toXml(), expected) 327 self.assertEqualXML(sent.toXml(), expected)
261 for elt in sync_data[nick]: 328 for elt in sync_data[nick]:
262 if elt.name == 'preload': 329 if elt.name == "preload":
263 self.host.bridge.expectCall('radiocolPreload', ROOM_JID.full(), elt['timestamp'], elt['filename'], elt['title'], elt['artist'], elt['album'], elt['sender'], Const.PROFILE[profile_index]) 330 self.host.bridge.expectCall(
264 elif elt.name == 'play': 331 "radiocolPreload",
265 self.host.bridge.expectCall('radiocolPlay', ROOM_JID.full(), elt['filename'], Const.PROFILE[profile_index]) 332 ROOM_JID.full(),
266 elif elt.name == 'no_upload': 333 elt["timestamp"],
267 self.host.bridge.expectCall('radiocolNoUpload', ROOM_JID.full(), Const.PROFILE[profile_index]) 334 elt["filename"],
335 elt["title"],
336 elt["artist"],
337 elt["album"],
338 elt["sender"],
339 Const.PROFILE[profile_index],
340 )
341 elif elt.name == "play":
342 self.host.bridge.expectCall(
343 "radiocolPlay",
344 ROOM_JID.full(),
345 elt["filename"],
346 Const.PROFILE[profile_index],
347 )
348 elif elt.name == "no_upload":
349 self.host.bridge.expectCall(
350 "radiocolNoUpload", ROOM_JID.full(), Const.PROFILE[profile_index]
351 )
268 sync_data[nick] 352 sync_data[nick]
269 self._roomGameCmd(sent, []) 353 self._roomGameCmd(sent, [])
270 354
271 def _joinRoom(self, room, nicks, player_index, sync=True): 355 def _joinRoom(self, room, nicks, player_index, sync=True):
272 """Make a player join a room and update the list of nicks 356 """Make a player join a room and update the list of nicks
278 user_nick = self.plugin_0045.joinRoom(0, player_index) 362 user_nick = self.plugin_0045.joinRoom(0, player_index)
279 self.plugin.userJoinedTrigger(room, room.roster[user_nick], PROFILE) 363 self.plugin.userJoinedTrigger(room, room.roster[user_nick], PROFILE)
280 if player_index not in PLAYERS_INDICES: 364 if player_index not in PLAYERS_INDICES:
281 # this user is actually not a player 365 # this user is actually not a player
282 self.assertFalse(self.plugin.isPlayer(ROOM_JID, user_nick)) 366 self.assertFalse(self.plugin.isPlayer(ROOM_JID, user_nick))
283 to_jid, type_ = (JID(ROOM_JID.userhost() + '/' + user_nick), 'normal') 367 to_jid, type_ = (JID(ROOM_JID.userhost() + "/" + user_nick), "normal")
284 else: 368 else:
285 # this user is a player 369 # this user is a player
286 self.assertTrue(self.plugin.isPlayer(ROOM_JID, user_nick)) 370 self.assertTrue(self.plugin.isPlayer(ROOM_JID, user_nick))
287 nicks.append(user_nick) 371 nicks.append(user_nick)
288 to_jid, type_ = (ROOM_JID, 'groupchat') 372 to_jid, type_ = (ROOM_JID, "groupchat")
289 373
290 # Check that the message "players" has been sent by the referee 374 # Check that the message "players" has been sent by the referee
291 expected = self._expectedMessage(to_jid, type_, self._buildPlayers(nicks)) 375 expected = self._expectedMessage(to_jid, type_, self._buildPlayers(nicks))
292 sent = self.host.getSentMessage(0) 376 sent = self.host.getSentMessage(0)
293 self.assertEqualXML(sent.toXml(), expected) 377 self.assertEqualXML(sent.toXml(), expected)
294 378
295 # Process the command with the profiles of each room users 379 # Process the command with the profiles of each room users
296 self._roomGameCmd(sent, ['radiocolStarted', ROOM_JID.full(), REFEREE_FULL.full(), nicks, [plugin.QUEUE_TO_START, plugin.QUEUE_LIMIT]]) 380 self._roomGameCmd(
381 sent,
382 [
383 "radiocolStarted",
384 ROOM_JID.full(),
385 REFEREE_FULL.full(),
386 nicks,
387 [plugin.QUEUE_TO_START, plugin.QUEUE_LIMIT],
388 ],
389 )
297 390
298 if sync: 391 if sync:
299 self._syncCb(self.plugin._getSyncData(ROOM_JID, [user_nick]), player_index) 392 self._syncCb(self.plugin._getSyncData(ROOM_JID, [user_nick]), player_index)
300 393
301 def _leaveRoom(self, room, nicks, player_index): 394 def _leaveRoom(self, room, nicks, player_index):
320 dst_filepath = unicode(uuid.uuid1()) 413 dst_filepath = unicode(uuid.uuid1())
321 expect_io_error = True 414 expect_io_error = True
322 else: 415 else:
323 song_index = song_index % len(self.songs) 416 song_index = song_index % len(self.songs)
324 src_filename = self.songs[song_index] 417 src_filename = self.songs[song_index]
325 dst_filepath = '/tmp/%s%s' % (uuid.uuid1(), os.path.splitext(src_filename)[1]) 418 dst_filepath = "/tmp/%s%s" % (uuid.uuid1(), os.path.splitext(src_filename)[1])
326 shutil.copy(self.sound_dir + src_filename, dst_filepath) 419 shutil.copy(self.sound_dir + src_filename, dst_filepath)
327 expect_io_error = False 420 expect_io_error = False
328 421
329 try: 422 try:
330 d = self.plugin.radiocolSongAdded(REFEREE_FULL, dst_filepath, Const.PROFILE[profile_index]) 423 d = self.plugin.radiocolSongAdded(
424 REFEREE_FULL, dst_filepath, Const.PROFILE[profile_index]
425 )
331 except IOError: 426 except IOError:
332 self.assertTrue(expect_io_error) 427 self.assertTrue(expect_io_error)
333 return 428 return
334 429
335 self.assertFalse(expect_io_error) 430 self.assertFalse(expect_io_error)
338 def eb(failure): 433 def eb(failure):
339 if not isinstance(failure, Failure): 434 if not isinstance(failure, Failure):
340 self.fail("Adding a song which is not OGG nor MP3 should fail!") 435 self.fail("Adding a song which is not OGG nor MP3 should fail!")
341 self.assertEqual(failure.value.__class__, exceptions.DataError) 436 self.assertEqual(failure.value.__class__, exceptions.DataError)
342 437
343 if src_filename.endswith('.ogg') or src_filename.endswith('.mp3'): 438 if src_filename.endswith(".ogg") or src_filename.endswith(".mp3"):
344 d.addCallbacks(cb, cb) 439 d.addCallbacks(cb, cb)
345 else: 440 else:
346 d.addCallbacks(eb, eb) 441 d.addCallbacks(eb, eb)
347 442
348 def test_init(self): 443 def test_init(self):
360 self.assertTrue(self.plugin._gameExists(ROOM_JID, True)) 455 self.assertTrue(self.plugin._gameExists(ROOM_JID, True))
361 room = self.plugin_0045.getRoom(0, 0) 456 room = self.plugin_0045.getRoom(0, 0)
362 nicks = [self.plugin_0045.getNick(0, 0)] 457 nicks = [self.plugin_0045.getNick(0, 0)]
363 458
364 sent = self.host.getSentMessage(0) 459 sent = self.host.getSentMessage(0)
365 self.assertEqualXML(sent.toXml(), self._expectedMessage(ROOM_JID, 'groupchat', self._buildPlayers(nicks))) 460 self.assertEqualXML(
366 self._roomGameCmd(sent, ['radiocolStarted', ROOM_JID.full(), REFEREE_FULL.full(), nicks, [plugin.QUEUE_TO_START, plugin.QUEUE_LIMIT]]) 461 sent.toXml(),
462 self._expectedMessage(ROOM_JID, "groupchat", self._buildPlayers(nicks)),
463 )
464 self._roomGameCmd(
465 sent,
466 [
467 "radiocolStarted",
468 ROOM_JID.full(),
469 REFEREE_FULL.full(),
470 nicks,
471 [plugin.QUEUE_TO_START, plugin.QUEUE_LIMIT],
472 ],
473 )
367 474
368 self._joinRoom(room, nicks, 1) # player joins 475 self._joinRoom(room, nicks, 1) # player joins
369 self._joinRoom(room, nicks, 4) # user not playing joins 476 self._joinRoom(room, nicks, 4) # user not playing joins
370 477
371 song_index = 0 478 song_index = 0
372 self._uploadSong(song_index, 0) # ogg or mp3 file should exist in sat_media/test/song 479 self._uploadSong(
480 song_index, 0
481 ) # ogg or mp3 file should exist in sat_media/test/song
373 self._uploadSong(None, 0) # non existing file 482 self._uploadSong(None, 0) # non existing file
374 483
375 # another songs are added by Const.JID[1] until the radio starts + 1 to fill the queue 484 # another songs are added by Const.JID[1] until the radio starts + 1 to fill the queue
376 # when the first song starts + 1 to be rejected because the queue is full 485 # when the first song starts + 1 to be rejected because the queue is full
377 for song_index in xrange(1, plugin.QUEUE_TO_START + 1): 486 for song_index in xrange(1, plugin.QUEUE_TO_START + 1):
378 self._uploadSong(song_index, 1) 487 self._uploadSong(song_index, 1)
379 488
380 self.plugin.playNext(Const.MUC[0], PROFILE) # simulate the end of the first song 489 self.plugin.playNext(Const.MUC[0], PROFILE) # simulate the end of the first song
381 self._playNextSongCb() 490 self._playNextSongCb()
382 self._uploadSong(song_index, 1) # now the song is accepted and the queue is full again 491 self._uploadSong(
492 song_index, 1
493 ) # now the song is accepted and the queue is full again
383 494
384 self._joinRoom(room, nicks, 3) # new player joins 495 self._joinRoom(room, nicks, 3) # new player joins
385 496
386 self.plugin.playNext(Const.MUC[0], PROFILE) # the second song finishes 497 self.plugin.playNext(Const.MUC[0], PROFILE) # the second song finishes
387 self._playNextSongCb() 498 self._playNextSongCb()
394 self._playNextSongCb() 505 self._playNextSongCb()
395 self.plugin.playNext(Const.MUC[0], PROFILE) 506 self.plugin.playNext(Const.MUC[0], PROFILE)
396 self._playNextSongCb() 507 self._playNextSongCb()
397 508
398 for filename in self.playlist: 509 for filename in self.playlist:
399 self.plugin.deleteFile('/tmp/' + filename) 510 self.plugin.deleteFile("/tmp/" + filename)
400 511
401 return defer.succeed(None) 512 return defer.succeed(None)
402 513
403 def tearDown(self, *args, **kwargs): 514 def tearDown(self, *args, **kwargs):
404 """Clean the reactor""" 515 """Clean the reactor"""