3 # This file is part of DisOrder.
4 # Copyright (C) 2007, 2008 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("../config.h"):
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 ospath
.insert(0, os
.path
.join(top_builddir
, "tests"))
49 os
.environ
["PATH"] = os
.pathsep
.join(ospath
)
51 # Parse the makefile in the current directory to identify the source directory
53 for l
in file("Makefile"):
54 r
= re
.match("top_srcdir *= *(.*)", l
)
56 top_srcdir
= r
.group(1)
59 fatal("cannot identify source directory")
61 # The tests source directory must be on the module search path already since
64 # -----------------------------------------------------------------------------
69 open(b
,"w").write(open(a
).read())
72 """Convert UTF-8 to unicode. A no-op if already unicode."""
73 if type(s
) == unicode:
76 return unicode(s
, "UTF-8")
79 """Convert UTF-8 string or unicode to NFC unicode."""
80 return unicodedata
.normalize("NFC", to_unicode(s
))
85 Make 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
):
90 copyfile("%s/sounds/long.ogg" % top_builddir
, 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
94 bits
= nfc(s
).split('/')
97 dd
= "%s/%s" %
(dp
, d
)
98 if dp
not in dirs_by_dir
:
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]))
108 # We create some tracks with non-ASCII characters in the name and
109 # we (currently) force UTF-8.
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.
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)
121 global dirs_by_dir
, files_by_dir
125 # C3 8C = 00CC LATIN CAPITAL LETTER I WITH GRAVE
127 maketrack("Joe Bloggs/First Album/01:F\xC3\x8Crst track.ogg")
129 maketrack("Joe Bloggs/First Album/02:Second track.ogg")
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")
158 Return True iff UDP port P is bindable, else False"""
159 s
= socket
.socket(socket
.AF_INET
,
163 s
.bind(("127.0.0.1", p
))
169 def default_config(encoding
="UTF-8"):
170 """Write the default config"""
171 open("%s/config" % testroot
, "w").write(
173 collection fs %s %s/tracks
174 scratch %s/scratch.ogg
177 stopword 01 02 03 04 05 06 07 08 09 10
178 stopword 1 2 3 4 5 6 7 8 9
179 stopword 11 12 13 14 15 16 17 18 19 20
180 stopword 21 22 23 24 25 26 27 28 29 30
181 stopword the a an and to too in on of we i am as im for is
186 plugins %s/plugins/.libs
187 player *.mp3 execraw disorder-decode
188 player *.ogg execraw disorder-decode
189 player *.wav execraw disorder-decode
190 player *.flac execraw disorder-decode
191 tracklength *.mp3 disorder-tracklength
192 tracklength *.ogg disorder-tracklength
193 tracklength *.wav disorder-tracklength
194 tracklength *.flac disorder-tracklength
196 broadcast 127.0.0.1 %d
197 broadcast_from 127.0.0.1 %d
198 mail_sender no.such.user.sorry@greenend.org.uk
199 """ %
(testroot
, encoding
, testroot
, testroot
, top_builddir
, top_builddir
,
207 port
= random
.randint(49152, 65535)
208 while not bindable(port
+ 1):
209 print "port %d is not bindable, trying another" %
(port
+ 1)
210 port
= random
.randint(49152, 65535)
211 # Log anything sent to that port
212 packetlog
= "%s/packetlog" % testroot
213 subprocess
.Popen(["disorder-udplog",
214 "--output", packetlog
,
215 "127.0.0.1", "%d" % port
])
216 # disorder-udplog will quit when its parent process terminates
217 copyfile("%s/sounds/scratch.ogg" % top_srcdir
,
218 "%s/scratch.ogg" % testroot
)
225 global daemon
, errs
, port
226 assert daemon
== None, "no daemon running"
227 if not bindable(port
+ 1):
228 print "waiting for port %d to become bindable again..." %
(port
+ 1)
230 while not bindable(port
+ 1):
232 print " starting daemon"
233 # remove the socket if it exists
234 socket
= "%s/home/socket" % testroot
239 daemon
= subprocess
.Popen(["disorderd",
241 "--config", "%s/config" % testroot
],
243 # Wait for the socket to be created
245 while not os
.path
.exists(socket
):
248 print "FATAL: daemon failed to start up"
252 print " waiting for socket..."
254 print "FATAL: took too long for socket to appear"
258 print " took about %ds for socket to appear" % waited
260 def create_user(username
="fred", password
="fredpass"):
261 """create_user(USERNAME, PASSWORD)
263 Create a user, abusing direct database access to do so. Gives the
264 user rights 'all', allowing them to do anything."""
265 print " creating user %s" % username
267 "--config", disorder
._configfile
, "--no-per-user-config",
268 "--user", "root", "adduser", username
, password
])
270 "--config", disorder
._configfile
, "--no-per-user-config",
271 "--user", "root", "edituser", username
, "rights", "all"])
274 print " initiating rescan"
276 c
= disorder
.client()
278 print " rescan completed"
283 Stop the daemon if it has not stopped already"""
289 print " stopping daemon"
290 disorder
.client().shutdown()
291 print " waiting for daemon"
293 print " daemon has stopped"
295 print " daemon already stopped"
298 def run(module
=None, report
=True):
301 Run the test in MODULE. This can be a string (in which case the module
302 will be imported) or a module object."""
305 # Locate the test module
307 # We're running a test stand-alone
310 name
= os
.path
.splitext(os
.path
.basename(sys
.argv
[0]))[0]
312 # We've been passed a module or a module name
313 if type(module
) == str:
314 module
= __import__(module
)
315 name
= module
.__name__
316 print "--- %s ---" % name
319 logfile
= "%s.log" % name
324 errs
= open(logfile
, "a")
325 # Ensure that disorder.py uses the test installation
326 disorder
._configfile
= "%s/config" % testroot
327 disorder
._userconf
= False
328 # Make config file etc
330 # Create some standard tracks
346 Recursively delete directory D"""
347 if os
.path
.lexists(d
):
349 for dd
in os
.listdir(d
):
350 remove_dir("%s/%s" %
(d
, dd
))
355 def lists_have_same_contents(l1
, l2
):
356 """lists_have_same_contents(L1, L2)
358 Return True if L1 and L2 have equal members, in any order; else False."""
365 return map(nfc
, s1
) == map(nfc
, s2
)
367 def check_files(chatty
=True):
368 c
= disorder
.client()
370 for d
in dirs_by_dir
:
371 xdirs
= dirs_by_dir
[d
]
372 dirs
= c
.directories(d
)
373 if not lists_have_same_contents(xdirs
, dirs
):
376 print "directory: %s" % d
377 print "expected: %s" % xdirs
378 print "got: %s" % dirs
380 for d
in files_by_dir
:
381 xfiles
= files_by_dir
[d
]
383 if not lists_have_same_contents(xfiles
, files
):
386 print "directory: %s" % d
387 print "expected: %s" % xfiles
388 print "got: %s" % files
393 """Execute a command given as a list and return its stdout"""
394 p
= subprocess
.Popen(args
, stdout
=subprocess
.PIPE
)
395 lines
= p
.stdout
.readlines()
397 assert rc
== 0, ("%s returned status %s" %
(args
, rc
))
400 # -----------------------------------------------------------------------------
406 testroot
= "%s/tests/testroot" % top_builddir
407 tracks
= "%s/tracks" % testroot