3 # This file is part of DisOrder.
4 # Copyright (C) 2007 Richard Kettlewell
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.
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.
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
22 """Utility module used by tests"""
24 import os,os.path,subprocess,sys,re,time,unicodedata,random,socket
27 """Write an error message and exit"""
28 sys.stderr.write("ERROR: %s\n" % s)
31 # Identify the top build directory
33 if os.path.exists("config.h"):
35 elif os.path.exists("alltests"):
36 top_builddir = os.path.dirname(cwd)
38 fatal("cannot identify build directory")
40 # Make sure the Python build directory is on the module search path
41 sys.path.insert(0, os.path.join(top_builddir, "python"))
44 # Make sure the build directories are on the executable search path
45 ospath = os.environ["PATH"].split(os.pathsep)
46 ospath.insert(0, os.path.join(top_builddir, "server"))
47 ospath.insert(0, os.path.join(top_builddir, "clients"))
48 os.environ["PATH"] = os.pathsep.join(ospath)
50 # Parse the makefile in the current directory to identify the source directory
52 for l in file("Makefile"):
53 r = re.match("top_srcdir *= *(.*)", l)
55 top_srcdir = r.group(1)
58 fatal("cannot identify source directory")
60 # The tests source directory must be on the module search path already since
63 # -----------------------------------------------------------------------------
68 open(b,"w").write(open(a).read())
71 """Convert UTF-8 to unicode. A no-op if already unicode."""
72 if type(s) == unicode:
75 return unicode(s, "UTF-8")
78 """Convert UTF-8 string or unicode to NFC unicode."""
79 return unicodedata.normalize("NFC", to_unicode(s))
84 Make track with relative path S exist"""
85 trackpath = "%s/%s" % (tracks, s)
86 trackdir = os.path.dirname(trackpath)
87 if not os.path.exists(trackdir):
89 copyfile("%s/sounds/slap.ogg" % top_srcdir, trackpath)
90 # We record the tracks we created so they can be tested against
91 # server responses. We put them into NFC since that's what the server
93 bits = nfc(s).split('/')
96 dd = "%s/%s" % (dp, d)
97 if dp not in dirs_by_dir:
99 if dd not in dirs_by_dir[dp]:
100 dirs_by_dir[dp].append(dd)
101 dp = "%s/%s" % (dp, d)
102 if dp not in files_by_dir:
103 files_by_dir[dp] = []
104 files_by_dir[dp].append("%s/%s" % (dp, bits[-1]))
107 # We create some tracks with non-ASCII characters in the name and
108 # we (currently) force UTF-8.
110 # On a traditional UNIX filesystem, that treats filenames as byte strings
111 # with special significant for '/', this should just work, though the
112 # names will look wrong to ls(1) in a non UTF-8 locale.
114 # On Apple HFS+ filenames normalized to a decomposed form that isn't quite
115 # NFD, so our attempts to have both normalized and denormalized filenames
116 # is frustrated. Provided we test on traditional filesytsems too this
117 # shouldn't be a problem.
118 # (See http://developer.apple.com/qa/qa2001/qa1173.html)
120 global dirs_by_dir, files_by_dir
124 # C3 8C = 00CC LATIN CAPITAL LETTER I WITH GRAVE
126 maketrack("Joe Bloggs/First Album/01:F\xC3\x8Crst track.ogg")
128 maketrack("Joe Bloggs/First Album/02:Second track.ogg")
130 # CC 81 = 0301 COMBINING ACUTE ACCENT
131 # (giving an NFD i-acute)
132 maketrack("Joe Bloggs/First Album/03:ThI\xCC\x81rd track.ogg")
133 # ...hopefuly giving C3 8D = 00CD LATIN CAPITAL LETTER I WITH ACUTE
134 maketrack("Joe Bloggs/First Album/04:Fourth track.ogg")
135 maketrack("Joe Bloggs/First Album/05:Fifth track.ogg")
136 maketrack("Joe Bloggs/Second Album/01:First track.ogg")
137 maketrack("Joe Bloggs/Second Album/02:Second track.ogg")
138 maketrack("Joe Bloggs/Second Album/03:Third track.ogg")
139 maketrack("Joe Bloggs/Second Album/04:Fourth track.ogg")
140 maketrack("Joe Bloggs/Second Album/05:Fifth track.ogg")
141 maketrack("Joe Bloggs/Third Album/01:First_track.ogg")
142 maketrack("Joe Bloggs/Third Album/02:Second_track.ogg")
143 maketrack("Joe Bloggs/Third Album/03:Third_track.ogg")
144 maketrack("Joe Bloggs/Third Album/04:Fourth_track.ogg")
145 maketrack("Joe Bloggs/Third Album/05:Fifth_track.ogg")
146 maketrack("Fred Smith/Boring/01:Dull.ogg")
147 maketrack("Fred Smith/Boring/02:Tedious.ogg")
148 maketrack("Fred Smith/Boring/03:Drum Solo.ogg")
149 maketrack("Fred Smith/Boring/04:Yawn.ogg")
150 maketrack("misc/blahblahblah.ogg")
151 maketrack("Various/Greatest Hits/01:Jim Whatever - Spong.ogg")
152 maketrack("Various/Greatest Hits/02:Joe Bloggs - Yadda.ogg")
157 Return True iff UDP port P is bindable, else False"""
158 s = socket.socket(socket.AF_INET,
162 s.bind(("127.0.0.1", p))
172 port = random.randint(49152, 65535)
173 while not bindable(port):
174 print "port %d is not bindable, trying another" % port
175 port = random.randint(49152, 65535)
176 open("%s/config" % testroot, "w").write(
178 collection fs UTF-8 %s/tracks
179 scratch %s/scratch.ogg
181 stopword 01 02 03 04 05 06 07 08 09 10
182 stopword 1 2 3 4 5 6 7 8 9
183 stopword 11 12 13 14 15 16 17 18 19 20
184 stopword 21 22 23 24 25 26 27 28 29 30
185 stopword the a an and to too in on of we i am as im for is
192 plugins %s/plugins/.libs
193 player *.mp3 execraw disorder-decode
194 player *.ogg execraw disorder-decode
195 player *.wav execraw disorder-decode
196 player *.flac execraw disorder-decode
197 tracklength *.mp3 disorder-tracklength
198 tracklength *.ogg disorder-tracklength
199 tracklength *.wav disorder-tracklength
200 tracklength *.flac disorder-tracklength
201 speaker_backend network
202 broadcast 127.0.0.1 %d
203 broadcast_from 127.0.0.1 %d
204 """ % (testroot, testroot, testroot, top_builddir, top_builddir,
206 copyfile("%s/sounds/scratch.ogg" % top_srcdir,
207 "%s/scratch.ogg" % testroot)
213 global daemon, errs, port
214 assert daemon == None, "no daemon running"
215 if not bindable(port):
216 print "waiting for speaker socket to become bindable again..."
218 while not bindable(port):
220 print " starting daemon"
221 # remove the socket if it exists
222 socket = "%s/socket" % testroot
227 daemon = subprocess.Popen(["disorderd",
229 "--config", "%s/config" % testroot],
231 # Wait for the socket to be created
233 while not os.path.exists(socket):
236 print "FATAL: daemon failed to start up"
240 print " waiting for socket..."
242 print "FATAL: took too long for socket to appear"
246 print " took about %ds for socket to appear" % waited
251 Stop the daemon if it has not stopped already"""
257 print " stopping daemon"
258 disorder.client().shutdown()
259 print " waiting for daemon"
261 print " daemon has stopped"
263 print " daemon already stopped"
266 def run(module=None, report=True):
269 Run the test in MODULE. This can be a string (in which case the module
270 will be imported) or a module object."""
273 # Locate the test module
275 # We're running a test stand-alone
278 name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
280 # We've been passed a module or a module name
281 if type(module) == str:
282 module = __import__(module)
283 name = module.__name__
286 errs = open("%s.log" % name, "w")
287 # Ensure that disorder.py uses the test installation
288 disorder._configfile = "%s/config" % testroot
289 disorder._userconf = False
290 # Make config file etc
292 # Create some standard tracks
297 except AssertionError, e:
300 print "assertion failed: %s" % e.message
313 Recursively delete directory D"""
314 if os.path.lexists(d):
316 for dd in os.listdir(d):
317 remove_dir("%s/%s" % (d, dd))
322 def lists_have_same_contents(l1, l2):
323 """lists_have_same_contents(L1, L2)
325 Return True if L1 and L2 have equal members, in any order; else False."""
335 c = disorder.client()
337 for d in dirs_by_dir:
338 xdirs = dirs_by_dir[d]
339 dirs = c.directories(d)
340 if not lists_have_same_contents(xdirs, dirs):
342 print "directory: %s" % d
343 print "expected: %s" % xdirs
344 print "got: %s" % dirs
346 for d in files_by_dir:
347 xfiles = files_by_dir[d]
349 if not lists_have_same_contents(xfiles, files):
351 print "directory: %s" % d
352 print "expected: %s" % xfiles
353 print "got: %s" % files
358 """Execute a command given as a list and return its stdout"""
359 p = subprocess.Popen(args, stdout=subprocess.PIPE)
360 lines = p.stdout.readlines()
362 assert rc == 0, ("%s returned status %s" % (args, rc))
365 # -----------------------------------------------------------------------------
371 testroot = "%s/tests/testroot" % top_builddir
372 tracks = "%s/tracks" % testroot