chiark / gitweb /
New tests/recode.py converts filenames back and forth between UTF-8
[disorder] / tests / dtest.py
... / ...
CommitLineData
1#-*-python-*-
2#
3# This file is part of DisOrder.
4# Copyright (C) 2007 ,2008 Richard Kettlewell
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 2 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, but
12# WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14# 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, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19# USA
20#
21
22"""Utility module used by tests"""
23
24import os,os.path,subprocess,sys,re,time,unicodedata,random,socket
25
26def fatal(s):
27 """Write an error message and exit"""
28 sys.stderr.write("ERROR: %s\n" % s)
29 sys.exit(1)
30
31# Identify the top build directory
32cwd = os.getcwd()
33if os.path.exists("config.h"):
34 top_builddir = cwd
35elif os.path.exists("alltests"):
36 top_builddir = os.path.dirname(cwd)
37else:
38 fatal("cannot identify build directory")
39
40# Make sure the Python build directory is on the module search path
41sys.path.insert(0, os.path.join(top_builddir, "python"))
42import disorder
43
44# Make sure the build directories are on the executable search path
45ospath = os.environ["PATH"].split(os.pathsep)
46ospath.insert(0, os.path.join(top_builddir, "server"))
47ospath.insert(0, os.path.join(top_builddir, "clients"))
48ospath.insert(0, os.path.join(top_builddir, "tests"))
49os.environ["PATH"] = os.pathsep.join(ospath)
50
51# Parse the makefile in the current directory to identify the source directory
52top_srcdir = None
53for l in file("Makefile"):
54 r = re.match("top_srcdir *= *(.*)", l)
55 if r:
56 top_srcdir = r.group(1)
57 break
58if not top_srcdir:
59 fatal("cannot identify source directory")
60
61# The tests source directory must be on the module search path already since
62# we found dtest.py
63
64# -----------------------------------------------------------------------------
65
66def copyfile(a,b):
67 """copyfile(A, B)
68Copy A to B."""
69 open(b,"w").write(open(a).read())
70
71def to_unicode(s):
72 """Convert UTF-8 to unicode. A no-op if already unicode."""
73 if type(s) == unicode:
74 return s
75 else:
76 return unicode(s, "UTF-8")
77
78def nfc(s):
79 """Convert UTF-8 string or unicode to NFC unicode."""
80 return unicodedata.normalize("NFC", to_unicode(s))
81
82def maketrack(s):
83 """maketrack(S)
84
85Make track with relative path S exist"""
86 trackpath = "%s/%s" % (tracks, s)
87 trackdir = os.path.dirname(trackpath)
88 if not os.path.exists(trackdir):
89 os.makedirs(trackdir)
90 copyfile("%s/sounds/slap.ogg" % top_srcdir, trackpath)
91 # We record the tracks we created so they can be tested against
92 # server responses. We put them into NFC since that's what the server
93 # uses internally.
94 bits = nfc(s).split('/')
95 dp = tracks
96 for d in bits [0:-1]:
97 dd = "%s/%s" % (dp, d)
98 if dp not in dirs_by_dir:
99 dirs_by_dir[dp] = []
100 if dd not in dirs_by_dir[dp]:
101 dirs_by_dir[dp].append(dd)
102 dp = "%s/%s" % (dp, d)
103 if dp not in files_by_dir:
104 files_by_dir[dp] = []
105 files_by_dir[dp].append("%s/%s" % (dp, bits[-1]))
106
107def stdtracks():
108 # We create some tracks with non-ASCII characters in the name and
109 # we (currently) force UTF-8.
110 #
111 # On a traditional UNIX filesystem, that treats filenames as byte strings
112 # with special significant for '/', this should just work, though the
113 # names will look wrong to ls(1) in a non UTF-8 locale.
114 #
115 # On Apple HFS+ filenames normalized to a decomposed form that isn't quite
116 # NFD, so our attempts to have both normalized and denormalized filenames
117 # is frustrated. Provided we test on traditional filesytsems too this
118 # shouldn't be a problem.
119 # (See http://developer.apple.com/qa/qa2001/qa1173.html)
120
121 global dirs_by_dir, files_by_dir
122 dirs_by_dir={}
123 files_by_dir={}
124
125 # C3 8C = 00CC LATIN CAPITAL LETTER I WITH GRAVE
126 # (in NFC)
127 maketrack("Joe Bloggs/First Album/01:F\xC3\x8Crst track.ogg")
128
129 maketrack("Joe Bloggs/First Album/02:Second track.ogg")
130
131 # CC 81 = 0301 COMBINING ACUTE ACCENT
132 # (giving an NFD i-acute)
133 maketrack("Joe Bloggs/First Album/03:ThI\xCC\x81rd track.ogg")
134 # ...hopefuly giving C3 8D = 00CD LATIN CAPITAL LETTER I WITH ACUTE
135 maketrack("Joe Bloggs/First Album/04:Fourth track.ogg")
136 maketrack("Joe Bloggs/First Album/05:Fifth track.ogg")
137 maketrack("Joe Bloggs/Second Album/01:First track.ogg")
138 maketrack("Joe Bloggs/Second Album/02:Second track.ogg")
139 maketrack("Joe Bloggs/Second Album/03:Third track.ogg")
140 maketrack("Joe Bloggs/Second Album/04:Fourth track.ogg")
141 maketrack("Joe Bloggs/Second Album/05:Fifth track.ogg")
142 maketrack("Joe Bloggs/Third Album/01:First_track.ogg")
143 maketrack("Joe Bloggs/Third Album/02:Second_track.ogg")
144 maketrack("Joe Bloggs/Third Album/03:Third_track.ogg")
145 maketrack("Joe Bloggs/Third Album/04:Fourth_track.ogg")
146 maketrack("Joe Bloggs/Third Album/05:Fifth_track.ogg")
147 maketrack("Fred Smith/Boring/01:Dull.ogg")
148 maketrack("Fred Smith/Boring/02:Tedious.ogg")
149 maketrack("Fred Smith/Boring/03:Drum Solo.ogg")
150 maketrack("Fred Smith/Boring/04:Yawn.ogg")
151 maketrack("misc/blahblahblah.ogg")
152 maketrack("Various/Greatest Hits/01:Jim Whatever - Spong.ogg")
153 maketrack("Various/Greatest Hits/02:Joe Bloggs - Yadda.ogg")
154
155def bindable(p):
156 """bindable(P)
157
158 Return True iff UDP port P is bindable, else False"""
159 s = socket.socket(socket.AF_INET,
160 socket.SOCK_DGRAM,
161 socket.IPPROTO_UDP)
162 try:
163 s.bind(("127.0.0.1", p))
164 s.close()
165 return True
166 except:
167 return False
168
169def default_config(encoding="UTF-8"):
170 """Write the default config"""
171 open("%s/config" % testroot, "w").write(
172 """home %s
173collection fs %s %s/tracks
174scratch %s/scratch.ogg
175gap 0
176stopword 01 02 03 04 05 06 07 08 09 10
177stopword 1 2 3 4 5 6 7 8 9
178stopword 11 12 13 14 15 16 17 18 19 20
179stopword 21 22 23 24 25 26 27 28 29 30
180stopword the a an and to too in on of we i am as im for is
181username fred
182password fredpass
183plugins
184plugins %s/plugins
185plugins %s/plugins/.libs
186player *.mp3 execraw disorder-decode
187player *.ogg execraw disorder-decode
188player *.wav execraw disorder-decode
189player *.flac execraw disorder-decode
190tracklength *.mp3 disorder-tracklength
191tracklength *.ogg disorder-tracklength
192tracklength *.wav disorder-tracklength
193tracklength *.flac disorder-tracklength
194api network
195broadcast 127.0.0.1 %d
196broadcast_from 127.0.0.1 %d
197mail_sender no.such.user.sorry@greenend.org.uk
198""" % (testroot, encoding, testroot, testroot, top_builddir, top_builddir,
199 port, port + 1))
200
201def common_setup():
202 remove_dir(testroot)
203 os.mkdir(testroot)
204 # Choose a port
205 global port
206 port = random.randint(49152, 65535)
207 while not bindable(port + 1):
208 print "port %d is not bindable, trying another" % (port + 1)
209 port = random.randint(49152, 65535)
210 # Log anything sent to that port
211 packetlog = "%s/packetlog" % testroot
212 subprocess.Popen(["disorder-udplog",
213 "--output", packetlog,
214 "127.0.0.1", "%d" % port])
215 # disorder-udplog will quit when its parent process terminates
216 copyfile("%s/sounds/scratch.ogg" % top_srcdir,
217 "%s/scratch.ogg" % testroot)
218 default_config()
219
220def start_daemon():
221 """start_daemon()
222
223Start the daemon."""
224 global daemon, errs, port
225 assert daemon == None, "no daemon running"
226 if not bindable(port + 1):
227 print "waiting for port %d to become bindable again..." % (port + 1)
228 time.sleep(1)
229 while not bindable(port + 1):
230 time.sleep(1)
231 print " starting daemon"
232 # remove the socket if it exists
233 socket = "%s/socket" % testroot
234 try:
235 os.remove(socket)
236 except:
237 pass
238 daemon = subprocess.Popen(["disorderd",
239 "--foreground",
240 "--config", "%s/config" % testroot],
241 stderr=errs)
242 # Wait for the socket to be created
243 waited = 0
244 while not os.path.exists(socket):
245 rc = daemon.poll()
246 if rc is not None:
247 print "FATAL: daemon failed to start up"
248 sys.exit(1)
249 waited += 1
250 if waited == 1:
251 print " waiting for socket..."
252 elif waited >= 60:
253 print "FATAL: took too long for socket to appear"
254 sys.exit(1)
255 time.sleep(1)
256 if waited > 0:
257 print " took about %ds for socket to appear" % waited
258
259def create_user(username="fred", password="fredpass"):
260 """create_user(USERNAME, PASSWORD)
261
262 Create a user, abusing direct database access to do so. Gives the
263 user rights 'all', allowing them to do anything."""
264 print " creating user %s" % username
265 command(["disorder",
266 "--config", disorder._configfile, "--no-per-user-config",
267 "--user", "root", "adduser", username, password])
268 command(["disorder",
269 "--config", disorder._configfile, "--no-per-user-config",
270 "--user", "root", "edituser", username, "rights", "all"])
271
272def rescan(c=None):
273 class rescan_monitor(disorder.monitor):
274 def rescanned(self):
275 return False
276 if c is None:
277 c = disorder.client()
278 m = rescan_monitor()
279 print " initiating rescan"
280 c.rescan()
281 print " waiting for rescan to complete"
282 m.run()
283 print " rescan completed"
284
285def stop_daemon():
286 """stop_daemon()
287
288Stop the daemon if it has not stopped already"""
289 global daemon
290 if daemon == None:
291 return
292 rc = daemon.poll()
293 if rc == None:
294 print " stopping daemon"
295 disorder.client().shutdown()
296 print " waiting for daemon"
297 rc = daemon.wait()
298 print " daemon has stopped"
299 else:
300 print " daemon already stopped"
301 daemon = None
302
303def run(module=None, report=True):
304 """dtest.run(MODULE)
305
306 Run the test in MODULE. This can be a string (in which case the module
307 will be imported) or a module object."""
308 global tests
309 tests += 1
310 # Locate the test module
311 if module is None:
312 # We're running a test stand-alone
313 import __main__
314 module = __main__
315 name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
316 else:
317 # We've been passed a module or a module name
318 if type(module) == str:
319 module = __import__(module)
320 name = module.__name__
321 # Open the error log
322 global errs
323 logfile = "%s.log" % name
324 try:
325 os.remove(logfile)
326 except:
327 pass
328 errs = open(logfile, "a")
329 # Ensure that disorder.py uses the test installation
330 disorder._configfile = "%s/config" % testroot
331 disorder._userconf = False
332 # Make config file etc
333 common_setup()
334 # Create some standard tracks
335 stdtracks()
336 try:
337 module.test()
338 finally:
339 stop_daemon()
340 if report:
341 if failures:
342 print " FAILED"
343 sys.exit(1)
344 else:
345 print " OK"
346
347def remove_dir(d):
348 """remove_dir(D)
349
350Recursively delete directory D"""
351 if os.path.lexists(d):
352 if os.path.isdir(d):
353 for dd in os.listdir(d):
354 remove_dir("%s/%s" % (d, dd))
355 os.rmdir(d)
356 else:
357 os.remove(d)
358
359def lists_have_same_contents(l1, l2):
360 """lists_have_same_contents(L1, L2)
361
362 Return True if L1 and L2 have equal members, in any order; else False."""
363 s1 = []
364 s1.extend(l1)
365 s1.sort()
366 s2 = []
367 s2.extend(l2)
368 s2.sort()
369 return map(nfc, s1) == map(nfc, s2)
370
371def check_files(chatty=True):
372 c = disorder.client()
373 failures = 0
374 for d in dirs_by_dir:
375 xdirs = dirs_by_dir[d]
376 dirs = c.directories(d)
377 if not lists_have_same_contents(xdirs, dirs):
378 if chatty:
379 print
380 print "directory: %s" % d
381 print "expected: %s" % xdirs
382 print "got: %s" % dirs
383 failures += 1
384 for d in files_by_dir:
385 xfiles = files_by_dir[d]
386 files = c.files(d)
387 if not lists_have_same_contents(xfiles, files):
388 if chatty:
389 print
390 print "directory: %s" % d
391 print "expected: %s" % xfiles
392 print "got: %s" % files
393 failures += 1
394 return failures
395
396def command(args):
397 """Execute a command given as a list and return its stdout"""
398 p = subprocess.Popen(args, stdout=subprocess.PIPE)
399 lines = p.stdout.readlines()
400 rc = p.wait()
401 assert rc == 0, ("%s returned status %s" % (args, rc))
402 return lines
403
404# -----------------------------------------------------------------------------
405# Common setup
406
407tests = 0
408failures = 0
409daemon = None
410testroot = "%s/tests/testroot" % top_builddir
411tracks = "%s/tracks" % testroot