My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
#
# Copyright [2010] the stanislaw.bartkowski@gmail.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Some public helper functions and classes for Boa test harness
"""

__authors__ = [
'"Stansislaw Bartkowski" <stanislawbartkowski@gmail.com>',
]

import logging
import filecmp
import logging
import os
import shutil
import tempfile
import time
import unittest

def _getKey(cf, key):
if cf == None : return None
ikey = osPrefix() + "." + key
if cf.has_key(ikey): return cf[ikey]
if cf.has_key(key): return cf[key]
return None

def osPrefix():
"""Returns system prefix

Args:
No args

Returns:
linux/windows

Raises:
Nothing
"""
name = os.name
if name == "posix": return "linux"
return "windows"

def isLinux():
"""Is host system linux

Args:
No args

Returns:
True: linux, False: windows

Raises:
Nothing
"""
prefix = osPrefix()
if prefix == "linux": return True
return False

def prepareRunCommand(command):
"""Modify command (binary file) with 'executable' access

Is valid for windows but do nothing
On linux: chmod a+x,g+a,u+x command

Args:
File name

Returns:
Nothing

Raises:
Exception if error
"""
if not isLinux(): return
os.chmod(command, 0777)

def _getTmpName():
"""Returns temporary and uniq file name

Args:
Nothing

Returns:
File name

Raises:
Exception if error
"""
f = tempfile.mkstemp()
tmp = f[1]
os.close(f[0])
return tmp


def __waitforBin(bin):
"""Stops until process is not visible in ps command.

Wait for command to exit

Args:
Command to watch

Returns:
Nothing

Raises:
Nothing
"""
if not isLinux() : return
while True:
time.sleep(1)
tmp = _getTmpName()
logging.debug("Wait for " + bin)
logging.debug("Read ps output to temp " + tmp)
os.system("ps -aef >" + tmp)
f = open(tmp)
li = f.readlines()
f.close()
os.unlink(tmp)
found = 0
for l in li:
logging.debug(l)
if l.find(bin) != -1:
found = 1
break
if not found:
break

class ChangeDir :
""" Change current directory and keeps previous

Attributes:
param : TestParam container
dir : previous directory
"""

def __init__(self,param) :
""" Constructor

Args:
param : TestParam container
"""
self.__param = param
self.__dir = os.getcwd()
os.chdir(param.getRunDir())

def restore(self) :
""" Restores previous directory
"""
os.chdir(self.__dir)


def runBin(param, com, binarywaited):
"""Launch command and wait for exit


Args:
param: TestParam
com: command to lauch
binarywaited: binary string visible in ps command

Returns:
Exit code

Raises:
Exception if any error has occured
"""
d = ChangeDir(param)
res = os.system(com)
__waitforBin(binarywaited)
d.restore()
return res

"""Replace variables using format (like ConfigParser) %(..)s

Args:
line : line to be changed
param : TestParam
teparam : OneTestParam

Returns:
Fixed line

Raises:
Exception if variable for replacement not found

"""


def replaceLine(line, param, teparam):
while 1 :
low = line.rfind("%(")
if low == -1 : break
up = line.rfind(")s")
if up == -1 : break
before = line[0: low]
after = line[up+2: len(line)]
key = line[low+2: up]
value = teparam.getPar(key)
if value == None : value = param.getPar(key)
if value == None :
raise TestException(key + " variable for replacement not found !")
line = before + value + after

return line


class TestException(Exception):

"""General exception raised

Attributes:
s : error message

"""

def __init__(self, s):
"""Constructor

Args:
s : error message
"""
self.s = s
logging.critical(s)

def draw(self):
"""Prints error message

Args: nothing

Returns: nothing

Raises: nothing

"""
print self.s

def __str__(str) :
return self.s


class OneTestParam:

"""Container for test case parameters

Attributes:
testId : string, test identifier
cf : dictionary, test properties, key : value
predefined:
'descr' - short test description
'testcase' : if not None predefined python test case
'copytestres' : if not Nodn test resource to copy
'copycommonres' : if not None common resource to copy
'command' : if not None predefined command test case
"""

def __init__(self, testId, cf):
""" Constructor

Args:
testId : test identifier
cf : dictionary for test specific properties

"""
self.testId = testId;
self.cf = cf

def getPar(self, key):
""" Getter for test properties

Args:
key : key for property

Returns:
Value or None if property not defined

"""
return _getKey(self.cf, key)

def getDescr(self):
""" Getter for description property
"""
return self.getPar('descr')

def getTestId(self):
""" Getter for test id property
"""
return self.testId

def isTestCase(self):
""" Checker if test case is predefined python test case

Returns:
True: if predefined python test case
False: otherwise

"""
if self.cf.has_key('testcase'): return 1
return 0

def getTestCase(self):
""" Getter for test case property

Returns:
Test case name or None if not defined

"""
return self.getPar('testcase')

def getCopyTestRes(self):
""" Getter for 'copytestres' property
"""

return self.getPar('copytestres')

def getCopyCommonRes(self):
""" Getter for 'copycommonres' property
"""
return self.getPar('copycommonres')

def getCommand(self):
""" Getter for 'command' property
"""
return self.getPar('command')


class TestParam:

""" Container for general test suite properties

Attributes:
suiteparam : container for test suite run parameters
cf : dictionary with test suite properties
can be None if not defined

"""

def __init__(self, he, suiteparam):
""" Constructor

Args:
he : dictionary with test suite properties (can be None)
suiteparam : container with test suite run param

"""
self.cf = he
self.suiteparam = suiteparam

def getResDir(self):
""" Getter for 'resdir' parameter
(directory where test cases and resources are placed)
"""
return self.suiteparam.resdir

def getGlobResDir(self):
""" Getter for 'globresdir' parameter
(directory where common resources are located)
"""
return self.suiteparam.globresdir

def getTestDir(self, s):
""" Getter for directory where resource for one test case are located

Args:
s : test case identifier

Returns:
Path name, directory for test case

"""
dd = self.suiteparam.resdir
di = os.path.join(dd, s)
return di

def getRunDir(self):
""" Getter for 'run dir' parameter
(directory where test case is copied and launched)
"""
return self.suiteparam.rundir

def getPar(self, key):
""" Getter for global test suite property

Args:
key : parameter key

Returns:
value or None if property not defined

"""
return _getKey(self.cf, key)

def getCustomC(self):
""" Getter for 'customC' reference
"""
return self.suiteparam.customC


def removeDir(te):
""" Remove directory and all subdirectories.

Args:
te : directory name to be removed

Returns:
Nothing

Raise:
Exception if error

"""
if not os.path.isdir(te): return
shutil.rmtree(te)


def copyDir(sou, dest):
""" Copy directory (with subdirectories)

Args:
sou : directory name to be copied from
dest : directory to be copied to

Returns:
Nothing

Raise:
Exception if error
"""
if not os.path.isdir(dest):
# logging.debug("Copy tree : " + sou + " ==> " + dest)
# shutil.copytree(sou, dest)
# return
logging.debug("Create directory : " + dest)
os.mkdir(dest)
li = os.listdir(sou)
for na in li:
if na == ".svn" :
logging.debug(" Ignore " + na)
continue
soul = os.path.join(sou, na)
destl = os.path.join(dest, na)
if os.path.isfile(soul):
logging.debug("Copy file : " + soul + " ==> " + destl)
shutil.copyfile(soul, destl)
else:
logging.debug("Copy directory : " + soul + " ==> " + destl)
copyDir(soul, destl)

def copyFile(param, teparam, file):
""" Copy file from test case directory to run directory

Args:
param : TestParam container
teparam: OneTestParam container
file : file name to be copied

Returns:
Nothing

Raise:
Exception if error

"""
soud = param.getTestDir(teparam.getTestId())
soufile = os.path.join(soud, file)
destd = param.getRunDir()
destfile = os.path.join(destd, file)
shutil.copy2(soufile, destfile)


def clearRunDir(param):
""" Clean run directory, removes all files

Args:
param : TestParam container

Returns:
Nothing

Raise:
Exception if error

"""
tt = param.getRunDir()
logging.debug("Clear " + tt)
removeDir(tt)
if not os.path.isdir(tt):
os.makedirs(tt)

def __copyRes(test, testId, dest):
""" Copy resource (command or test case specific) to run directory

Args:
test : TestParam container
testId : if None common resource, test case resource otherwise
dest : resource description (<name sou> : <name dest>

Returns:
Nothing

Raise:
Exception if error

"""
if dest == None: return
sou = test.getResDir()
if testId != None:
sou = test.getResDir()
sou = test.getTestDir(testId)
else:
sou = test.getGlobResDir()
list = dest.split(":")
if len(list) == 1:
soud = list[0]
destd = soud
else:
soud = list[0]
destd = list[1]
soudir = os.path.join(sou, soud)
destdir = os.path.join(test.getRunDir(), destd)
logging.debug(soudir + " ==> " + destdir)
copyDir(soudir, destdir)


def prepareRunDir(param, teparam):
""" Prepare run directory for testcase : cleans and copy resources


Args:
param : TestParam container
teparam : OneTestParam container

Returns:
Nothing

Raise:
Exception if error

"""
clearRunDir(param)
__copyRes(param, None, teparam.getCopyCommonRes())
__copyRes(param, teparam.getTestId(), teparam.getCopyTestRes())

def compareFiles(param, teparam, testdir, patt, destdir):
""" Compare files in test case resource directory and test dir

Args:
param : TestParam container
teparam: OneTestParam container
testdir : subdirectory in test case resource with files to compare
patt : file pattern for file to be compared
destdir : subdirectory in run dir containing files to be compares

Returns:
True: all files are the same
False: at least one file is different

Raise:
Exception if any error

"""
t = param.getTestDir(teparam.getTestId())
xdir = os.path.join(t, testdir)
if not os.path.isdir(xdir): return 1
li = os.listdir(xdir)
tdir = param.getRunDir()
res = 1
for l in li:
if l.find(patt) == -1: continue
sou = os.path.join(xdir, l)
dest = os.path.join(tdir, destdir)
dest = os.path.join(dest, l)
logging.info(sou + " <=> " + dest)
if not os.path.isfile(dest):
logging.info (" " + dest + " - does not exist")
res = 0
continue
f1 = open(sou, "r")
f2 = open(dest, "r")
li1 = f1.readlines()
li2 = f2.readlines()
if len(li1) != len(li2) :
logging.info(" number of lines is different")
res = 0
continue
for i in range(0, len(li1)) :
line1 = li1[i].rstrip()
line2 = li2[i].rstrip()
if line1 != line2 :
logging.info(" line number: " + str(i) + " different")
logging.info(line1)
logging.info(line2)
res = 0
break

# 2011/08/30 - filecmp.cmp replace by manual comparing to avoid trailing whitespaces
# eq = filecmp.cmp(sou, dest)
# if not eq:
# logging.info(" different")
# res = 0
return res

class SampleTestCase(unittest.TestCase):
""" Sample test case, do nothing

Attributes:
param : TestParam container
teparam : OneTestParam container

"""

def __init__(self, param, teparam):
unittest.TestCase.__init__(self, 'runTest')
self.param = param
self.teparam = teparam

def setUp(self):
prepareRunDir(self.param, self.teparam)

def runTest(self):
print self.teparam.getDescr()

Change log

r87 by stanislawbartkowski on Sep 2, 2011   Diff
Changed the method of file comparing
Go to: 
Project members, sign in to write a code review

Older revisions

r86 by stanislawbartkowski on Jul 3, 2011   Diff
Environment variable substitution for
selenium test.
Custom environment substitution for
ConfigParses
r80 by stanislawbartkowski on Jan 2, 2011   Diff
1) strip spaces for alias searching
2) critical error logging for
TestException
r61 by stanislawbartkowski on Sep 27, 2010   Diff
[No log message]
All revisions of this file

File info

Size: 14373 bytes, 634 lines
Powered by Google Project Hosting