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
|
"""
High-level API for the Nitrate test case management system
This module provides a high-level python interface for the nitrate
module. Connection to the server is handled automatically by the
Nitrate object which checks user configuration file ~/.nitrate for
the "url" variable.
"""
import nitrate, sys, os
from nitrate import NitrateError
from pprint import pprint
from ConfigParser import SafeConfigParser, Error as ConfigParserError
class Nitrate(object):
"""
General Nitrate Object
Takes care of initiating the connection to the Nitrate server,
parses user configuration and handles the debugging mode.
"""
_connection = None
_debugging = None
_settings = None
_requests = 0
def _debug(self, text, data = "nothing"):
""" Log text if debugging (pretty print data if provided). """
# Detect mode if run for the first time
if Nitrate._debugging is None:
Nitrate._debugging = "--debug" in sys.argv
# Log the text & pretty print data if available
if Nitrate._debugging:
sys.stderr.write(text + "\n")
# Data itself can be a None, so we use rather "nothing" here
if data != "nothing":
pprint(data, stream=sys.stderr)
@property
def _config(self):
""" User configuration (expected in ~/.nitrate). """
# Read the config file (unless already done)
if Nitrate._settings is None:
try:
path = os.path.expanduser("~/.nitrate")
parser = SafeConfigParser()
parser.read([path])
Nitrate._settings = dict(parser.items("nitrate"))
except ConfigParserError:
raise NitrateError(
"Cannot read the config file {0}".format(path))
# We need to know at least the server URL
if "url" not in self._settings:
raise NitrateError("No url found in the config file")
# Return the settings
return Nitrate._settings
@property
def _server(self):
""" Connection to the Nitrate server. """
# Connect to the server unless already connected
if Nitrate._connection is None:
self._debug("Contacting server {0}".format(self._config["url"]))
Nitrate._connection = nitrate.NitrateKerbXmlrpc(
self._config["url"]).server
# Return existing connection
Nitrate._requests += 1
return Nitrate._connection
def __str__(self):
""" Provide a short summary about the connection. """
return "Nitrate server: {0}\nTotal requests handled: {1}".format(
self._config["url"], self._requests)
class Server(Nitrate):
"""
Server object providing direct access to the Nitrate server XMLRPC.
Usage: Server().TestRun.get(1234)
"""
# Dispatch XMLRPC methods to the server
def __getattr__(self, name):
""" Dispatch XMLRPC methods to the server. """
return getattr(self._server, name)
class Status(Nitrate):
"""
Test case run status
Used for easy converting between status id and name.
"""
_statuses = ['PAD', 'IDLE', 'PASSED', 'FAILED', 'RUNNING', 'PAUSED',
'BLOCKED', 'ERROR', 'WAIVED']
def __init__(self, status):
"""
Takes numeric status id (1-8) or status name which is one of:
IDLE, PASSED, FAILED, RUNNING, PAUSED, BLOCKED, ERROR, WAIVED
"""
if isinstance(status, int):
self._id = status
else:
try:
self._id = self._statuses.index(status)
except ValueError:
raise NitrateError("Invalid status '{0}'".format(status))
def __str__(self):
""" Return status name for printing. """
return self.name
def __eq__(self, other):
""" Handle correctly status equality. """
return self._id == other._id
def __ne__(self, other):
""" Handle correctly status inequality. """
return self._id != other._id
@property
def id(self):
""" Numeric status id. """
return self._id
@property
def name(self):
""" Human readable status name. """
return self._statuses[self._id]
class NitrateMutable(Nitrate):
"""
General class for all mutable Nitrate objects
Implements default handling of object data access & updates.
Provides the update() method which pushes the changes (if any)
to the Nitrate server.
"""
def __init__(self):
# List of available attributes
self._fields = []
self._modified = False
self.data = {}
def __del__(self):
""" Automatically update data upon destruction. """
self.update()
def __getattr__(self, name):
""" Supported fields automatically dispatched for getting. """
if name in self.__dict__.get("_fields", []):
return self.data[name]
else:
return self.__dict__[name]
def __setattr__(self, name, value):
""" Allow direct field update, note modified state. """
if name in self.__dict__.get("_fields", []):
if self.data[name] != value:
self.data[name] = value
self._modified = True
self._debug("Updating {0} to {1}".format(name, value))
else:
object.__setattr__(self, name, value)
def _update(self):
""" Save data to server (to be implemented by respective class) """
raise NitrateError("Data update not implemented")
def update(self):
""" Update the data, if modified, to the Nitrate server """
if self._modified:
self._update()
self._modified = False
class TestPlan(NitrateMutable):
"""
Provides 'testruns' and 'testcases' attributes, the latter as
the default iterator. Supported fields: name
"""
def __init__(self, id):
""" Takes numeric plan id. """
NitrateMutable.__init__(self)
self._fields = "name".split()
self.id = id
self.data = self._server.TestPlan.get(id)
self._debug("TP#{0} fetched".format(self.id), self.data)
self._testruns = None
self._testcases = None
def __iter__(self):
""" Provide test case list as the default iterator. """
for testcase in self.testcases:
yield testcase
def __str__(self):
""" Short test plan summary pro printing. """
return "TP#{0} - {1} ({2} cases, {3} runs)".format(self.id,
self.name, len(self.testcases), len(self.testruns))
def _update(self):
""" Save test plan data to the Nitrate server """
hash = {"name": self.data["name"]}
self._debug("Updating TP#{0}".format(self.id), hash)
self._server.TestPlan.update(self.id, hash)
@property
def testruns(self):
""" List of TestRun() objects related to this plan. """
if self._testruns is None:
self._testruns = [TestRun(hash) for hash in
self._server.TestPlan.get_test_runs(self.id)]
return self._testruns
@property
def testcases(self):
""" List of TestCase() objects related to this plan. """
if self._testcases is None:
self._testcases = [TestCase(hash) for hash in
self._server.TestPlan.get_test_cases(self.id)]
return self._testcases
class TestRun(NitrateMutable):
"""
Provides 'caseruns' attribute containing all relevant case
runs. This is also the default iterator. Other supported
fields: summary, notes
"""
def __init__(self, data):
""" Takes numeric id or test run hash. """
NitrateMutable.__init__(self)
self._fields = "summary notes".split()
# Fetch the data hash from the server if id provided
if isinstance(data, int):
self.id = data
self.data = self._server.TestRun.get(self.id)
# Otherwise just save the already-prepared data hash
else:
self.id = data["run_id"]
self.data = data
self._debug("Fetched TR#{0}".format(self.id), self.data)
self._caseruns = None
def __iter__(self):
""" Provide test case run list as the default iterator. """
for caserun in self.caseruns:
yield caserun
def __str__(self):
""" Short test run summary pro printing. """
return "TR#{0} - {1} ({2} cases)".format(
self.id, self.summary, len(self.caseruns))
def _update(self):
""" Save test run data to the Nitrate server """
# Filter out unsupported None values
hash = {}
hash["summary"] = self.data["summary"]
hash["notes"] = self.data["notes"]
self._debug("Updating TR#{0}".format(self.id), hash)
self._server.TestRun.update(self.id, hash)
@property
def caseruns(self):
""" List of TestCaseRun() objects related to this run. """
if self._caseruns is None:
# Fetch both test cases & test case runs
testcases = self._server.TestRun.get_test_cases(self.id)
caseruns = self._server.TestRun.get_test_case_runs(self.id)
# Create the CaseRun objects
self._caseruns = [TestCaseRun(testcase=testcase, caserun=caserun)
for caserun in caseruns for testcase in testcases
if testcase['case_id'] == caserun['case_id']]
return self._caseruns
class TestCase(NitrateMutable):
"""
Provides access to the test case fields. Following fields are
supported: summary, notes, script and arguments.
"""
def __init__(self, data):
""" Takes numeric id or test case hash. """
super(TestCase, self).__init__()
self._fields = "summary notes script arguments".split()
# Fetch the data hash from the server if numeric id provided
if isinstance(data, int):
self.id = data
self.data = self._server.TestCase.get(self.id)
# Otherwise just save the already-prepared data hash
else:
self.id = data["case_id"]
self.data = data
self._debug("Fetched TC#{0}".format(self.id), self.data)
def __str__(self):
""" Short test case summary for printing. """
return "TC#{0} - {1}".format(str(self.id).ljust(5), self.summary)
def _update(self):
""" Save test case data to Nitrate server """
# Filter out unsupported None values
hash = {}
for (name, value) in self.data.iteritems():
if value is not None:
hash[name] = value
self._debug("Updating TC#{0}".format(self.id), hash)
self._server.TestCase.update(self.id, hash)
class TestCaseRun(NitrateMutable):
"""
Provides access to the case run specific fields. Includes
the 'testcase' attribute holding the respective test case
object. Supported fields: status, notes
"""
def __init__(self, id=None, testcase=None, caserun=None):
""" Takes case run id or both test case and case run hashes. """
NitrateMutable.__init__(self)
self._fields = "notes".split()
# Fetch the data hash from the server if id provided
if id is not None:
self.data = self._server.TestCaseRun.get(id)
self.testcase = TestCase(self.data["case_id"])
self.id = id
# Otherwise just save the already-prepared data hash
else:
self.testcase = TestCase(testcase)
self.data = caserun
self.id = caserun["case_run_id"]
self._debug("Fetched CR#{0}".format(self.id), self.data)
def __str__(self):
""" Short test case summary pro printing. """
return "{0} - CR#{1} - {2}".format(self.stat, str(self.id).ljust(6),
self.testcase.data["summary"])
def _update(self):
""" Save test case run data to the Nitrate server """
# Filter out unsupported None values
hash = {}
for (name, value) in self.data.iteritems():
if value is not None:
hash[name] = value
# Different name for the status key in update()
hash["case_run_status"] = hash["case_run_status_id"]
self._debug("Updating CR#{0}".format(self.id), hash)
self._server.TestCaseRun.update(self.id, hash)
@property
def status(self):
""" Get case run status object """
return Status(self.data["case_run_status_id"])
@status.setter
def status(self, newstatus):
""" Set case run status """
if self.status != newstatus:
self.data["case_run_status_id"] = newstatus.id
self._modified = True
@property
def stat(self):
""" Short same-width status string (4 chars) """
return self.status.name[0:4]
class Product(Nitrate): pass
class Build(Nitrate): pass
class Tag(Nitrate): pass
class Bug(Nitrate): pass
# Self-test
if __name__ == "__main__":
# Display info about the server
print Nitrate()
# Show test plan summary and list test cases
testplan = TestPlan(2214)
print "\n", testplan
for testcase in testplan:
print ' ', testcase
# For each test run list test cases with their status
for testrun in testplan.testruns:
print "\n", testrun
for caserun in testrun:
print ' ', caserun
# Update test case data / case run status
TestPlan(289).name = "Tessst plan"
TestRun(6757).notes = "Testing notes"
TestCase(46490).script = "/CoreOS/component/example"
TestCaseRun(525318).status = Status("PASSED")
# Display info about the server
print Nitrate()
|