-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbtest.py
executable file
·3319 lines (2969 loc) · 133 KB
/
fbtest.py
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
# PROGRAM/MODULE:
# FILE: fbtest.py
# DESCRIPTION: Firebird QA system
# CREATED: 22.6.2009
#
# The contents of this file are subject to the Initial
# Developer's Public License Version 1.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.firebirdsql.org/en/initial-developer-s-public-license-version-1-0
#
# Software distributed under the License is distributed AS IS,
# WITHOUT WARRANTY OF ANY KIND, either express or implied.
# See the License for the specific language governing rights
# and limitations under the License.
#
# The Original Code was created by Pavel Cisar
#
# Copyright (c) 2009 Pavel Cisar <[email protected]>
# and all contributors signed below.
#
# All Rights Reserved.
# Contributor(s): ______________________________________.
from __future__ import print_function
import sys
import types
import os
from stat import S_IRWXU, S_IRWXG, S_IRWXO
import platform
import tempfile
import re
import difflib
import operator
import itertools
import pickle
import weakref
import traceback
from StringIO import StringIO
import fdb
import fdb.services as fbservice
from fdb.ibase import DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP
from mako.template import Template
from mako.lookup import TemplateLookup
from argparse import ArgumentParser
from time import time
from xml.sax import saxutils
import datetime
__version__ = "1.0.2"
try:
from subprocess import Popen, PIPE
except ImportError:
from subprocess25 import Popen, PIPE
try:
import pysvn
pysvn_present = True
except ImportError:
pysvn_present = False
PYTHON_MAJOR_VER = sys.version_info[0]
#: Test Repository Subversion path
svn_repository = 'https://svn.code.sf.net/p/firebird/code/qa/fbt-repository/trunk/'
#: Constant
DB_NEW = 'New'
#:
DB_EXISTING = 'Existing'
#:
DB_RESTORE = 'Restore'
#:
DB_ACCESS = [None, DB_NEW, DB_EXISTING, DB_RESTORE]
#:
CHARACTER_SETS = [None, 'NONE','ASCII','BIG_5','CYRL','DOS437','DOS737','DOS775',
'DOS850','DOS852','DOS857','DOS858','DOS860','DOS861','DOS862',
'DOS863','DOS864','DOS865','DOS866','DOS869','EUCJ_0208','GBK',
'GB_2312','ISO8859_1','ISO8859_2','ISO8859_3','ISO8859_4',
'ISO8859_5','ISO8859_6','ISO8859_7','ISO8859_8','ISO8859_9',
'ISO8859_13','KOI8R','KOI8U','KSC_5601','NEXT','OCTETS',
'SJIS_0208','TIS620','UNICODE_FSS','UTF8','WIN1250','WIN1251',
'WIN1252','WIN1253','WIN1254','WIN1255','WIN1256','WIN1257',
'WIN1258','LATIN2']
#:
PAGE_SIZES = [None,'1024','2048','4096','8192','16384']
#:
TYPE_ISQL = 'ISQL'
#:
TYPE_PYTHON = 'Python'
#:
TEST_TYPES = [TYPE_ISQL,TYPE_PYTHON]
#:
PLATFORMS = ['Windows','Linux','MacOS','FreeBSD','Solaris','HP-UX']
#:
UNKNOWN = 'Unknown'
class FirebirdNotAvailable(Exception):
pass
# Invalid XML characters, control characters 0-31 sans \t, \n and \r
CONTROL_CHARACTERS = re.compile(r"[\000-\010\013\014\016-\037]")
template_base = """<%def name="title()">Firebird QA Analysis</%def>
<%! import datetime %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css" media="screen" title="Normal Text">
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p,
blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em,
font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption,
tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0;
font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit;
vertical-align: baseline;}
:focus { outline: 0; }
body { line-height: 1; color: black; background: white; }
ol, ul { list-style: none; }
caption, th, td { text-align: left; font-weight: normal; }
blockquote:before, blockquote:after, q:before, q:after { content: ""; }
blockquote, q { quotes: "" ""; }
body { margin: 0; padding: 0; font-family: verdana, sans-serif; font-size: 69%;
color: #000; background-color: #fff; }
h1 { font-size: 1.4em; font-weight: bold; margin-top: 0em; margin-bottom: 0em; }
h2 { font-size: 1.2em; margin: 1.2em 0em 1.2em 0em; font-weight: bold; }
h3 { font-size: 1.0em; margin: 1.2em 0em 1.2em 0em; font-weight: bold; }
h4 { font-size: 0.95em; margin: 1.2em 0em 1.2em 0em; font-weight: normal; }
h5 { font-size: 0.9em; margin: 1.2em 0em 1.2em 0em; font-weight: normal; }
h6 { font-size: 0.85em; margin: 1.2em 0em 1.2em 0em; font-weight: normal; }
pre { font-family: courier, courier-new; }
th { text-align: center; font-weight: bold; background-color: #e0e0e0; padding: 2px; }
table { border-collapse: separate; border-spacing: 2px; }
td { padding: 2px 0.5em 0 0.5em;}
.PASS { background-color: #a0f0a0; text-align: }
.FAIL { background-color: #ff9090; text-align: }
.ERROR { background-color: #ffffe0; text-align: }
.UNTESTED { background-color: #d0d0d0; text-align: }
.SKIPPED { background-color: #d0d0d0; text-align: }
.NA { background-color: white; text-align: center; }
.test_id { padding-left: 5px;}
.ann-o { background-color: white; padding: 2px; }
.ann-e { background-color: #ffffe0; padding: 2px; }
.cause { background-color: #ff9090; padding: 2px;}
.total { font-weight: bold; background-color: #e0e0e0; padding: 2px; }
#Container { margin: 0em auto; padding: 4px 20px 4px 20px ;
text-align: left; /* Win IE5 */ }
#Header { position: relative; margin: 0; padding: 10px; clear: both; }
#Footer { font-size: 0.9em; color: #666; line-height: 1.3em; padding-top: 5px;clear: both; }
#Content { display: block; }
</style>
<title>${self.title()}</title>
</head>
<body>
<div id="Container">
<div id="Header"><H1>QA Analysis for Firebird ${version}</H1></div>
<div id="Content">${self.body()}
</div>
<div id="Footer">
Generated by fbtest analyzer, ${datetime.datetime.now()}
</div>
</div>
</body>
</html>
"""
template_detail = """<%inherit file="base.mako"/>
<H1>Details for test ${test_id}</H1>
%for group in test_detail:
<%
result = group[0]
i = 1
has_diffs = diffs_only and len([key for key in result.annotations.keys() if key.endswith('diff')]) > 0
if has_diffs:
annotations = ((x,y) for x,y in result.annotations.items() if x.endswith('diff'))
else:
annotations = ((x,y) for x,y in result.annotations.items() if x != result.CAUSE)
%>
<H2>${', '.join(group[1])}</H2>
<table width="100%" border=1>
<tr><th>Annotation</th><th>Value</th></tr>
<tr><td class="cause">Cause</td><td class="cause">${result.get_cause()}</td></tr>
%for key,value in annotations:
<tr>
%if (i % 2) == 0:
<td class="ann-o">${key}</td><td class="ann-o"><pre>${value}</pre></td>
%else:
<td class="ann-e">${key}</td><td class="ann-e"><pre>${value}</pre></td>
%endif
</tr>
<%
i += 1
%>
%endfor
</table>
%endfor
"""
template_main = """<%inherit file="base.mako"/>
<%
from operator import attrgetter
from itertools import groupby
platforms = [(k,len(list(g))) for k,g in groupby(results,attrgetter('platform'))]
cpuarchs = [(k,len(list(g))) for k,g in groupby(results,attrgetter('cpuarch'))]
archs = [(k,len(list(g))) for k,g in groupby(results,attrgetter('arch'))]
runs = [(k,len(list(g))) for k,g in groupby(results,attrgetter('sequence'))]
totals = [0 for x in tests[test_order[0]]]
%>
<table>
<tr>
%for platform,span in platforms:
<th colspan=${span}>${platform}</th>
%endfor
</tr>
<tr>
%for cpuarch,span in cpuarchs:
<th colspan=${span}>${cpuarch}-bit</th>
%endfor
</tr>
<tr>
%for arch,span in archs:
<th colspan=${span}>${arch}</th>
%endfor
</tr>
<tr>
%for run,span in runs:
<th colspan=${span}>${run}</th>
%endfor
</tr>
%for test_id in test_order:
<% test_results = tests[test_id] %>
<!--%for test_id,test_results in tests.items():-->
<tr>
%for result in test_results:
%if result:
<% r = result.outcome
totals[test_results.index(result)] += result.get_elapsed()
%>
%else:
<% r = 'NA' %>
%endif
<td class='${r}'>
%if result:
${result.outcome[:1]} ${result.get_run_time().strftime('%M:%S:%f')}
%else:
-
%endif
</td>
%endfor
%if test_id in test_details:
<td class="test_id"><a href="${test_id}.html">${test_id}</a></td></tr>
%else:
<td class="test_id">${test_id}</td></tr>
%endif
%endfor
<tr>
%for total in totals:
<td class='total'>${time2datetime(total).strftime('%H:%M:%S:%f')}</td>
%endfor
<td class='total'>Total run-time</td>
</tr>
</table>
"""
makolookup = TemplateLookup(output_encoding='utf-8', input_encoding='utf-8',
encoding_errors='replace')
makolookup.template_args['default_filters']=['decode.utf8']
makolookup.put_string('base.mako',template_base)
makolookup.put_string('main.mako',template_main)
makolookup.put_string('detail.mako',template_detail)
def time2datetime(sec):
s,ms = str(sec).split('.')
h = 0
m = 0
ms = int(ms[:6])
s = int(s)
if s >= 60:
m = s / 60
s = s % 60
if m >= 60:
h = m / 60
m = m % 60
return datetime.time(hour=h,minute=m,second=s,microsecond=ms)
def xml_safe(value):
"""Replaces invalid XML characters with '?'."""
return CONTROL_CHARACTERS.sub('?', value)
def escape_cdata(cdata):
"""Escape a string for an XML CDATA section."""
return xml_safe(cdata).replace(']]>', ']]>]]><![CDATA[')
def trim_value(value):
"""Return string with trailing whitespaces from each line removed."""
return '\n'.join((row.rstrip() for row in value.split('\n')))
def quote(value):
"""Return properly quoted string according its content."""
single = value.find("'")
double = value.find('"')
multiline = value.find('\n') != -1
if multiline or ((single != -1) and (double != -1)):
if value.find('"""') == -1 and value[0] != '"' and value[-1] != '"':
s = '"""%s"""' % value
else:
s = "'''%s'''" % value
elif (single != -1) and (double == -1):
s = '"%s"' % value
else:
s = "'%s'" % value
return s
def compare_versions(lver, rver):
""" Compare two version strings, returns:
0 for lver = rver
-1 for lver < rver
1 for lver > rver"""
if lver == None:
lver = "0"
if rver == None:
rver = "0"
lverlist = lver.split(".")[:3]
rverlist = rver.split(".")[:3]
if len(rverlist) < len(lverlist):
for i in range(len(lverlist)-len(rverlist)):
rverlist.append("0")
if len(rverlist) > len(lverlist):
for i in range(len(rverlist)-len(lverlist)):
lverlist.append("0")
for i in range(len(rverlist)):
if (int(rverlist[i]) > int(lverlist[i])):
return -1
if (int(rverlist[i]) < int(lverlist[i])):
return 1
return 0
def as_unicode(value):
"""Make sure that string is unicode.
Accepts `Unicode`, `strings` encoded in UTF-8 or `None` and returns `Unicode`
string or `None`.
"""
assert value is None or isinstance(value,types.StringTypes)
if isinstance(value,types.StringType):
return value.decode('utf-8')
else:
return value
def as_utf8(value):
"""Make sure that string is encoded in UTF-8.
Accepts `Unicode`, `strings` or `None`. If paremeter is unicode, it's returned as
string encoded in UTF-8. String or `None` parameter is returned as is.
"""
assert value is None or isinstance(value,types.StringTypes)
if isinstance(value,types.UnicodeType):
return value.encode('utf-8')
else:
return value
def runProgram(args,environment,stdin=None,**kwargs):
"""Run external program using :class:`~subprocess.Popen` from subprocess
module and capture `stdin` and `stderr`.
:param list args: List of arguments for :class:`subprocess.Popen`. First item
must be specification of program to run.
:param dict environment: Dictionary of environment variables. Ignored in this version.
:param string stdin: String to be passed as stdin to external program.
:param dict kwarg: Dictionary of additional keyword arguments for Popen.
:returns: Tuple of (returncode, stdout, stderr)
"""
if stdin:
kwargs['stdin'] = PIPE
p = Popen(args,stdout=PIPE,stderr=PIPE,**kwargs)
(stdout,stderr) = p.communicate(stdin)
return (p.returncode,stdout,stderr)
class TestVersion(object):
"""Recipe for test execution against specific Firebird version and OS platform.
"""
#: List of attribute names that should be included in :meth:`as_expression` returned string.
FIELDS = ['id','qmid','firebird_version','platform','database','database_name',
'backup_file','user_name','user_password','database_character_set',
'connection_character_set','page_size','sql_dialect','init_script',
'test_type','test_script','expected_stdout','expected_stderr',
'resources','substitutions']
def __init__(self, id, platform, firebird_version, test_type,
test_script, database=DB_NEW, expected_stdout='', expected_stderr = '',
database_name = None, backup_file = None, user_name = 'SYSDBA',
user_password = 'masterkey', database_character_set = None,
connection_character_set = None, page_size = None,
sql_dialect = 3, init_script = '', resources= None,
substitutions = None,qmid=None):
"""
:param string id: Test ID (dot-separated name).
:param string platform: List of platform names separated by colon.
:param string firebird_version: First Firebird version this test version is designed for.
:param string test_type: Test implemetation method: "ISQL" or "Python".
:param string test_script: Test code.
:param string database: Database usage specification: None, "New", "Existing" or "Restore".
:param string expected_stdout: Expected STDOUT content.
:param string expected_stderr: Expected STDERR content.
:param string database_name: Database file name.
:param string backup_file: Backup file name.
:param string user_name: User name.
:param string user_password: User password.
:param string database_character_set: Character set for database.
:param string connection_character_set: Character set for connection.
:param string page_size: Page size for database.
:param integer sql_dialect: SQL dialect for database.
:param string init_script: Test initialization script.
:param list resources: List of :class:`Resource` names.
:param list substitutions: List of substitution specifications.
:param string qmid: Test ID from old system (QMTest).
"""
assert database_character_set in CHARACTER_SETS
assert connection_character_set in CHARACTER_SETS
#assert platform in PLATFORMS
assert page_size in PAGE_SIZES
assert database in DB_ACCESS
#: Test ID.
self.id = id
#: Legacy test ID.
self.qmid = qmid
#: Platform specification (list of platform names separated by colon).
self.platform = platform
#: Firebird version string.
self.firebird_version = firebird_version
#: Database specification: :data:`DB_NEW`, :data:`DB_EXISTING` or :data:`DB_RESTORE`.
self.database = database
#: Database name.
self.database_name = database_name
#: Backup file name.
self.backup_file = backup_file
#: Firebird user name.
self.user_name = user_name
#: Firebird user password.
self.user_password = user_password
#: Database character set.
self.database_character_set = database_character_set
#: Connection character set.
self.connection_character_set = connection_character_set
#: Page size.
self.page_size = page_size
#: SQL dialect.
self.sql_dialect = sql_dialect
#: Test initialization script.
self.init_script = as_unicode(init_script)
#: Test type: :data:`TYPE_ISQL` or :data:`TYPE_PYTHON`.
self.test_type = test_type
#: Test stcript.
self.test_script = as_unicode(test_script)
#: Expected `stdout` content.
self.expected_stdout = as_unicode(expected_stdout)
#: Expected `stderr` content.
self.expected_stderr = as_unicode(expected_stderr)
#: List of resource names.
self.resources = resources
#: List of substitution definitions.
self.substitutions = []
if substitutions:
for (pattern,replacement) in substitutions:
self.substitutions.append((as_unicode(pattern),
as_unicode(replacement)))
def get_platforms(self):
"""Returns platforms supported by this test version as list of platform
names.
"""
if self.platform == 'All':
return PLATFORMS
else:
return self.platform.split(':')
def run(self,context,result):
"""Execute the recipe.
.. important:: Test run outcome is stored in :class:`Result` instance.
:param context: :class:`Runner` instance.
:param result: :class:`Result` instance.
"""
def fb15bandaid(self):
if self.init_script and self.init_script[-1] != '\n':
self.init_script = self.init_script+'\n'
if self.test_script and self.test_script[-1] != '\n':
self.test_script = self.test_script+'\n'
def fail_and_annotate_streams(outcome, program_name, cause, stdout=None,
stderr=None, annotate={}):
"""Set test as FAILed and set annotations. Used to note failures
from external programs.
"""
annotations = dict(annotate)
unexp=[]
if stdout:
unexp.append("stdout")
annotations["%s_STDOUT" % program_name]= stdout
if stderr: # gbak prints nothing to stderr if everything went ok
unexp.append("stderr")
annotations["%s_STDERR" % program_name]= stderr
if unexp: # if we got something in stdout, stderr or both
cause += "\nUnexpected " + " and ".join(unexp) + \
" stream%s " % "s"[len(unexp)==1:] + \
"received from %s." % program_name
result.set_outcome(outcome,cause,annotations)
def substitute_macros(text):
"""Substitute macros for context values."""
f_text = text
for (pattern,replacement) in context.environment.items():
replacement = replacement.replace(os.path.sep,'/')
f_text = f_text.replace('$(%s)' % pattern.upper(), replacement)
return f_text
def string_strip(string, isql=True, remove_space=True):
"""Remove unwanted isql noise strings and apply substitutions defined
in recipe to captured output string.
"""
if not string:
return string
if isql:
for regex in isqlsubs:
string = re.sub(regex, "", string)
for pattern, replacement in self.substitutions:
string= re.compile(pattern, re.M).sub(replacement, string)
if remove_space:
string = space_strip(string)
return string
def space_strip(string):
"""Reduce spaces in string"""
string= re.sub("(?m)^\s+", "", string)
return re.sub("(?m)\s+$", "", string)
def annotate_diff(desc, stdout_e, stdout_a, stdout_e_strp, stdout_a_strp):
"""Set test as FAILed due to difference in actual and expected stdout
and set annotations accordingly.
"""
id_str= "%s_" % desc
result[id_str + "stdout_expected"] = stdout_e
result[id_str + "stdout_actual"] = stdout_a
result[id_str + "stdout_expected_stripped"]= stdout_e_strp
result[id_str + "stdout_actual_stripped"] = stdout_a_strp
result[id_str + "stripped_diff"] = '\n'.join( difflib.ndiff( stdout_e_strp.splitlines(),
stdout_a_strp.splitlines() ))
result.fail("Expected standard output from %s does not match actual output." % desc)
def annotate_error_diff(desc, stderr_e, stderr_a, stderr_e_strp, stderr_a_strp):
"""Set test as FAILed due to difference in actual and expected stderr
and set annotations accordingly.
"""
id_str= "%s_" % desc
result[id_str + "stderr_expected"] = stderr_e
result[id_str + "stderr_actual"] = stderr_a
result[id_str + "stderr_expected_stripped"]= stderr_e_strp
result[id_str + "stderr_actual_stripped"] = stderr_a_strp
result[id_str + "stderr_stripped_diff"] = '\n'.join( difflib.ndiff( stderr_e_strp.splitlines(),
stderr_a_strp.splitlines() ))
result.fail("Expected error output from %s does not match actual error output." % desc)
def python_data_printer(cur):
"""Print data from open KInterbasDB cursor to stdout."""
# Print a header.
for fieldDesc in cur.description:
print (fieldDesc[fdb.DESCRIPTION_NAME].ljust(fieldDesc[fdb.DESCRIPTION_DISPLAY_SIZE]),end=' ')
print('')
for fieldDesc in cur.description:
print ("-" * max((len(fieldDesc[fdb.DESCRIPTION_NAME]),fieldDesc[fdb.DESCRIPTION_DISPLAY_SIZE])),end=' ')
print('')
# For each row, print the value of each field left-justified within
# the maximum possible width of that field.
fieldIndices = range(len(cur.description))
for row in cur:
for fieldIndex in fieldIndices:
fieldValue = row[fieldIndex]
if not isinstance(fieldValue,types.StringTypes):
fieldValue = str(fieldValue)
if isinstance(fieldValue,types.UnicodeType):
fieldValue = fieldValue.encode('utf8')
fieldMaxWidth = max((len(cur.description[fieldIndex][fdb.DESCRIPTION_NAME]),cur.description[fieldIndex][fdb.DESCRIPTION_DISPLAY_SIZE]))
print (fieldValue.ljust(fieldMaxWidth),end=' ')
print('')
def run_program_from_python_test(program, args, stdin=''):
"""Helper method to run external programs from tests written in Python.
stdout and stderr from program are written to stdout and stderr.
"""
#environ = self.__MakeEnvironment()
# PC: fix values so they are strings. Needed for Windows.
#for key in environ.iterkeys():
#environ[key] = str(environ[key])
# provide full path for standard tools
program = context.environment.get('%s_path' % program, program)
basename = os.path.split(program)[-1]
args.insert(0,program)
if self.connection_character_set:
args.extend(['-ch',self.connection_character_set])
script = stdin.encode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
script = stdin.encode('ascii')
script = substitute_macros(script)
try:
return_code, stdout, stderr = runProgram(args,[],stdin=script)
sys.stdout.writelines(stdout)
sys.stderr.writelines(stderr)
except:
result.note_exception(cause="Python test: Exception raised while running external program from Python test.")
result["failing_program"] = program
#cleanup()
def cleanup():
"""Cleanup after the test run."""
if connection:
try:
if not connection.closed:
connection.close()
except:
result.note_exception(cause="Exception raised while closing database.")
result["db_unable_to_close"] = dsn
if cleanup_db:
params = {'dsn':cleanup_db,'user':self.user_name.encode('ascii'),'password':self.user_password.encode('ascii')}
try:
c = fdb.connect(**params)
c.drop_database()
except:
result.note_exception(cause="Test cleanup: Exception raised while dropping database.")
return
def get_log():
conn = fdb.services.connect(user='sysdba',password=self.user_password)
conn.get_log()
log = conn.readlines()
conn.close()
return log
if context.version.startswith('1.5'):
fb15bandaid()
isqlsubs= map(re.compile,['(?m)Database:.*\n?', 'SQL>[ \t]*\n?',
'CON>[ \t]*\n?', '-->[ \t]*\n?'])
cause = 'Unknown cause'
cleanup_db = None
connection = None
if self.database_name:
db_name = self.database_name
else:
db_name = self.id + '.fdb'
dsn = db_filename = os.path.join(context.tempdir, db_name)
if context.server_location:
dsn = context.server_location + dsn
context.environment['DSN'] = dsn
#
if (self.user_name == 'SYSDBA'
and self.user_password == 'masterkey'
and context.environment['user_password'] != 'masterkey'):
self.user_password = context.environment['user_password']
#
result[Result.START_TIME] = str(time())
try:
# Check that Firebird is running
try:
conn = fdb.services.connect(user='sysdba',password=self.user_password)
conn.close()
#self.firebird_log = get_log()
except:
result.set_outcome(Result.UNTESTED,"Can't connect to Firebird")
raise FirebirdNotAvailable()
# Prepare database if needed
if self.database == DB_NEW:
createCommand = "CREATE DATABASE '%s' USER '%s' PASSWORD '%s'" % (dsn,
self.user_name,
self.user_password)
if self.page_size:
createCommand += " PAGE_SIZE=%d" % int(self.page_size)
if self.database_character_set:
createCommand += " DEFAULT CHARACTER SET %s" % self.database_character_set
# We'll try to attach it first to see if it doesn't already exists
# and drop it if it does. It's probably leftover from previous test
# failure.
try:
conn = fdb.connect(dsn=dsn,user=self.user_name,
password=self.user_password)
conn.drop_database()
except:
pass
try:
conn = fdb.create_database(createCommand, self.sql_dialect)
conn.close()
except KeyboardInterrupt:
cleanup_db = dsn
raise
except:
result.note_exception(cause="Test setup: Exception raised while creating database.")
result["db_unable_to_create"] = dsn
return
else:
cleanup_db = dsn
elif self.database == DB_RESTORE:
try:
return_code, stdout, stderr= runProgram([context.gbak_path, "-C",
"-user", self.user_name,
"-password", self.user_password,
os.path.join(context.repository.backup_location,self.backup_file),
dsn],[])
except KeyboardInterrupt:
cleanup_db = dsn
raise
except:
result.note_exception(cause="Test setup: Database restore failed.")
result["db_unable_to_restore"] = dsn
return
else:
if stdout or stderr:
fail_and_annotate_streams(Result.ERROR,'GBAK','Database restore',
stdout,stderr)
return
else:
cleanup_db = dsn
elif self.database == DB_EXISTING:
dsn = db_filename = os.path.join(context.repository.suite_database_location, db_name)
if context.server_location:
dsn = context.server_location + dsn
params = {'dsn':dsn,'user':self.user_name,'password':self.user_password,
'sql_dialect':self.sql_dialect}
if self.connection_character_set:
params['charset'] = self.connection_character_set
try:
connection = fdb.connect(**params)
except KeyboardInterrupt:
raise
except:
result.note_exception(cause="Test setup: Exception raised while connecting to database.")
return
# Execute Init script
if self.init_script:
params = [context.isql_path,dsn,'-user',self.user_name,'-password',
self.user_password]
if self.connection_character_set:
params.extend(['-ch',self.connection_character_set])
script = self.init_script.encode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
script = self.init_script.encode('ascii')
script = substitute_macros(script)
try:
return_code, stdout, stderr= runProgram(params,[],stdin=script)
except KeyboardInterrupt:
raise
except:
result.note_exception(cause="Test setup: Exception raised while running init script.")
result["failing_script"] = self.init_script.encode('utf-8')
cleanup()
return
else:
if stderr:
if self.connection_character_set:
stderr = stderr.decode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set]).encode('utf-8')
fail_and_annotate_streams(Result.ERROR,'ISQL','Init script',stderr=stderr)
cleanup()
return
# Run test
if self.test_type == TYPE_ISQL:
params = [context.isql_path,dsn,'-user',self.user_name,'-password',
self.user_password]
if self.connection_character_set:
params.extend(['-ch',self.connection_character_set])
script = self.test_script.encode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
script = self.test_script.encode('ascii')
script = substitute_macros(script)
try:
return_code, stdout, stderr= runProgram(params,[],stdin=script)
except KeyboardInterrupt:
raise
except:
result.note_exception(cause="Exception raised while running ISQL test script.")
result["failing_script"] = self.test_script
else:
# First, convert it to unicode
if stdout:
if self.connection_character_set:
stdout = stdout.decode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
stdout = stdout.decode('ascii')
if stderr:
if self.connection_character_set:
stderr = stderr.decode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
stderr = stderr.decode('ascii')
# Create stripped versions
stdout_stripped = string_strip(stdout) # strip whole stdout
stdout_e_stripped = string_strip(self.expected_stdout) # strip whole expected stdout
stderr_stripped = string_strip(stderr) # strip whole stderr
stderr_e_stripped = string_strip(self.expected_stderr) # strip whole expected stderr
# Analyze results
if stderr_stripped != stderr_e_stripped: # if error outputs do not match
annotate_error_diff("ISQL",
self.expected_stderr,
stderr,
stderr_e_stripped,
stderr_stripped)
elif stdout_stripped == stdout_e_stripped: # if they match
pass
else:
annotate_diff("ISQL",
self.expected_stdout,
stdout,
stdout_e_stripped,
stdout_stripped)
else:
# test is written in Python
if not connection and self.database != None:
params = {'dsn':dsn,'user':self.user_name.encode('ascii'),'password':self.user_password.encode('ascii'),
'sql_dialect':self.sql_dialect}
if self.connection_character_set:
params['charset'] = self.connection_character_set
try:
connection = fdb.connect(**params)
except KeyboardInterrupt:
raise
except:
result.note_exception(cause="Test setup: Exception raised while connecting to database.")
cleanup()
return
global_ns={
'context' : context.environment,
'kdb' : fdb,
'fdb' : fdb,
'printData' : python_data_printer,
'runProgram' : run_program_from_python_test,
'sys' : sys,
'dsn' : dsn,
'db_filename' : db_filename,
'user_name' : self.user_name.encode('ascii'),
'user_password' : self.user_password.encode('ascii'),
'page_size' : self.page_size,
'sql_dialect' : self.sql_dialect,
'character_set' : self.connection_character_set,
#'inital_log' : self.firebird_log,
#'get_log' : get_log,
#'server_location' : context["server_location"],
#'database_location' : context[self.db_path_property],
'db_conn' : connection,
'db_path_property' : 'database_location',
'print' : print
}
local_ns={}
saved_out = sys.stdout
saved_err = sys.stderr
try:
sys.stdout = StringIO()
sys.stderr = StringIO()
exec substitute_macros(self.test_script) in global_ns, local_ns
except KeyboardInterrupt:
raise
except:
result.note_exception(cause="Exception raised while executing Python test script.")
else:
stdout_a = ''
try:
stdout_a = sys.stdout.getvalue()
if self.connection_character_set:
stdout_a = stdout_a.decode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
stdout_a = stdout_a.decode('ascii')
except UnicodeDecodeError:
result.note_exception(cause="Exception raised while processing stdout from Python test script.")
try:
stderr_a = sys.stderr.getvalue()
if self.connection_character_set:
stderr_a = stderr_a.decode(DB_CHAR_SET_NAME_TO_PYTHON_ENCODING_MAP[self.connection_character_set])
else:
stderr_a = stderr_a.decode('ascii')
except UnicodeDecodeError:
result.note_exception(cause="Exception raised while processing stderr from Python test script.")
stdout_e_stripped= string_strip(self.expected_stdout)
stdout_a_stripped= string_strip(stdout_a)
stderr_e_stripped= string_strip(self.expected_stderr)
stderr_a_stripped= string_strip(stderr_a)
if stderr_a_stripped != stderr_e_stripped: # if error outputs do not match
annotate_error_diff("Python",
self.expected_stderr, stderr_a,
stderr_e_stripped, stderr_a_stripped)
elif stdout_a_stripped == stdout_e_stripped:
pass
else:
annotate_diff("Python",
self.expected_stdout, stdout_a,
stdout_e_stripped, stdout_a_stripped)
finally:
sys.stdout = saved_out
sys.stderr = saved_err
for conn in (obj for (name,obj) in itertools.chain(global_ns.items(),local_ns.items())
if isinstance(obj,fdb.Connection) and name != 'db_conn'):
if not conn.closed:
conn.close()
# Cleanup
cleanup()
except KeyboardInterrupt:
cleanup()
raise
except FirebirdNotAvailable:
pass
finally:
result[Result.END_TIME] = str(time())
def as_expression(self):
"""Return recipe data as string definition of Python dictionary.
This string could be evaluated back to Python dictionary and passed to
:class:`TestVersion` constructor to recreate the test version instance.
String is encoded in UTF-8 if necessary.
.. note:: Only attributes that haven't DEFAULT values are included.
"""
def store(attr,value):
if value and attr in ['firebird_version','platform','init_script',
'test_script','expected_stdout','expected_stderr',
'resources','substitutions','test_type']:
return True
elif attr == 'database' and value in [None,DB_EXISTING,DB_RESTORE]:
return True
elif attr == 'database_name' and value and self.database in [None,DB_EXISTING]:
return True
elif attr == 'backup_file' and self.database == DB_RESTORE:
return True
elif attr == 'user_name' and value != 'SYSDBA':
return True
elif attr == 'user_password' and (value != 'masterkey' or self.user_name != 'SYSDBA'):
return True
elif attr == 'database_character_set' and value and value != 'NONE':
return True
elif attr == 'connection_character_set' and value and value != 'NONE':
return True
elif attr == 'page_size' and value:
return True
elif attr == 'sql_dialect' and value != 3:
return True
else:
return False
data = [(key,self.__dict__[key]) for key in self.FIELDS]
items = []
for (key,value) in data:
if not store(key,value):
continue
if isinstance(value,types.UnicodeType):
value = value.encode('utf-8')
if isinstance(value,types.StringTypes):
value = trim_value(value)
if key in ['database_name','expected_stderr','expected_stdout',
'init_script','test_script']:
items.append(" '%s': %s" % (key,quote(value)))
elif isinstance(value,types.StringType):
items.append(" '%s': %s" % (key,quote(value)))
elif key == 'substitutions':
l = []
for (pattern,replacement) in value:
if isinstance(pattern,types.UnicodeType):
pattern = pattern.encode('utf-8')
if isinstance(replacement,types.UnicodeType):
replacement = replacement.encode('utf-8')
l.append('(%s,%s)' % (quote(pattern),quote(replacement)))
items.append(" '%s': %s" % (key,'[%s]' % ','.join(l)))
elif key == 'resources':
l = []
for res in value:
l.append(quote(res))
items.append(" '%s': %s" % (key,'[%s]' % ','.join(l)))
else:
items.append(" '%s': %s" % (key,str(value)))
r = '{\n%s\n}' % ',\n'.join(items)
return r
class Test(object):
"""Test definition.
Can contain multiple :class:`TestVersion` recipes for test execution against
different Firebird versions on various OS platforms.
"""
#: List of attribute names that should be included in :meth:`as_expression` returned string.
FIELDS = ['id','qmid','tracker_id','title','description','min_versions','versions']
def __init__(self,id,title='',description='',tracker_id='',min_versions=None,
versions=None,qmid=None):
"""
:param string id: Test ID (dot-separated name).
:param string title: Test title.
:param string description: test description.