VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/tests/additions/tdAddGuestCtrl.py@ 56709

Last change on this file since 56709 was 56688, checked in by vboxsync, 10 years ago

tdAddGuestCtrl.py: Fixed up the session environment change test.

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 174.3 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# pylint: disable=C0302
4
5"""
6VirtualBox Validation Kit - Guest Control Tests.
7"""
8
9__copyright__ = \
10"""
11Copyright (C) 2010-2015 Oracle Corporation
12
13This file is part of VirtualBox Open Source Edition (OSE), as
14available from http://www.virtualbox.org. This file is free software;
15you can redistribute it and/or modify it under the terms of the GNU
16General Public License (GPL) as published by the Free Software
17Foundation, in version 2 as it comes in the "COPYING" file of the
18VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20
21The contents of this file may alternatively be used under the terms
22of the Common Development and Distribution License Version 1.0
23(CDDL) only, as it comes in the "COPYING.CDDL" file of the
24VirtualBox OSE distribution, in which case the provisions of the
25CDDL are applicable instead of those of the GPL.
26
27You may elect to license modified versions of this file under the
28terms and conditions of either the GPL or the CDDL or both.
29"""
30__version__ = "$Revision: 56688 $"
31
32# Disable bitching about too many arguments per function.
33# pylint: disable=R0913
34
35## @todo Convert map() usage to a cleaner alternative Python now offers.
36# pylint: disable=W0141
37
38## @todo Convert the context/test classes into named tuples. Not in the mood right now, so
39# disabling it.
40# pylint: disable=R0903
41
42# Standard Python imports.
43from array import array
44import errno
45import os
46import random
47import string # pylint: disable=W0402
48import struct
49import sys
50import time
51
52# Only the main script needs to modify the path.
53try: __file__
54except: __file__ = sys.argv[0];
55g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))));
56sys.path.append(g_ksValidationKitDir);
57
58# Validation Kit imports.
59from testdriver import reporter;
60from testdriver import base;
61from testdriver import vbox;
62from testdriver import vboxcon;
63from testdriver import vboxwrappers;
64
65
66class GuestStream(bytearray):
67 """
68 Class for handling a guest process input/output stream.
69 """
70 def appendStream(self, stream, convertTo='<b'):
71 """
72 Appends and converts a byte sequence to this object;
73 handy for displaying a guest stream.
74 """
75 self.extend(struct.pack(convertTo, stream));
76
77class tdCtxTest(object):
78 """
79 Provides the actual test environment. Should be kept
80 as generic as possible.
81 """
82 def __init__(self, oSession, oTxsSession, oTestVm): # pylint: disable=W0613
83 ## The desired Main API result.
84 self.fRc = False;
85 ## IGuest reference.
86 self.oGuest = oSession.o.console.guest;
87 # Rest not used (yet).
88
89class tdCtxCreds(object):
90 """
91 Provides credentials to pass to the guest.
92 """
93 def __init__(self, sUser = None, sPassword = None, sDomain = None, oTestVm = None):
94 # If no user is specified, select the default user and
95 # password for the given test VM.
96 if sUser is None:
97 assert sPassword is None;
98 assert sDomain is None;
99 assert oTestVm is not None;
100
101 ## @todo fix this so all VMs have several usable test users with the same passwords (or none).
102 sUser = 'test';
103 sPassword = 'password';
104 if oTestVm.isWindows():
105 #sPassword = ''; # stupid config mistake.
106 sPassword = 'password';
107 sUser = 'Administrator';
108 sDomain = '';
109
110 self.sUser = sUser;
111 self.sPassword = sPassword if sPassword is not None else '';
112 self.sDomain = sDomain if sDomain is not None else '';
113
114class tdTestGuestCtrlBase(object):
115 """
116 Base class for all guest control tests.
117 Note: This test ASSUMES that working Guest Additions
118 were installed and running on the guest to be tested.
119 """
120 def __init__(self):
121 self.oTest = None;
122 self.oCreds = None;
123 self.timeoutMS = 30 * 1000; # 30s timeout
124 ## IGuestSession reference or None.
125 self.oGuestSession = None;
126
127 def setEnvironment(self, oSession, oTxsSession, oTestVm):
128 """
129 Sets the test environment required for this test.
130 """
131 self.oTest = tdCtxTest(oSession, oTxsSession, oTestVm);
132 return self.oTest;
133
134 def createSession(self, sName):
135 """
136 Creates (opens) a guest session.
137 Returns (True, IGuestSession) on success or (False, None) on failure.
138 """
139 if self.oGuestSession is None:
140 if sName is None:
141 sName = "<untitled>";
142 try:
143 reporter.log('Creating session "%s" ...' % (sName,));
144 self.oGuestSession = self.oTest.oGuest.createSession(self.oCreds.sUser,
145 self.oCreds.sPassword,
146 self.oCreds.sDomain,
147 sName);
148 except:
149 # Just log, don't assume an error here (will be done in the main loop then).
150 reporter.logXcpt('Creating a guest session "%s" failed; sUser="%s", pw="%s", sDomain="%s":'
151 % (sName, self.oCreds.sUser, self.oCreds.sPassword, self.oCreds.sDomain));
152 return (False, None);
153
154 try:
155 reporter.log('Waiting for session "%s" to start within %dms...' % (sName, self.timeoutMS));
156 fWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
157 waitResult = self.oGuestSession.waitForArray(fWaitFor, self.timeoutMS);
158 #
159 # Be nice to Guest Additions < 4.3: They don't support session handling and
160 # therefore return WaitFlagNotSupported.
161 #
162 if waitResult != vboxcon.GuestSessionWaitResult_Start \
163 and waitResult != vboxcon.GuestSessionWaitResult_WaitFlagNotSupported:
164 # Just log, don't assume an error here (will be done in the main loop then).
165 reporter.log('Session did not start successfully, returned wait result: %d' \
166 % (waitResult,));
167 return (False, None);
168 reporter.log('Session "%s" successfully started' % (sName,));
169 except:
170 # Just log, don't assume an error here (will be done in the main loop then).
171 reporter.logXcpt('Waiting for guest session "%s" (usr=%s;pw=%s;dom=%s) to start failed:'
172 % (sName, self.oCreds.sUser, self.oCreds.sPassword, self.oCreds.sDomain,));
173 return (False, None);
174 else:
175 reporter.log('Warning: Session already set; this is probably not what you want');
176 return (True, self.oGuestSession);
177
178 def setSession(self, oGuestSession):
179 """
180 Sets the current guest session and closes
181 an old one if necessary.
182 """
183 if self.oGuestSession is not None:
184 self.closeSession();
185 self.oGuestSession = oGuestSession;
186 return self.oGuestSession;
187
188 def closeSession(self):
189 """
190 Closes the guest session.
191 """
192 if self.oGuestSession is not None:
193 sName = self.oGuestSession.name;
194 try:
195 reporter.log('Closing session "%s" ...' % (sName,));
196 self.oGuestSession.close();
197 self.oGuestSession = None;
198 except:
199 # Just log, don't assume an error here (will be done in the main loop then).
200 reporter.logXcpt('Closing guest session "%s" failed:' % (sName,));
201 return False;
202 return True;
203
204class tdTestCopyFrom(tdTestGuestCtrlBase):
205 """
206 Test for copying files from the guest to the host.
207 """
208 def __init__(self, sSrc = "", sDst = "", sUser = "", sPassword = "", aFlags = None):
209 tdTestGuestCtrlBase.__init__(self);
210 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
211 self.sSrc = sSrc;
212 self.sDst = sDst;
213 self.aFlags = aFlags;
214
215class tdTestCopyTo(tdTestGuestCtrlBase):
216 """
217 Test for copying files from the host to the guest.
218 """
219 def __init__(self, sSrc = "", sDst = "", sUser = "", sPassword = "", aFlags = None):
220 tdTestGuestCtrlBase.__init__(self);
221 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
222 self.sSrc = sSrc;
223 self.sDst = sDst;
224 self.aFlags = aFlags;
225
226class tdTestDirCreate(tdTestGuestCtrlBase):
227 """
228 Test for directoryCreate call.
229 """
230 def __init__(self, sDirectory = "", sUser = "", sPassword = "", fMode = 0, aFlags = None):
231 tdTestGuestCtrlBase.__init__(self);
232 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
233 self.sDirectory = sDirectory;
234 self.fMode = fMode;
235 self.aFlags = aFlags;
236
237class tdTestDirCreateTemp(tdTestGuestCtrlBase):
238 """
239 Test for the directoryCreateTemp call.
240 """
241 def __init__(self, sDirectory = "", sTemplate = "", sUser = "", sPassword = "", fMode = 0, fSecure = False):
242 tdTestGuestCtrlBase.__init__(self);
243 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
244 self.sDirectory = sDirectory;
245 self.sTemplate = sTemplate;
246 self.fMode = fMode;
247 self.fSecure = fSecure;
248
249class tdTestDirOpen(tdTestGuestCtrlBase):
250 """
251 Test for the directoryOpen call.
252 """
253 def __init__(self, sDirectory = "", sUser = "", sPassword = "",
254 sFilter = "", aFlags = None):
255 tdTestGuestCtrlBase.__init__(self);
256 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
257 self.sDirectory = sDirectory;
258 self.sFilter = sFilter;
259 self.aFlags = aFlags or [];
260
261class tdTestDirRead(tdTestDirOpen):
262 """
263 Test for the opening, reading and closing a certain directory.
264 """
265 def __init__(self, sDirectory = "", sUser = "", sPassword = "",
266 sFilter = "", aFlags = None):
267 tdTestDirOpen.__init__(self, sDirectory, sUser, sPassword, sFilter, aFlags);
268
269class tdTestExec(tdTestGuestCtrlBase):
270 """
271 Specifies exactly one guest control execution test.
272 Has a default timeout of 5 minutes (for safety).
273 """
274 def __init__(self, sCmd = "", aArgs = None, aEnv = None, \
275 aFlags = None, timeoutMS = 5 * 60 * 1000, \
276 sUser = "", sPassword = "", sDomain = "", \
277 fWaitForExit = True):
278 tdTestGuestCtrlBase.__init__(self);
279 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain);
280 self.sCmd = sCmd;
281 self.aArgs = aArgs if aArgs is not None else [sCmd,];
282 self.aEnv = aEnv;
283 self.aFlags = aFlags or [];
284 self.timeoutMS = timeoutMS;
285 self.fWaitForExit = fWaitForExit;
286 self.uExitStatus = 0;
287 self.iExitCode = 0;
288 self.cbStdOut = 0;
289 self.cbStdErr = 0;
290 self.sBuf = '';
291
292class tdTestFileExists(tdTestGuestCtrlBase):
293 """
294 Test for the file exists API call (fileExists).
295 """
296 def __init__(self, sFile = "", sUser = "", sPassword = ""):
297 tdTestGuestCtrlBase.__init__(self);
298 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
299 self.sFile = sFile;
300
301class tdTestFileRemove(tdTestGuestCtrlBase):
302 """
303 Test querying guest file information.
304 """
305 def __init__(self, sFile = "", sUser = "", sPassword = ""):
306 tdTestGuestCtrlBase.__init__(self);
307 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
308 self.sFile = sFile;
309
310class tdTestFileStat(tdTestGuestCtrlBase):
311 """
312 Test querying guest file information.
313 """
314 def __init__(self, sFile = "", sUser = "", sPassword = "", cbSize = 0, eFileType = 0):
315 tdTestGuestCtrlBase.__init__(self);
316 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
317 self.sFile = sFile;
318 self.cbSize = cbSize;
319 self.eFileType = eFileType;
320
321class tdTestFileIO(tdTestGuestCtrlBase):
322 """
323 Test for the IGuestFile object.
324 """
325 def __init__(self, sFile = "", sUser = "", sPassword = ""):
326 tdTestGuestCtrlBase.__init__(self);
327 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
328 self.sFile = sFile;
329
330class tdTestFileQuerySize(tdTestGuestCtrlBase):
331 """
332 Test for the file size query API call (fileQuerySize).
333 """
334 def __init__(self, sFile = "", sUser = "", sPassword = ""):
335 tdTestGuestCtrlBase.__init__(self);
336 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
337 self.sFile = sFile;
338
339class tdTestFileReadWrite(tdTestGuestCtrlBase):
340 """
341 Tests reading from guest files.
342 """
343 def __init__(self, sFile = "", sUser = "", sPassword = "",
344 sOpenMode = "r", sDisposition = "",
345 sSharingMode = "",
346 lCreationMode = 0, cbOffset = 0, cbToReadWrite = 0,
347 aBuf = None):
348 tdTestGuestCtrlBase.__init__(self);
349 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain = "");
350 self.sFile = sFile;
351 self.sOpenMode = sOpenMode;
352 self.sDisposition = sDisposition;
353 self.sSharingMode = sSharingMode;
354 self.lCreationMode = lCreationMode;
355 self.cbOffset = cbOffset;
356 self.cbToReadWrite = cbToReadWrite;
357 self.aBuf = aBuf;
358
359 def getOpenAction(self):
360 """ Converts string disposition to open action enum. """
361 if self.sDisposition == 'oe': return vboxcon.FileOpenAction_OpenExisting;
362 if self.sDisposition == 'oc': return vboxcon.FileOpenAction_OpenOrCreate;
363 if self.sDisposition == 'ce': return vboxcon.FileOpenAction_CreateNew;
364 if self.sDisposition == 'ca': return vboxcon.FileOpenAction_CreateOrReplace;
365 if self.sDisposition == 'ot': return vboxcon.FileOpenAction_OpenExistingTruncated;
366 if self.sDisposition == 'oa': return vboxcon.FileOpenAction_AppendOrCreate;
367 raise base.GenError(self.sDisposition);
368
369 def getAccessMode(self):
370 """ Converts open mode to access mode enum. """
371 if self.sOpenMode == 'r': return vboxcon.FileOpenMode_ReadOnly;
372 if self.sOpenMode == 'w': return vboxcon.FileOpenMode_WriteOnly;
373 if self.sOpenMode == 'w+': return vboxcon.FileOpenMode_ReadWrite;
374 if self.sOpenMode == 'r+': return vboxcon.FileOpenMode_ReadWrite;
375 raise base.GenError(self.sOpenMode);
376
377 def getSharingMode(self):
378 """ Converts the sharing mode. """
379 return vboxcon.FileSharingMode_All;
380
381class tdTestSession(tdTestGuestCtrlBase):
382 """
383 Test the guest session handling.
384 """
385 def __init__(self, sUser = "", sPassword = "", sDomain = "", \
386 sSessionName = ""):
387 tdTestGuestCtrlBase.__init__(self);
388 self.sSessionName = sSessionName;
389 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain);
390
391 def getSessionCount(self, oVBoxMgr):
392 """
393 Helper for returning the number of currently
394 opened guest sessions of a VM.
395 """
396 if self.oTest.oGuest is None:
397 return 0;
398 aoSession = oVBoxMgr.getArray(self.oTest.oGuest, 'sessions')
399 return len(aoSession);
400
401class tdTestSessionEx(tdTestGuestCtrlBase):
402 """
403 Test the guest session.
404 """
405 def __init__(self, aoSteps = None, enmUser = None):
406 tdTestGuestCtrlBase.__init__(self);
407 assert enmUser == None; # For later.
408 self.enmUser = enmUser;
409 self.aoSteps = aoSteps if aoSteps is not None else [];
410
411 def execute(self, oTstDrv, oVmSession, oTxsSession, oTestVm, sMsgPrefix):
412 """
413 Executes the test.
414 """
415 #
416 # Create a session.
417 #
418 assert self.enmUser == None; # For later.
419 self.oCreds = tdCtxCreds(oTestVm = oTestVm);
420 self.setEnvironment(oVmSession, oTxsSession, oTestVm);
421 reporter.log2('%s: %s steps' % (sMsgPrefix, len(self.aoSteps),));
422 fRc, oCurSession = self.createSession(sMsgPrefix);
423 if fRc is True:
424 #
425 # Execute the tests.
426 #
427 try:
428 fRc = self.executeSteps(oTstDrv, oCurSession, sMsgPrefix);
429 except:
430 reporter.errorXcpt('%s: Unexpected exception executing test steps' % (sMsgPrefix,));
431 fRc = False;
432
433 fRc2 = self.closeSession();
434 if fRc2 is False:
435 reporter.error('%s: Session could not be closed' % (sMsgPrefix,));
436 fRc = False;
437 else:
438 reporter.error('%s: Session creation failed' % (sMsgPrefix,));
439 fRc = False;
440 return fRc;
441
442 def executeSteps(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
443 """
444 Executes just the steps.
445 Returns True on success, False on test failure.
446 """
447 fRc = True;
448 for (i, oStep) in enumerate(self.aoSteps):
449 fRc2 = oStep.execute(oTstDrv, oGstCtrlSession, sMsgPrefix + ', step #%d' % i);
450 if fRc2 is False:
451 fRc = False;
452 return fRc;
453
454
455#
456# Scheduling Environment Changes with the Guest Control Session.
457#
458
459class tdStepSessionSetEnv(object):
460 """
461 Guest session environment: schedule putenv
462 """
463 def __init__(self, sVar, sValue, hrcExpected = 0):
464 self.sVar = sVar;
465 self.sValue = sValue;
466 self.hrcExpected = hrcExpected;
467
468 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
469 """
470 Executes the step.
471 Returns True on success, False on test failure.
472 """
473 reporter.log2('tdStepSessionSetEnv: sVar=%s sValue=%s hrcExpected=%#x' % (self.sVar, self.sValue, self.hrcExpected,));
474 try:
475 if oTstDrv.fpApiVer >= 5.0:
476 oGstCtrlSession.environmentScheduleSet(self.sVar, self.sValue);
477 else:
478 oGstCtrlSession.environmentSet(self.sVar, self.sValue);
479 except vbox.ComException, oXcpt:
480 # Is this an expected failure?
481 if vbox.ComError.equal(oXcpt, self.hrcExpected):
482 return True;
483 reporter.errorXcpt('%s: Expected hrc=%#x (%s) got %#x (%s) instead (setenv %s=%s)'
484 % (sMsgPrefix, self.hrcExpected, vbox.ComError.toString(self.hrcExpected),
485 vbox.ComError.getXcptResult(oXcpt),
486 vbox.ComError.toString(vbox.ComError.getXcptResult(oXcpt)),
487 self.sVar, self.sValue,));
488 return False;
489 except:
490 reporter.errorXcpt('%s: Unexpected exception in tdStepSessionSetEnv::execute (%s=%s)'
491 % (sMsgPrefix, self.sVar, self.sValue,));
492 return False;
493
494 # Should we succeed?
495 if self.hrcExpected != 0:
496 reporter.error('%s: Expected hrcExpected=%#x, got S_OK (putenv %s=%s)'
497 % (sMsgPrefix, self.hrcExpected, self.sVar, self.sValue,));
498 return False;
499 return True;
500
501class tdStepSessionUnsetEnv(object):
502 """
503 Guest session environment: schedule unset.
504 """
505 def __init__(self, sVar, hrcExpected = 0):
506 self.sVar = sVar;
507 self.hrcExpected = hrcExpected;
508
509 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
510 """
511 Executes the step.
512 Returns True on success, False on test failure.
513 """
514 reporter.log2('tdStepSessionUnsetEnv: sVar=%s hrcExpected=%#x' % (self.sVar, self.hrcExpected,));
515 try:
516 if oTstDrv.fpApiVer >= 5.0:
517 oGstCtrlSession.environmentScheduleUnset(self.sVar);
518 else:
519 oGstCtrlSession.environmentUnset(self.sVar);
520 except vbox.ComException, oXcpt:
521 # Is this an expected failure?
522 if vbox.ComError.equal(oXcpt, self.hrcExpected):
523 return True;
524 reporter.errorXcpt('%s: Expected hrc=%#x (%s) got %#x (%s) instead (unsetenv %s)'
525 % (sMsgPrefix, self.hrcExpected, vbox.ComError.toString(self.hrcExpected),
526 vbox.ComError.getXcptResult(oXcpt),
527 vbox.ComError.toString(vbox.ComError.getXcptResult(oXcpt)),
528 self.sVar,));
529 return False;
530 except:
531 reporter.errorXcpt('%s: Unexpected exception in tdStepSessionUnsetEnv::execute (%s)'
532 % (sMsgPrefix, self.sVar,));
533 return False;
534
535 # Should we succeed?
536 if self.hrcExpected != 0:
537 reporter.error('%s: Expected hrcExpected=%#x, got S_OK (unsetenv %s)'
538 % (sMsgPrefix, self.hrcExpected, self.sVar,));
539 return False;
540 return True;
541
542class tdStepSessionBulkEnv(object):
543 """
544 Guest session environment: Bulk environment changes.
545 """
546 def __init__(self, asEnv = None, hrcExpected = 0):
547 self.asEnv = asEnv if asEnv is not None else [];
548 self.hrcExpected = hrcExpected;
549
550 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
551 """
552 Executes the step.
553 Returns True on success, False on test failure.
554 """
555 reporter.log2('tdStepSessionBulkEnv: asEnv=%s hrcExpected=%#x' % (self.asEnv, self.hrcExpected,));
556 try:
557 if oTstDrv.fpApiVer >= 5.0:
558 oTstDrv.oVBoxMgr.setArray(oGstCtrlSession, 'environmentChanges', self.asEnv);
559 else:
560 oTstDrv.oVBoxMgr.setArray(oGstCtrlSession, 'environment', self.asEnv);
561 except vbox.ComException, oXcpt:
562 # Is this an expected failure?
563 if vbox.ComError.equal(oXcpt, self.hrcExpected):
564 return True;
565 reporter.errorXcpt('%s: Expected hrc=%#x (%s) got %#x (%s) instead (asEnv=%s)'
566 % (sMsgPrefix, self.hrcExpected, vbox.ComError.toString(self.hrcExpected),
567 vbox.ComError.getXcptResult(oXcpt),
568 vbox.ComError.toString(vbox.ComError.getXcptResult(oXcpt)),
569 self.asEnv,));
570 return False;
571 except:
572 reporter.errorXcpt('%s: Unexpected exception writing the environmentChanges property (asEnv=%s).'
573 % (sMsgPrefix, self.asEnv));
574 return False;
575 return True;
576
577class tdStepSessionClearEnv(tdStepSessionBulkEnv):
578 """
579 Guest session environment: clears the scheduled environment changes.
580 """
581 def __init__(self):
582 tdStepSessionBulkEnv.__init__(self);
583
584
585class tdStepSessionCheckEnv(object):
586 """
587 Check the currently scheduled environment changes of a guest control session.
588 """
589 def __init__(self, asEnv = None):
590 self.asEnv = asEnv if asEnv is not None else [];
591
592 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
593 """
594 Executes the step.
595 Returns True on success, False on test failure.
596 """
597 reporter.log2('tdStepSessionCheckEnv: asEnv=%s' % (self.asEnv,));
598
599 #
600 # Get the environment change list.
601 #
602 try:
603 if oTstDrv.fpApiVer >= 5.0:
604 asCurEnv = oTstDrv.oVBoxMgr.getArray(oGstCtrlSession, 'environmentChanges');
605 else:
606 asCurEnv = oTstDrv.oVBoxMgr.getArray(oGstCtrlSession, 'environment');
607 except:
608 reporter.errorXcpt('%s: Unexpected exception reading the environmentChanges property.' % (sMsgPrefix,));
609 return False;
610
611 #
612 # Compare it with the expected one by trying to remove each expected value
613 # and the list anything unexpected.
614 #
615 fRc = True;
616 asCopy = list(asCurEnv); # just in case asCurEnv is immutable
617 for sExpected in self.asEnv:
618 try:
619 asCopy.remove(sExpected);
620 except:
621 reporter.error('%s: Expected "%s" to be in the resulting environment' % (sMsgPrefix, sExpected,));
622 fRc = False;
623 for sUnexpected in asCopy:
624 reporter.error('%d: Unexpected "%s" in the resulting environment' % (sMsgPrefix, sUnexpected,));
625 fRc = False;
626
627 if fRc is not True:
628 reporter.log2('%s: Current environment: %s' % (sMsgPrefix, asCurEnv));
629 return fRc;
630
631#
632#
633#
634
635class tdTestSessionFileRefs(tdTestGuestCtrlBase):
636 """
637 Tests session file (IGuestFile) reference counting.
638 """
639 def __init__(self, cRefs = 0):
640 tdTestGuestCtrlBase.__init__(self);
641 self.cRefs = cRefs;
642
643class tdTestSessionDirRefs(tdTestGuestCtrlBase):
644 """
645 Tests session directory (IGuestDirectory) reference counting.
646 """
647 def __init__(self, cRefs = 0):
648 tdTestGuestCtrlBase.__init__(self);
649 self.cRefs = cRefs;
650
651class tdTestSessionProcRefs(tdTestGuestCtrlBase):
652 """
653 Tests session process (IGuestProcess) reference counting.
654 """
655 def __init__(self, cRefs = 0):
656 tdTestGuestCtrlBase.__init__(self);
657 self.cRefs = cRefs;
658
659class tdTestUpdateAdditions(tdTestGuestCtrlBase):
660 """
661 Test updating the Guest Additions inside the guest.
662 """
663 def __init__(self, sSrc = "", aArgs = None, aFlags = None,
664 sUser = "", sPassword = "", sDomain = ""):
665 tdTestGuestCtrlBase.__init__(self);
666 self.oCreds = tdCtxCreds(sUser, sPassword, sDomain);
667 self.sSrc = sSrc;
668 self.aArgs = aArgs;
669 self.aFlags = aFlags;
670
671class tdTestResult(object):
672 """
673 Base class for test results.
674 """
675 def __init__(self, fRc = False):
676 ## The overall test result.
677 self.fRc = fRc;
678
679class tdTestResultDirRead(tdTestResult):
680 """
681 Test result for reading guest directories.
682 """
683 def __init__(self, fRc = False,
684 numFiles = 0, numDirs = 0):
685 tdTestResult.__init__(self, fRc = fRc);
686 self.numFiles = numFiles;
687 self.numDirs = numDirs;
688
689class tdTestResultExec(tdTestResult):
690 """
691 Holds a guest process execution test result,
692 including the exit code, status + aFlags.
693 """
694 def __init__(self, fRc = False, \
695 uExitStatus = 500, iExitCode = 0, \
696 sBuf = None, cbBuf = 0, \
697 cbStdOut = 0, cbStdErr = 0):
698 tdTestResult.__init__(self);
699 ## The overall test result.
700 self.fRc = fRc;
701 ## Process exit stuff.
702 self.uExitStatus = uExitStatus;
703 self.iExitCode = iExitCode;
704 ## Desired buffer length returned back from stdout/stderr.
705 self.cbBuf = cbBuf;
706 ## Desired buffer result from stdout/stderr. Use with caution!
707 self.sBuf = sBuf;
708 self.cbStdOut = cbStdOut;
709 self.cbStdErr = cbStdErr;
710
711class tdTestResultFileStat(tdTestResult):
712 """
713 Test result for stat'ing guest files.
714 """
715 def __init__(self, fRc = False,
716 cbSize = 0, eFileType = 0):
717 tdTestResult.__init__(self, fRc = fRc);
718 self.cbSize = cbSize;
719 self.eFileType = eFileType;
720 ## @todo Add more information.
721
722class tdTestResultFileReadWrite(tdTestResult):
723 """
724 Test result for reading + writing guest directories.
725 """
726 def __init__(self, fRc = False,
727 cbProcessed = 0, cbOffset = 0, aBuf = None):
728 tdTestResult.__init__(self, fRc = fRc);
729 self.cbProcessed = cbProcessed;
730 self.cbOffset = cbOffset;
731 self.aBuf = aBuf;
732
733class tdTestResultSession(tdTestResult):
734 """
735 Test result for guest session counts.
736 """
737 def __init__(self, fRc = False, cNumSessions = 0):
738 tdTestResult.__init__(self, fRc = fRc);
739 self.cNumSessions = cNumSessions;
740
741class SubTstDrvAddGuestCtrl(base.SubTestDriverBase):
742 """
743 Sub-test driver for executing guest control (VBoxService, IGuest) tests.
744 """
745
746 def __init__(self, oTstDrv):
747 base.SubTestDriverBase.__init__(self, 'add-guest-ctrl', oTstDrv);
748
749 ## @todo base.TestBase.
750 self.asTestsDef = \
751 [
752 'session_basic', 'session_env', 'session_file_ref', 'session_dir_ref', 'session_proc_ref', \
753 'exec_basic', 'exec_errorlevel', 'exec_timeout', \
754 'dir_create', 'dir_create_temp', 'dir_read', \
755 'file_remove', 'file_stat', 'file_read', 'file_write', \
756 'copy_to', 'copy_from', \
757 'update_additions'
758 ];
759 self.asTests = self.asTestsDef;
760
761 def parseOption(self, asArgs, iArg): # pylint: disable=R0912,R0915
762 if asArgs[iArg] == '--add-guest-ctrl-tests':
763 iArg += 1;
764 if asArgs[iArg] == 'all': # Nice for debugging scripts.
765 self.asTests = self.asTestsDef;
766 return iArg + 1;
767
768 iNext = self.oTstDrv.requireMoreArgs(1, asArgs, iArg);
769 self.asTests = asArgs[iArg].split(':');
770 for s in self.asTests:
771 if s not in self.asTestsDef:
772 raise base.InvalidOption('The "--add-guest-ctrl-tests" value "%s" is not valid; valid values are: %s' \
773 % (s, ' '.join(self.asTestsDef)));
774 return iNext;
775 return iArg;
776
777 def showUsage(self):
778 base.SubTestDriverBase.showUsage(self);
779 reporter.log(' --add-guest-ctrl-tests <s1[:s2[:]]>');
780 reporter.log(' Default: %s (all)' % (':'.join(self.asTestsDef)));
781 return True;
782
783 def testIt(self, oTestVm, oSession, oTxsSession):
784 """
785 Executes the test.
786
787 Returns fRc, oTxsSession. The latter may have changed.
788 """
789 reporter.log("Active tests: %s" % (self.asTests,));
790
791 # Do the testing.
792 reporter.testStart('Session Basics');
793 fSkip = 'session_basic' not in self.asTests;
794 if fSkip == False:
795 fRc, oTxsSession = self.testGuestCtrlSession(oSession, oTxsSession, oTestVm);
796 reporter.testDone(fSkip);
797
798 reporter.testStart('Session Environment');
799 fSkip = 'session_env' not in self.asTests or fRc is False;
800 if fSkip == False:
801 fRc, oTxsSession = self.testGuestCtrlSessionEnvironment(oSession, oTxsSession, oTestVm);
802 reporter.testDone(fSkip);
803
804 reporter.testStart('Session File References');
805 fSkip = 'session_file_ref' not in self.asTests;
806 if fSkip == False:
807 fRc, oTxsSession = self.testGuestCtrlSessionFileRefs(oSession, oTxsSession, oTestVm);
808 reporter.testDone(fSkip);
809
810 ## @todo Implement this.
811 #reporter.testStart('Session Directory References');
812 #fSkip = 'session_dir_ref' not in self.asTests;
813 #if fSkip == False:
814 # fRc, oTxsSession = self.testGuestCtrlSessionDirRefs(oSession, oTxsSession, oTestVm);
815 #reporter.testDone(fSkip);
816
817 reporter.testStart('Session Process References');
818 fSkip = 'session_proc_ref' not in self.asTests or fRc is False;
819 if fSkip == False:
820 fRc, oTxsSession = self.testGuestCtrlSessionProcRefs(oSession, oTxsSession, oTestVm);
821 reporter.testDone(fSkip);
822
823 reporter.testStart('Execution');
824 fSkip = 'exec_basic' not in self.asTests or fRc is False;
825 if fSkip == False:
826 fRc, oTxsSession = self.testGuestCtrlExec(oSession, oTxsSession, oTestVm);
827 reporter.testDone(fSkip);
828
829 reporter.testStart('Execution Error Levels');
830 fSkip = 'exec_errorlevel' not in self.asTests or fRc is False;
831 if fSkip == False:
832 fRc, oTxsSession = self.testGuestCtrlExecErrorLevel(oSession, oTxsSession, oTestVm);
833 reporter.testDone(fSkip);
834
835 reporter.testStart('Execution Timeouts');
836 fSkip = 'exec_timeout' not in self.asTests or fRc is False;
837 if fSkip == False:
838 fRc, oTxsSession = self.testGuestCtrlExecTimeout(oSession, oTxsSession, oTestVm);
839 reporter.testDone(fSkip);
840
841 reporter.testStart('Creating directories');
842 fSkip = 'dir_create' not in self.asTests or fRc is False;
843 if fSkip == False:
844 fRc, oTxsSession = self.testGuestCtrlDirCreate(oSession, oTxsSession, oTestVm);
845 reporter.testDone(fSkip);
846
847 reporter.testStart('Creating temporary directories');
848 fSkip = 'dir_create_temp' not in self.asTests or fRc is False;
849 if fSkip == False:
850 fRc, oTxsSession = self.testGuestCtrlDirCreateTemp(oSession, oTxsSession, oTestVm);
851 reporter.testDone(fSkip);
852
853 reporter.testStart('Reading directories');
854 fSkip = 'dir_read' not in self.asTests or fRc is False;
855 if fSkip == False:
856 fRc, oTxsSession = self.testGuestCtrlDirRead(oSession, oTxsSession, oTestVm);
857 reporter.testDone(fSkip);
858
859 # FIXME: Failing test.
860 # reporter.testStart('Copy to guest');
861 # fSkip = 'copy_to' not in self.asTests or fRc is False;
862 # if fSkip == False:
863 # fRc, oTxsSession = self.testGuestCtrlCopyTo(oSession, oTxsSession, oTestVm);
864 # reporter.testDone(fSkip);
865
866 reporter.testStart('Copy from guest');
867 fSkip = 'copy_from' not in self.asTests or fRc is False;
868 if fSkip == False:
869 fRc, oTxsSession = self.testGuestCtrlCopyFrom(oSession, oTxsSession, oTestVm);
870 reporter.testDone(fSkip);
871
872 reporter.testStart('Removing files');
873 fSkip = 'file_remove' not in self.asTests or fRc is False;
874 if fSkip == False:
875 fRc, oTxsSession = self.testGuestCtrlFileRemove(oSession, oTxsSession, oTestVm);
876 reporter.testDone(fSkip);
877
878 reporter.testStart('Querying file information (stat)');
879 fSkip = 'file_stat' not in self.asTests or fRc is False;
880 if fSkip == False:
881 fRc, oTxsSession = self.testGuestCtrlFileStat(oSession, oTxsSession, oTestVm);
882 reporter.testDone(fSkip);
883
884 # FIXME: Failing tests.
885 # reporter.testStart('File read');
886 # fSkip = 'file_read' not in self.asTests or fRc is False;
887 # if fSkip == False:
888 # fRc, oTxsSession = self.testGuestCtrlFileRead(oSession, oTxsSession, oTestVm);
889 # reporter.testDone(fSkip);
890
891 # reporter.testStart('File write');
892 # fSkip = 'file_write' not in self.asTests or fRc is False;
893 # if fSkip == False:
894 # fRc, oTxsSession = self.testGuestCtrlFileWrite(oSession, oTxsSession, oTestVm);
895 # reporter.testDone(fSkip);
896
897 reporter.testStart('Updating Guest Additions');
898 fSkip = 'update_additions' not in self.asTests or fRc is False;
899 # Skip test for updating Guest Additions if we run on a too old (Windows) guest.
900 fSkip = oTestVm.sKind in ('WindowsNT4', 'Windows2000', 'WindowsXP', 'Windows2003');
901 if fSkip == False:
902 fRc, oTxsSession = self.testGuestCtrlUpdateAdditions(oSession, oTxsSession, oTestVm);
903 reporter.testDone(fSkip);
904
905 return (fRc, oTxsSession);
906
907 def gctrlCopyFileFrom(self, oGuestSession, sSrc, sDst, aFlags):
908 """
909 Helper function to copy a single file from the guest to the host.
910 """
911 fRc = True; # Be optimistic.
912 try:
913 reporter.log2('Copying guest file "%s" to host "%s"' % (sSrc, sDst));
914 if self.oTstDrv.fpApiVer >= 5.0:
915 curProgress = oGuestSession.fileCopyFromGuest(sSrc, sDst, aFlags);
916 else:
917 curProgress = oGuestSession.copyFrom(sSrc, sDst, aFlags);
918 if curProgress is not None:
919 oProgress = vboxwrappers.ProgressWrapper(curProgress, self.oTstDrv.oVBoxMgr, self, "gctrlCopyFrm");
920 try:
921 iRc = oProgress.waitForOperation(0, fIgnoreErrors = True);
922 if iRc != 0:
923 reporter.log('Waiting for copyFrom failed');
924 fRc = False;
925 except:
926 reporter.logXcpt('Copy from waiting exception for sSrc="%s", sDst="%s":' \
927 % (sSrc, sDst));
928 fRc = False;
929 except:
930 # Just log, don't assume an error here (will be done in the main loop then).
931 reporter.logXcpt('Copy from exception for sSrc="%s", sDst="%s":' \
932 % (sSrc, sDst));
933 fRc = False;
934
935 return fRc;
936
937 def gctrlCopyFileTo(self, oGuestSession, sSrc, sDst, aFlags):
938 """
939 Helper function to copy a single file from host to the guest.
940 """
941 fRc = True; # Be optimistic.
942 try:
943 reporter.log2('Copying host file "%s" to guest "%s"' % (sSrc, sDst));
944 if self.oTstDrv.fpApiVer >= 5.0:
945 curProgress = oGuestSession.fileCopyToGuest(sSrc, sDst, aFlags);
946 else:
947 curProgress = oGuestSession.copyTo(sSrc, sDst, aFlags);
948 if curProgress is not None:
949 oProgress = vboxwrappers.ProgressWrapper(curProgress, self.oTstDrv.oVBoxMgr, self, "gctrlCopyTo");
950 try:
951 iRc = oProgress.waitForOperation(0, fIgnoreErrors = True);
952 if iRc != 0:
953 reporter.log('Waiting for copyTo failed');
954 fRc = False;
955 except:
956 reporter.logXcpt('Copy to waiting exception for sSrc="%s", sDst="%s":' \
957 % (sSrc, sDst));
958 fRc = False;
959 else:
960 reporter.error('No progress object returned');
961 except:
962 # Just log, don't assume an error here (will be done in the main loop then).
963 reporter.logXcpt('Copy to exception for sSrc="%s", sDst="%s":' \
964 % (sSrc, sDst));
965 fRc = False;
966
967 return fRc;
968
969 def gctrlCopyFrom(self, oTest, oRes, oGuestSession, subDir = ''): # pylint: disable=R0914
970 """
971 Copies files / directories to the host.
972 Source always contains the absolute path, subDir all paths
973 below it.
974 """
975 ## @todo r=bird: The use subDir and sSubDir in this method is extremely confusing!!
976 # Just follow the coding guidelines and ALWAYS use prefixes, please!
977 fRc = True; # Be optimistic.
978
979 sSrc = oTest.sSrc;
980 sDst = oTest.sDst;
981 aFlags = oTest.aFlags;
982
983 if sSrc == "" \
984 or os.path.isfile(sSrc):
985 return self.gctrlCopyFileFrom(oGuestSession, \
986 sSrc, sDst, aFlags);
987 sSrcAbs = sSrc;
988 if subDir != "":
989 sSrcAbs = os.path.join(sSrc, subDir);
990 sFilter = ""; # No filter.
991
992 sDstAbs = os.path.join(sDst, subDir);
993 reporter.log2('Copying guest directory "%s" to host "%s"' % (sSrcAbs, sDstAbs));
994
995 try:
996 #reporter.log2('Directory="%s", filter="%s", aFlags="%s"' % (sCurDir, sFilter, aFlags));
997 oCurDir = oGuestSession.directoryOpen(sSrcAbs, sFilter, aFlags);
998 while fRc:
999 try:
1000 oFsObjInfo = oCurDir.read();
1001 if oFsObjInfo.name == "." \
1002 or oFsObjInfo.name == "..":
1003 #reporter.log2('\tSkipping "%s"' % (oFsObjInfo.name,));
1004 continue; # Skip "." and ".." entries.
1005 if oFsObjInfo.type is vboxcon.FsObjType_Directory:
1006 #reporter.log2('\tDirectory "%s"' % (oFsObjInfo.name,));
1007 sDirCreate = sDst;
1008 if subDir != "":
1009 sDirCreate = os.path.join(sDirCreate, subDir);
1010 sDirCreate = os.path.join(sDirCreate, oFsObjInfo.name);
1011 try:
1012 reporter.log2('\tCreating directory "%s"' % (sDirCreate,));
1013 os.makedirs(sDirCreate);
1014 sSubDir = oFsObjInfo.name;
1015 if subDir != "":
1016 sSubDir = os.path.join(subDir, oFsObjInfo.name);
1017 self.gctrlCopyFrom(oTest, oRes, oGuestSession, sSubDir);
1018 except (OSError) as e:
1019 if e.errno == errno.EEXIST:
1020 pass;
1021 else:
1022 # Just log, don't assume an error here (will be done in the main loop then).
1023 reporter.logXcpt('\tDirectory creation exception for directory="%s":' % (sSubDir,));
1024 raise;
1025 elif oFsObjInfo.type is vboxcon.FsObjType_File:
1026 #reporter.log2('\tFile "%s"' % (oFsObjInfo.name,));
1027 sSourceFile = os.path.join(sSrcAbs, oFsObjInfo.name);
1028 sDestFile = os.path.join(sDstAbs, oFsObjInfo.name);
1029 self.gctrlCopyFileFrom(oGuestSession, sSourceFile, sDestFile, aFlags);
1030 elif oFsObjInfo.type is vboxcon.FsObjType_Symlink:
1031 #reporter.log2('\tSymlink "%s" -- not tested yet' % oFsObjInfo.name);
1032 pass;
1033 else:
1034 reporter.error('\tDirectory "%s" contains invalid directory entry "%s" (%d)' \
1035 % (sSubDir, oFsObjInfo.name, oFsObjInfo.type));
1036 fRc = False;
1037 except Exception, oXcpt:
1038 # No necessarily an error -- could be VBOX_E_OBJECT_NOT_FOUND. See reference.
1039 if vbox.ComError.equal(oXcpt, vbox.ComError.VBOX_E_OBJECT_NOT_FOUND):
1040 #reporter.log2('\tNo more directory entries for "%s"' % (sCurDir,));
1041 break
1042 # Just log, don't assume an error here (will be done in the main loop then).
1043 reporter.logXcpt('\tDirectory read exception for directory="%s":' % (sSrcAbs,));
1044 fRc = False;
1045 break;
1046 oCurDir.close();
1047 except:
1048 # Just log, don't assume an error here (will be done in the main loop then).
1049 reporter.logXcpt('\tDirectory open exception for directory="%s":' % (sSrcAbs,));
1050 fRc = False;
1051
1052 return fRc;
1053
1054 def gctrlCopyTo(self, oTest, oGuestSession, subDir = ''): # pylint: disable=R0914
1055 """
1056 Copies files / directories to the guest.
1057 Source always contains the absolute path,
1058 subDir all paths below it.
1059 """
1060 fRc = True; # Be optimistic.
1061
1062 sSrc = oTest.sSrc;
1063 sDst = oTest.sDst;
1064 aFlags = oTest.aFlags;
1065
1066 reporter.log2('sSrc=%s, sDst=%s, aFlags=%s' % (sSrc, sDst, aFlags));
1067
1068 sSrcAbs = sSrc;
1069 if subDir != "":
1070 sSrcAbs = os.path.join(sSrc, subDir);
1071
1072 # Note: Current test might want to test copying empty sources
1073 if not os.path.exists(sSrcAbs) \
1074 or os.path.isfile(sSrcAbs):
1075 return self.gctrlCopyFileTo(oGuestSession, \
1076 sSrcAbs, sDst, aFlags);
1077
1078 sDstAbs = os.path.join(sDst, subDir);
1079 reporter.log2('Copying host directory "%s" to guest "%s"' % (sSrcAbs, sDstAbs));
1080
1081 try:
1082 # Note: Symlinks intentionally not considered here.
1083 for (sDirCurrent, oDirs, oFiles) in os.walk(sSrcAbs, topdown=True):
1084 for sFile in oFiles:
1085 sCurFile = os.path.join(sDirCurrent, sFile);
1086 reporter.log2('Processing host file "%s"' % (sCurFile,));
1087 sFileDest = os.path.join(sDstAbs, os.path.relpath(sCurFile, sSrcAbs));
1088 reporter.log2('Copying file to "%s"' % (sFileDest,));
1089 fRc = self.gctrlCopyFileTo(oGuestSession, \
1090 sCurFile, sFileDest, aFlags);
1091 if fRc is False:
1092 break;
1093
1094 if fRc is False:
1095 break;
1096
1097 for sSubDir in oDirs:
1098 sCurDir = os.path.join(sDirCurrent, sSubDir);
1099 reporter.log2('Processing host dir "%s"' % (sCurDir,));
1100 sDirDest = os.path.join(sDstAbs, os.path.relpath(sCurDir, sSrcAbs));
1101 reporter.log2('Creating guest dir "%s"' % (sDirDest,));
1102 oGuestSession.directoryCreate(sDirDest, \
1103 700, [ vboxcon.DirectoryCreateFlag_Parents ]);
1104 if fRc is False:
1105 break;
1106
1107 if fRc is False:
1108 break;
1109 except:
1110 # Just log, don't assume an error here (will be done in the main loop then).
1111 reporter.logXcpt('Copy to exception for sSrc="%s", sDst="%s":' \
1112 % (sSrcAbs, sDst));
1113 return False;
1114
1115 return fRc;
1116
1117 def gctrlCreateDir(self, oTest, oRes, oGuestSession):
1118 """
1119 Helper function to create a guest directory specified in
1120 the current test.
1121 """
1122 fRc = True; # Be optimistic.
1123 reporter.log2('Creating directory "%s"' % (oTest.sDirectory,));
1124
1125 try:
1126 oGuestSession.directoryCreate(oTest.sDirectory, \
1127 oTest.fMode, oTest.aFlags);
1128 if self.oTstDrv.fpApiVer >= 5.0:
1129 fDirExists = oGuestSession.directoryExists(oTest.sDirectory, False);
1130 else:
1131 fDirExists = oGuestSession.directoryExists(oTest.sDirectory);
1132 if fDirExists is False \
1133 and oRes.fRc is True:
1134 # Directory does not exist but we want it to.
1135 fRc = False;
1136 except:
1137 reporter.logXcpt('Directory create exception for directory "%s":' % (oTest.sDirectory,));
1138 if oRes.fRc is True:
1139 # Just log, don't assume an error here (will be done in the main loop then).
1140 fRc = False;
1141 # Directory creation failed, which was the expected result.
1142
1143 return fRc;
1144
1145 def gctrlReadDir(self, oTest, oRes, oGuestSession, subDir = ''): # pylint: disable=R0914
1146 """
1147 Helper function to read a guest directory specified in
1148 the current test.
1149 """
1150 sDir = oTest.sDirectory;
1151 sFilter = oTest.sFilter;
1152 aFlags = oTest.aFlags;
1153
1154 fRc = True; # Be optimistic.
1155 cDirs = 0; # Number of directories read.
1156 cFiles = 0; # Number of files read.
1157
1158 try:
1159 sCurDir = os.path.join(sDir, subDir);
1160 #reporter.log2('Directory="%s", filter="%s", aFlags="%s"' % (sCurDir, sFilter, aFlags));
1161 oCurDir = oGuestSession.directoryOpen(sCurDir, sFilter, aFlags);
1162 while fRc:
1163 try:
1164 oFsObjInfo = oCurDir.read();
1165 if oFsObjInfo.name == "." \
1166 or oFsObjInfo.name == "..":
1167 #reporter.log2('\tSkipping "%s"' % oFsObjInfo.name);
1168 continue; # Skip "." and ".." entries.
1169 if oFsObjInfo.type is vboxcon.FsObjType_Directory:
1170 #reporter.log2('\tDirectory "%s"' % oFsObjInfo.name);
1171 cDirs += 1;
1172 sSubDir = oFsObjInfo.name;
1173 if subDir != "":
1174 sSubDir = os.path.join(subDir, oFsObjInfo.name);
1175 fRc, cSubDirs, cSubFiles = self.gctrlReadDir(oTest, oRes, oGuestSession, sSubDir);
1176 cDirs += cSubDirs;
1177 cFiles += cSubFiles;
1178 elif oFsObjInfo.type is vboxcon.FsObjType_File:
1179 #reporter.log2('\tFile "%s"' % oFsObjInfo.name);
1180 cFiles += 1;
1181 elif oFsObjInfo.type is vboxcon.FsObjType_Symlink:
1182 #reporter.log2('\tSymlink "%s" -- not tested yet' % oFsObjInfo.name);
1183 pass;
1184 else:
1185 reporter.error('\tDirectory "%s" contains invalid directory entry "%s" (type %d)' % \
1186 (sCurDir, oFsObjInfo.name, oFsObjInfo.type));
1187 fRc = False;
1188 except Exception, oXcpt:
1189 # No necessarily an error -- could be VBOX_E_OBJECT_NOT_FOUND. See reference.
1190 if vbox.ComError.equal(oXcpt, vbox.ComError.VBOX_E_OBJECT_NOT_FOUND):
1191 #reporter.log2('\tNo more directory entries for "%s"' % (sCurDir,));
1192 break
1193 # Just log, don't assume an error here (will be done in the main loop then).
1194 reporter.logXcpt('\tDirectory open exception for directory="%s":' % (sCurDir,));
1195 fRc = False;
1196 break;
1197 oCurDir.close();
1198 except:
1199 # Just log, don't assume an error here (will be done in the main loop then).
1200 reporter.logXcpt('\tDirectory open exception for directory="%s":' % (sCurDir,));
1201 fRc = False;
1202
1203 return (fRc, cDirs, cFiles);
1204
1205 def gctrlExecDoTest(self, i, oTest, oRes, oGuestSession):
1206 """
1207 Wrapper function around gctrlExecute to provide more sanity checking
1208 when needed in actual execution tests.
1209 """
1210 reporter.log('Testing #%d, cmd="%s" ...' % (i, oTest.sCmd));
1211 fRc = self.gctrlExecute(oTest, oGuestSession);
1212 if fRc is oRes.fRc:
1213 if fRc is True:
1214 # Compare exit status / code on successful process execution.
1215 if oTest.uExitStatus != oRes.uExitStatus \
1216 or oTest.iExitCode != oRes.iExitCode:
1217 reporter.error('Test #%d failed: Got exit status + code %d,%d, expected %d,%d'
1218 % (i, oTest.uExitStatus, oTest.iExitCode, oRes.uExitStatus, oRes.iExitCode));
1219 return False;
1220 if fRc is True:
1221 # Compare test / result buffers on successful process execution.
1222 if oTest.sBuf is not None \
1223 and oRes.sBuf is not None:
1224 if bytes(oTest.sBuf) != bytes(oRes.sBuf):
1225 reporter.error('Test #%d failed: Got buffer\n%s (%d bytes), expected\n%s (%d bytes)'
1226 % (i, map(hex, map(ord, oTest.sBuf)), len(oTest.sBuf), \
1227 map(hex, map(ord, oRes.sBuf)), len(oRes.sBuf)));
1228 return False;
1229 else:
1230 reporter.log2('Test #%d passed: Buffers match (%d bytes)' % (i, len(oRes.sBuf)));
1231 elif oRes.sBuf is not None \
1232 and len(oRes.sBuf):
1233 reporter.error('Test #%d failed: Got no buffer data, expected\n%s (%dbytes)' %
1234 (i, map(hex, map(ord, oRes.sBuf)), len(oRes.sBuf)));
1235 return False;
1236 elif oRes.cbStdOut > 0 \
1237 and oRes.cbStdOut != oTest.cbStdOut:
1238 reporter.error('Test #%d failed: Got %d stdout data, expected %d'
1239 % (i, oTest.cbStdOut, oRes.cbStdOut));
1240 return False;
1241 else:
1242 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc, oRes.fRc));
1243 return False;
1244 return True;
1245
1246 def gctrlExecute(self, oTest, oGuestSession):
1247 """
1248 Helper function to execute a program on a guest, specified in
1249 the current test.
1250 """
1251 fRc = True; # Be optimistic.
1252
1253 ## @todo Compare execution timeouts!
1254 #tsStart = base.timestampMilli();
1255
1256 reporter.log2('Using session user=%s, sDomain=%s, session name=%s, session timeout=%d' \
1257 % (oGuestSession.user, oGuestSession.domain, \
1258 oGuestSession.name, oGuestSession.timeout));
1259 reporter.log2('Executing cmd=%s, aFlags=%s, timeout=%d, args=%s, env=%s' \
1260 % (oTest.sCmd, oTest.aFlags, oTest.timeoutMS, \
1261 oTest.aArgs, oTest.aEnv));
1262 try:
1263 curProc = oGuestSession.processCreate(oTest.sCmd,
1264 oTest.aArgs if self.oTstDrv.fpApiVer >= 5.0 else oTest.aArgs[1:],
1265 oTest.aEnv, oTest.aFlags, oTest.timeoutMS);
1266 if curProc is not None:
1267 reporter.log2('Process start requested, waiting for start (%dms) ...' % (oTest.timeoutMS,));
1268 fWaitFor = [ vboxcon.ProcessWaitForFlag_Start ];
1269 waitResult = curProc.waitForArray(fWaitFor, oTest.timeoutMS);
1270 reporter.log2('Wait result returned: %d, current process status is: %d' % (waitResult, curProc.status));
1271
1272 if curProc.status == vboxcon.ProcessStatus_Started:
1273 fWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate ];
1274 if vboxcon.ProcessCreateFlag_WaitForStdOut in oTest.aFlags:
1275 fWaitFor.append(vboxcon.ProcessWaitForFlag_StdOut);
1276 if vboxcon.ProcessCreateFlag_WaitForStdErr in oTest.aFlags:
1277 fWaitFor.append(vboxcon.ProcessWaitForFlag_StdErr);
1278 ## @todo Add vboxcon.ProcessWaitForFlag_StdIn.
1279 reporter.log2('Process (PID %d) started, waiting for termination (%dms), waitFlags=%s ...' \
1280 % (curProc.PID, oTest.timeoutMS, fWaitFor));
1281 while True:
1282 waitResult = curProc.waitForArray(fWaitFor, oTest.timeoutMS);
1283 reporter.log2('Wait returned: %d' % (waitResult,));
1284 try:
1285 # Try stdout.
1286 if waitResult == vboxcon.ProcessWaitResult_StdOut \
1287 or waitResult == vboxcon.ProcessWaitResult_WaitFlagNotSupported:
1288 reporter.log2('Reading stdout ...');
1289 buf = curProc.Read(1, 64 * 1024, oTest.timeoutMS);
1290 if len(buf):
1291 reporter.log2('Process (PID %d) got %d bytes of stdout data' % (curProc.PID, len(buf)));
1292 oTest.cbStdOut += len(buf);
1293 oTest.sBuf = buf; # Appending does *not* work atm, so just assign it. No time now.
1294 # Try stderr.
1295 if waitResult == vboxcon.ProcessWaitResult_StdErr \
1296 or waitResult == vboxcon.ProcessWaitResult_WaitFlagNotSupported:
1297 reporter.log2('Reading stderr ...');
1298 buf = curProc.Read(2, 64 * 1024, oTest.timeoutMS);
1299 if len(buf):
1300 reporter.log2('Process (PID %d) got %d bytes of stderr data' % (curProc.PID, len(buf)));
1301 oTest.cbStdErr += len(buf);
1302 oTest.sBuf = buf; # Appending does *not* work atm, so just assign it. No time now.
1303 # Use stdin.
1304 if waitResult == vboxcon.ProcessWaitResult_StdIn \
1305 or waitResult == vboxcon.ProcessWaitResult_WaitFlagNotSupported:
1306 pass; #reporter.log2('Process (PID %d) needs stdin data' % (curProc.pid,));
1307 # Termination or error?
1308 if waitResult == vboxcon.ProcessWaitResult_Terminate \
1309 or waitResult == vboxcon.ProcessWaitResult_Error \
1310 or waitResult == vboxcon.ProcessWaitResult_Timeout:
1311 reporter.log2('Process (PID %d) reported terminate/error/timeout: %d, status: %d' \
1312 % (curProc.PID, waitResult, curProc.status));
1313 break;
1314 except:
1315 # Just skip reads which returned nothing.
1316 pass;
1317 reporter.log2('Final process status (PID %d) is: %d' % (curProc.PID, curProc.status));
1318 reporter.log2('Process (PID %d) %d stdout, %d stderr' % (curProc.PID, oTest.cbStdOut, oTest.cbStdErr));
1319 oTest.uExitStatus = curProc.status;
1320 oTest.iExitCode = curProc.exitCode;
1321 reporter.log2('Process (PID %d) has exit code: %d' % (curProc.PID, oTest.iExitCode));
1322 except KeyboardInterrupt:
1323 reporter.error('Process (PID %d) execution interrupted' % (curProc.PID,));
1324 if curProc is not None:
1325 curProc.close();
1326 except:
1327 # Just log, don't assume an error here (will be done in the main loop then).
1328 reporter.logXcpt('Execution exception for command "%s":' % (oTest.sCmd,));
1329 fRc = False;
1330
1331 return fRc;
1332
1333 def testGuestCtrlSessionEnvironment(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
1334 """
1335 Tests the guest session environment changes.
1336 """
1337
1338 aaTests = [
1339 # Check basic operations.
1340 tdTestSessionEx([ # Initial environment is empty.
1341 tdStepSessionCheckEnv(),
1342 # Check clearing empty env.
1343 tdStepSessionClearEnv(),
1344 tdStepSessionCheckEnv(),
1345 # Check set.
1346 tdStepSessionSetEnv('FOO', 'BAR'),
1347 tdStepSessionCheckEnv(['FOO=BAR',]),
1348 tdStepSessionClearEnv(),
1349 tdStepSessionCheckEnv(),
1350 # Check unset.
1351 tdStepSessionUnsetEnv('BAR'),
1352 tdStepSessionCheckEnv(['BAR']),
1353 tdStepSessionClearEnv(),
1354 tdStepSessionCheckEnv(),
1355 # Set + unset.
1356 tdStepSessionSetEnv('FOO', 'BAR'),
1357 tdStepSessionCheckEnv(['FOO=BAR',]),
1358 tdStepSessionUnsetEnv('FOO'),
1359 tdStepSessionCheckEnv(['FOO']),
1360 # Bulk environment changes (via attrib) (shall replace existing 'FOO').
1361 tdStepSessionBulkEnv( ['PATH=/bin:/usr/bin', 'TMPDIR=/var/tmp', 'USER=root']),
1362 tdStepSessionCheckEnv(['PATH=/bin:/usr/bin', 'TMPDIR=/var/tmp', 'USER=root']),
1363 ]),
1364 tdTestSessionEx([ # Check that setting the same value several times works.
1365 tdStepSessionSetEnv('FOO','BAR'),
1366 tdStepSessionCheckEnv([ 'FOO=BAR',]),
1367 tdStepSessionSetEnv('FOO','BAR2'),
1368 tdStepSessionCheckEnv([ 'FOO=BAR2',]),
1369 tdStepSessionSetEnv('FOO','BAR3'),
1370 tdStepSessionCheckEnv([ 'FOO=BAR3',]),
1371 # Add a little unsetting to the mix.
1372 tdStepSessionSetEnv('BAR', 'BEAR'),
1373 tdStepSessionCheckEnv([ 'FOO=BAR3', 'BAR=BEAR',]),
1374 tdStepSessionUnsetEnv('FOO'),
1375 tdStepSessionCheckEnv([ 'FOO', 'BAR=BEAR',]),
1376 tdStepSessionSetEnv('FOO','BAR4'),
1377 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR',]),
1378 # The environment is case sensitive.
1379 tdStepSessionSetEnv('foo','BAR5'),
1380 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR', 'foo=BAR5']),
1381 tdStepSessionUnsetEnv('foo'),
1382 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR', 'foo']),
1383 ]),
1384 tdTestSessionEx([ # Bulk settings merges stuff, last entry standing.
1385 tdStepSessionBulkEnv(['FOO=bar', 'foo=bar', 'FOO=doofus', 'TMPDIR=/tmp', 'foo=bar2']),
1386 tdStepSessionCheckEnv(['FOO=doofus', 'TMPDIR=/tmp', 'foo=bar2']),
1387 ]),
1388 # Invalid variable names.
1389 tdTestSessionEx([ tdStepSessionSetEnv('', 'FOO', vbox.ComError.E_INVALIDARG),
1390 tdStepSessionCheckEnv(),
1391 tdStepSessionSetEnv('=', '===', vbox.ComError.E_INVALIDARG),
1392 tdStepSessionCheckEnv(),
1393 tdStepSessionSetEnv('FOO=', 'BAR', vbox.ComError.E_INVALIDARG),
1394 tdStepSessionCheckEnv(),
1395 tdStepSessionSetEnv('=FOO', 'BAR', vbox.ComError.E_INVALIDARG),
1396 tdStepSessionCheckEnv(),
1397 tdStepSessionBulkEnv(['=', 'foo=bar'], vbox.ComError.E_INVALIDARG),
1398 tdStepSessionCheckEnv(),
1399 tdStepSessionBulkEnv(['=FOO', 'foo=bar'], vbox.ComError.E_INVALIDARG),
1400 tdStepSessionCheckEnv(),
1401 ]),
1402 # A bit more weird keys/values.
1403 tdTestSessionEx([ tdStepSessionSetEnv('$$$', ''),
1404 tdStepSessionCheckEnv([ '$$$=',]), ]),
1405 tdTestSessionEx([ tdStepSessionSetEnv('$$$', '%%%'),
1406 tdStepSessionCheckEnv([ '$$$=%%%',]),
1407 ]),
1408 tdTestSessionEx([ tdStepSessionSetEnv(u'ß$%ß&', ''),
1409 tdStepSessionCheckEnv([ u'ß$%ß&=',]),
1410 ]),
1411 # Misc stuff.
1412 tdTestSessionEx([ tdStepSessionSetEnv('FOO', ''),
1413 tdStepSessionCheckEnv(['FOO=',]),
1414 ]),
1415 tdTestSessionEx([ tdStepSessionSetEnv('FOO', 'BAR'),
1416 tdStepSessionCheckEnv(['FOO=BAR',])
1417 ],),
1418 tdTestSessionEx([ tdStepSessionSetEnv('FOO', 'BAR'),
1419 tdStepSessionSetEnv('BAR', 'BAZ'),
1420 tdStepSessionCheckEnv([ 'FOO=BAR', 'BAR=BAZ',]),
1421 ]),
1422 ];
1423
1424 #
1425 # Work through the tests.
1426 #
1427 fRc = True;
1428 for (i, oCurTest) in enumerate(aaTests):
1429 try:
1430 fRc2 = oCurTest.execute(self.oTstDrv, oSession, oTxsSession, oTestVm, 'test %#d' % (i,));
1431 if fRc2 is not True:
1432 fRc = False;
1433 except:
1434 reporter.errorXcpt('Unexpected exception executing test #%d' % (i,));
1435 fRc = False;
1436
1437 return (fRc, oTxsSession);
1438
1439 def testGuestCtrlSession(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
1440 """
1441 Tests the guest session handling.
1442 """
1443
1444 if oTestVm.isWindows():
1445 sUser = "Administrator";
1446 else:
1447 sUser = "vbox";
1448 sPassword = "password";
1449
1450 aaTests = [
1451 # Invalid parameters.
1452 [ tdTestSession(),
1453 tdTestResultSession(fRc = False) ],
1454 [ tdTestSession(sUser = ''),
1455 tdTestResultSession(fRc = False) ],
1456 [ tdTestSession(sPassword = 'bar'),
1457 tdTestResultSession(fRc = False) ],
1458 [ tdTestSession(sDomain = 'boo'),
1459 tdTestResultSession(fRc = False) ],
1460 [ tdTestSession(sPassword = 'bar', sDomain = 'boo'),
1461 tdTestResultSession(fRc = False) ],
1462 # User account without a passwort - forbidden.
1463 [ tdTestSession(sUser = sUser),
1464 tdTestResultSession(fRc = False) ],
1465 # Wrong credentials.
1466 # Note: On Guest Additions < 4.3 this always succeeds because these don't
1467 # support creating dedicated sessions. Instead, guest process creation
1468 # then will fail. See note below.
1469 [ tdTestSession(sUser = 'foo', sPassword = 'bar', sDomain = 'boo'),
1470 tdTestResultSession(fRc = False) ],
1471 # Correct credentials.
1472 [ tdTestSession(sUser = sUser, sPassword = sPassword),
1473 tdTestResultSession(fRc = True, cNumSessions = 1) ]
1474 ];
1475
1476 # Parameters.
1477 fRc = True;
1478 for (i, aTest) in enumerate(aaTests):
1479 curTest = aTest[0]; # tdTestSession, use an index, later.
1480 curRes = aTest[1]; # tdTestResult
1481 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
1482 reporter.log('Testing #%d, user="%s", sPassword="%s", sDomain="%s" ...' \
1483 % (i, curTest.oCreds.sUser, curTest.oCreds.sPassword, curTest.oCreds.sDomain));
1484 curGuestSessionName = 'testGuestCtrlSession: Test #%d' % (i);
1485 fRc2, curGuestSession = curTest.createSession(curGuestSessionName);
1486 # See note about < 4.3 Guest Additions above.
1487 if curGuestSession is not None \
1488 and curGuestSession.protocolVersion >= 2 \
1489 and fRc2 is not curRes.fRc:
1490 reporter.error('Test #%d failed: Session creation failed: Got %s, expected %s' \
1491 % (i, fRc2, curRes.fRc));
1492 fRc = False;
1493 if fRc2:
1494 # On Guest Additions < 4.3 getSessionCount() always will return 1, so skip the
1495 # check then.
1496 if curGuestSession.protocolVersion >= 2:
1497 curSessionCount = curTest.getSessionCount(self.oTstDrv.oVBoxMgr);
1498 if curSessionCount is not curRes.cNumSessions:
1499 reporter.error('Test #%d failed: Session count does not match: Got %d, expected %d' \
1500 % (i, curSessionCount, curRes.cNumSessions));
1501 fRc = False;
1502 break;
1503 if curGuestSession is not None \
1504 and curGuestSession.name != curGuestSessionName:
1505 reporter.error('Test #%d failed: Session name does not match: Got "%s", expected "%s"' \
1506 % (i, curGuestSession.name, curGuestSessionName));
1507 fRc = False;
1508 break;
1509 fRc2 = curTest.closeSession();
1510 if fRc2 is False:
1511 reporter.error('Test #%d failed: Session could not be closed' % (i,));
1512 fRc = False;
1513 break;
1514
1515 if fRc is False:
1516 return (False, oTxsSession);
1517
1518 # Multiple sessions.
1519 iMaxGuestSessions = 31; # Maximum number of concurrent guest session allowed.
1520 # Actually, this is 32, but we don't test session 0.
1521 multiSession = {};
1522 reporter.log2('Opening multiple guest tsessions at once ...');
1523 for i in range(iMaxGuestSessions + 1):
1524 multiSession[i] = tdTestSession(sUser = sUser, sPassword = sPassword, sSessionName = 'MultiSession #%d' % (i,));
1525 multiSession[i].setEnvironment(oSession, oTxsSession, oTestVm);
1526 curSessionCount = multiSession[i].getSessionCount(self.oTstDrv.oVBoxMgr);
1527 reporter.log2('MultiSession test #%d count is %d' % (i, curSessionCount));
1528 if curSessionCount is not i:
1529 reporter.error('MultiSession count #%d must be %d, got %d' % (i, i, curSessionCount));
1530 fRc = False;
1531 break;
1532 fRc2, _ = multiSession[i].createSession('MultiSession #%d' % (i,));
1533 if fRc2 is not True:
1534 if i < iMaxGuestSessions:
1535 reporter.error('MultiSession #%d test failed' % (i,));
1536 fRc = False;
1537 else:
1538 reporter.log('MultiSession #%d exceeded concurrent guest session count, good' % (i,));
1539 break;
1540
1541 curSessionCount = multiSession[i].getSessionCount(self.oTstDrv.oVBoxMgr);
1542 if curSessionCount is not iMaxGuestSessions:
1543 reporter.error('Final MultiSession count must be %d, got %d'
1544 % (iMaxGuestSessions, curSessionCount));
1545 return (False, oTxsSession);
1546
1547 reporter.log2('Closing MultiSessions ...');
1548 iLastSession = iMaxGuestSessions - 1;
1549 for i in range(iLastSession): # Close all but the last opened session.
1550 fRc2 = multiSession[i].closeSession();
1551 reporter.log2('MultiSession #%d count is %d' % (i, multiSession[i].getSessionCount(self.oTstDrv.oVBoxMgr),));
1552 if fRc2 is False:
1553 reporter.error('Closing MultiSession #%d failed' % (i,));
1554 fRc = False;
1555 break;
1556 curSessionCount = multiSession[i].getSessionCount(self.oTstDrv.oVBoxMgr);
1557 if curSessionCount is not 1:
1558 reporter.error('Final MultiSession count #2 must be 1, got %d' % (curSessionCount,));
1559 fRc = False;
1560
1561 try:
1562 # r=bird: multiSession[0].oGuestSession is None! Why don't you just use 'assert' or 'if' to check
1563 # the functioning of the __testcase__?
1564
1565 # Make sure that accessing the first opened guest session does not work anymore because we just removed (closed) it.
1566 curSessionName = multiSession[0].oGuestSession.name;
1567 reporter.error('Accessing first removed MultiSession should not be possible, got name="%s"' % (curSessionName,));
1568 fRc = False;
1569 except:
1570 reporter.logXcpt('Could not access first removed MultiSession object, good:');
1571
1572 try:
1573 # Try Accessing last opened session which did not get removed yet.
1574 curSessionName = multiSession[iLastSession].oGuestSession.name;
1575 reporter.log('Accessing last standing MultiSession worked, got name="%s"' % (curSessionName,));
1576 multiSession[iLastSession].closeSession();
1577 curSessionCount = multiSession[i].getSessionCount(self.oTstDrv.oVBoxMgr);
1578 if curSessionCount is not 0:
1579 reporter.error('Final MultiSession count #3 must be 0, got %d' % (curSessionCount,));
1580 fRc = False;
1581 except:
1582 reporter.logXcpt('Could not access last standing MultiSession object:');
1583 fRc = False;
1584
1585 ## @todo Test session timeouts.
1586
1587 return (fRc, oTxsSession);
1588
1589 def testGuestCtrlSessionFileRefs(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
1590 """
1591 Tests the guest session file reference handling.
1592 """
1593
1594 if oTestVm.isWindows():
1595 sUser = "Administrator";
1596 sPassword = "password";
1597 sDomain = "";
1598 sFile = "C:\\windows\\system32\\kernel32.dll";
1599
1600 # Number of stale guest files to create.
1601 cStaleFiles = 10;
1602
1603 fRc = True;
1604 try:
1605 oGuest = oSession.o.console.guest;
1606 oGuestSession = oGuest.createSession(sUser, sPassword, sDomain, \
1607 "testGuestCtrlSessionFileRefs");
1608 fWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
1609 waitResult = oGuestSession.waitForArray(fWaitFor, 30 * 1000);
1610 #
1611 # Be nice to Guest Additions < 4.3: They don't support session handling and
1612 # therefore return WaitFlagNotSupported.
1613 #
1614 if waitResult != vboxcon.GuestSessionWaitResult_Start \
1615 and waitResult != vboxcon.GuestSessionWaitResult_WaitFlagNotSupported:
1616 # Just log, don't assume an error here (will be done in the main loop then).
1617 reporter.log('Session did not start successfully, returned wait result: %d' \
1618 % (waitResult));
1619 return (False, oTxsSession);
1620 reporter.log('Session successfully started');
1621
1622 #
1623 # Open guest files and "forget" them (stale entries).
1624 # For them we don't have any references anymore intentionally.
1625 #
1626 reporter.log2('Opening stale files');
1627 for i in range(0, cStaleFiles):
1628 try:
1629 if self.oTstDrv.fpApiVer >= 5.0:
1630 oGuestSession.fileOpen(sFile, vboxcon.FileAccessMode_ReadOnly, vboxcon.FileOpenAction_OpenExisting, 0);
1631 else:
1632 oGuestSession.fileOpen(sFile, "r", "oe", 0);
1633 # Note: Use a timeout in the call above for not letting the stale processes
1634 # hanging around forever. This can happen if the installed Guest Additions
1635 # do not support terminating guest processes.
1636 except:
1637 reporter.errorXcpt('Opening stale file #%d failed:' % (i,));
1638 fRc = False;
1639 break;
1640
1641 if fRc:
1642 cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
1643 if cFiles != cStaleFiles:
1644 reporter.error('Test failed: Got %d stale files, expected %d' % (cFiles, cStaleFiles));
1645 fRc = False;
1646
1647 if fRc:
1648 #
1649 # Open non-stale files and close them again.
1650 #
1651 reporter.log2('Opening non-stale files');
1652 aaFiles = [];
1653 for i in range(0, cStaleFiles):
1654 try:
1655 if self.oTstDrv.fpApiVer >= 5.0:
1656 oCurFile = oGuestSession.fileOpen(sFile, vboxcon.FileAccessMode_ReadOnly,
1657 vboxcon.FileOpenAction_OpenExisting, 0);
1658 else:
1659 oCurFile = oGuestSession.fileOpen(sFile, "r", "oe", 0);
1660 aaFiles.append(oCurFile);
1661 except:
1662 reporter.errorXcpt('Opening non-stale file #%d failed:' % (i,));
1663 fRc = False;
1664 break;
1665 if fRc:
1666 cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
1667 if cFiles != cStaleFiles * 2:
1668 reporter.error('Test failed: Got %d total files, expected %d' % (cFiles, cStaleFiles * 2));
1669 fRc = False;
1670 if fRc:
1671 reporter.log2('Closing all non-stale files again ...');
1672 for i in range(0, cStaleFiles):
1673 try:
1674 aaFiles[i].close();
1675 except:
1676 reporter.errorXcpt('Waiting for non-stale file #%d failed:' % (i,));
1677 fRc = False;
1678 break;
1679 cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
1680 # Here we count the stale files (that is, files we don't have a reference
1681 # anymore for) and the opened and then closed non-stale files (that we still keep
1682 # a reference in aaFiles[] for).
1683 if cFiles != cStaleFiles:
1684 reporter.error('Test failed: Got %d total files, expected %d' \
1685 % (cFiles, cStaleFiles));
1686 fRc = False;
1687 if fRc:
1688 #
1689 # Check if all (referenced) non-stale files now are in "closed" state.
1690 #
1691 reporter.log2('Checking statuses of all non-stale files ...');
1692 for i in range(0, cStaleFiles):
1693 try:
1694 curFilesStatus = aaFiles[i].status;
1695 if curFilesStatus != vboxcon.FileStatus_Closed:
1696 reporter.error('Test failed: Non-stale file #%d has status %d, expected %d' \
1697 % (i, curFilesStatus, vboxcon.FileStatus_Closed));
1698 fRc = False;
1699 except:
1700 reporter.errorXcpt('Checking status of file #%d failed:' % (i,));
1701 fRc = False;
1702 break;
1703 if fRc:
1704 reporter.log2('All non-stale files closed');
1705 cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
1706 reporter.log2('Final guest session file count: %d' % (cFiles,));
1707 # Now try to close the session and see what happens.
1708 reporter.log2('Closing guest session ...');
1709 oGuestSession.close();
1710 except:
1711 reporter.errorXcpt('Testing for stale processes failed:');
1712 fRc = False;
1713
1714 return (fRc, oTxsSession);
1715
1716 #def testGuestCtrlSessionDirRefs(self, oSession, oTxsSession, oTestVm):
1717 # """
1718 # Tests the guest session directory reference handling.
1719 # """
1720
1721 # fRc = True;
1722 # return (fRc, oTxsSession);
1723
1724 def testGuestCtrlSessionProcRefs(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
1725 """
1726 Tests the guest session process reference handling.
1727 """
1728
1729 if oTestVm.isWindows():
1730 sUser = "Administrator";
1731 sPassword = "password";
1732 sDomain = "";
1733 sCmd = "C:\\windows\\system32\\cmd.exe";
1734 aArgs = [sCmd,];
1735
1736 # Number of stale guest processes to create.
1737 cStaleProcs = 10;
1738
1739 fRc = True;
1740 try:
1741 oGuest = oSession.o.console.guest;
1742 oGuestSession = oGuest.createSession(sUser, sPassword, sDomain, \
1743 "testGuestCtrlSessionProcRefs");
1744 fWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
1745 waitResult = oGuestSession.waitForArray(fWaitFor, 30 * 1000);
1746 #
1747 # Be nice to Guest Additions < 4.3: They don't support session handling and
1748 # therefore return WaitFlagNotSupported.
1749 #
1750 if waitResult != vboxcon.GuestSessionWaitResult_Start \
1751 and waitResult != vboxcon.GuestSessionWaitResult_WaitFlagNotSupported:
1752 # Just log, don't assume an error here (will be done in the main loop then).
1753 reporter.log('Session did not start successfully, returned wait result: %d' \
1754 % (waitResult));
1755 return (False, oTxsSession);
1756 reporter.log('Session successfully started');
1757
1758 #
1759 # Fire off forever-running processes and "forget" them (stale entries).
1760 # For them we don't have any references anymore intentionally.
1761 #
1762 reporter.log2('Starting stale processes');
1763 for i in range(0, cStaleProcs):
1764 try:
1765 oGuestSession.processCreate(sCmd,
1766 aArgs if self.oTstDrv.fpApiVer >= 5.0 else aArgs[1:], [],
1767 [ vboxcon.ProcessCreateFlag_WaitForStdOut ], \
1768 30 * 1000);
1769 # Note: Use a timeout in the call above for not letting the stale processes
1770 # hanging around forever. This can happen if the installed Guest Additions
1771 # do not support terminating guest processes.
1772 except:
1773 reporter.logXcpt('Creating stale process #%d failed:' % (i,));
1774 fRc = False;
1775 break;
1776
1777 if fRc:
1778 cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
1779 if cProcs != cStaleProcs:
1780 reporter.error('Test failed: Got %d stale processes, expected %d' % (cProcs, cStaleProcs));
1781 fRc = False;
1782
1783 if fRc:
1784 #
1785 # Fire off non-stale processes and wait for termination.
1786 #
1787 if oTestVm.isWindows():
1788 aArgs = [ sCmd, '/C', 'dir', '/S', 'C:\\Windows\\system'];
1789 reporter.log2('Starting non-stale processes');
1790 aaProcs = [];
1791 for i in range(0, cStaleProcs):
1792 try:
1793 oCurProc = oGuestSession.processCreate(sCmd, aArgs if self.oTstDrv.fpApiVer >= 5.0 else aArgs[1:],
1794 [], [], 0); # Infinite timeout.
1795 aaProcs.append(oCurProc);
1796 except:
1797 reporter.logXcpt('Creating non-stale process #%d failed:' % (i,));
1798 fRc = False;
1799 break;
1800 if fRc:
1801 reporter.log2('Waiting for non-stale processes to terminate');
1802 for i in range(0, cStaleProcs):
1803 try:
1804 aaProcs[i].waitForArray([ vboxcon.ProcessWaitForFlag_Terminate ], 30 * 1000);
1805 curProcStatus = aaProcs[i].status;
1806 if aaProcs[i].status != vboxcon.ProcessStatus_TerminatedNormally:
1807 reporter.error('Test failed: Waiting for non-stale processes #%d'
1808 ' resulted in status %d, expected %d' \
1809 % (i, curProcStatus, vboxcon.ProcessStatus_TerminatedNormally));
1810 fRc = False;
1811 except:
1812 reporter.logXcpt('Waiting for non-stale process #%d failed:' % (i,));
1813 fRc = False;
1814 break;
1815 cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
1816 # Here we count the stale processes (that is, processes we don't have a reference
1817 # anymore for) and the started + terminated non-stale processes (that we still keep
1818 # a reference in aaProcs[] for).
1819 if cProcs != (cStaleProcs * 2):
1820 reporter.error('Test failed: Got %d total processes, expected %d' \
1821 % (cProcs, cStaleProcs));
1822 fRc = False;
1823 if fRc:
1824 #
1825 # Check if all (referenced) non-stale processes now are in "terminated" state.
1826 #
1827 for i in range(0, cStaleProcs):
1828 curProcStatus = aaProcs[i].status;
1829 if aaProcs[i].status != vboxcon.ProcessStatus_TerminatedNormally:
1830 reporter.error('Test failed: Non-stale processes #%d has status %d, expected %d' \
1831 % (i, curProcStatus, vboxcon.ProcessStatus_TerminatedNormally));
1832 fRc = False;
1833 if fRc:
1834 reporter.log2('All non-stale processes terminated');
1835
1836 # Fire off blocking processes which are terminated via terminate().
1837 if oTestVm.isWindows():
1838 aArgs = [ sCmd, '/C', 'dir', '/S', 'C:\\Windows'];
1839 reporter.log2('Starting blocking processes');
1840 aaProcs = [];
1841 for i in range(0, cStaleProcs):
1842 try:
1843 oCurProc = oGuestSession.processCreate(sCmd, aArgs if self.oTstDrv.fpApiVer >= 5.0 else aArgs[1:],
1844 [], [], 30 * 1000);
1845 # Note: Use a timeout in the call above for not letting the stale processes
1846 # hanging around forever. This can happen if the installed Guest Additions
1847 # do not support terminating guest processes.
1848 aaProcs.append(oCurProc);
1849 except:
1850 reporter.logXcpt('Creating blocking process failed:');
1851 fRc = False;
1852 break;
1853 if fRc:
1854 reporter.log2('Terminating blocking processes');
1855 for i in range(0, cStaleProcs):
1856 try:
1857 aaProcs[i].terminate();
1858 except: # Termination might not be supported, just skip and log it.
1859 reporter.logXcpt('Termination of blocking process failed, skipped:');
1860 cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
1861 if cProcs != (cStaleProcs * 2): # Still should be 20 processes because we terminated the 10 newest ones.
1862 reporter.error('Test failed: Got %d total processes, expected %d' % (cProcs, cStaleProcs * 2));
1863 fRc = False;
1864 cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
1865 reporter.log2('Final guest session processes count: %d' % (cProcs,));
1866 # Now try to close the session and see what happens.
1867 reporter.log2('Closing guest session ...');
1868 oGuestSession.close();
1869 except:
1870 reporter.logXcpt('Testing for stale processes failed:');
1871 fRc = False;
1872
1873 return (fRc, oTxsSession);
1874
1875 def testGuestCtrlExec(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914,R0915
1876 """
1877 Tests the basic execution feature.
1878 """
1879
1880 if oTestVm.isWindows():
1881 sUser = "Administrator";
1882 else:
1883 sUser = "vbox";
1884 sPassword = "password";
1885
1886 if oTestVm.isWindows():
1887 # Outputting stuff.
1888 sImageOut = "C:\\windows\\system32\\cmd.exe";
1889 else:
1890 reporter.error('Implement me!'); ## @todo Implement non-Windows bits.
1891 return (False, oTxsSession);
1892
1893 aaInvalid = [
1894 # Invalid parameters.
1895 [ tdTestExec(sUser = sUser, sPassword = sPassword),
1896 tdTestResultExec(fRc = False) ],
1897 # Non-existent / invalid image.
1898 [ tdTestExec(sCmd = "non-existent", sUser = sUser, sPassword = sPassword),
1899 tdTestResultExec(fRc = False) ],
1900 [ tdTestExec(sCmd = "non-existent2", sUser = sUser, sPassword = sPassword, fWaitForExit = True),
1901 tdTestResultExec(fRc = False) ],
1902 # Use an invalid format string.
1903 [ tdTestExec(sCmd = "%$%%%&", sUser = sUser, sPassword = sPassword),
1904 tdTestResultExec(fRc = False) ],
1905 # More stuff.
1906 [ tdTestExec(sCmd = "ƒ‰‹ˆ÷‹¸", sUser = sUser, sPassword = sPassword),
1907 tdTestResultExec(fRc = False) ],
1908 [ tdTestExec(sCmd = "???://!!!", sUser = sUser, sPassword = sPassword),
1909 tdTestResultExec(fRc = False) ],
1910 [ tdTestExec(sCmd = "<>!\\", sUser = sUser, sPassword = sPassword),
1911 tdTestResultExec(fRc = False) ]
1912 # Enable as soon as ERROR_BAD_DEVICE is implemented.
1913 #[ tdTestExec(sCmd = "CON", sUser = sUser, sPassword = sPassword),
1914 # tdTestResultExec(fRc = False) ]
1915 ];
1916
1917 if oTestVm.isWindows():
1918 sVBoxControl = "C:\\Program Files\\Oracle\\VirtualBox Guest Additions\\VBoxControl.exe";
1919 aaExec = [
1920 # Basic executon.
1921 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'c:\\windows\\system32' ],
1922 sUser = sUser, sPassword = sPassword),
1923 tdTestResultExec(fRc = True) ],
1924 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'c:\\windows\\system32\\kernel32.dll' ],
1925 sUser = sUser, sPassword = sPassword),
1926 tdTestResultExec(fRc = True) ],
1927 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'c:\\windows\\system32\\nonexist.dll' ],
1928 sUser = sUser, sPassword = sPassword),
1929 tdTestResultExec(fRc = True, iExitCode = 1) ],
1930 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', '/wrongparam' ],
1931 sUser = sUser, sPassword = sPassword),
1932 tdTestResultExec(fRc = True, iExitCode = 1) ],
1933 # Paths with spaces.
1934 ## @todo Get path of installed Guest Additions. Later.
1935 [ tdTestExec(sCmd = sVBoxControl, aArgs = [ sVBoxControl, 'version' ],
1936 sUser = sUser, sPassword = sPassword),
1937 tdTestResultExec(fRc = True) ],
1938 # StdOut.
1939 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'c:\\windows\\system32' ],
1940 sUser = sUser, sPassword = sPassword),
1941 tdTestResultExec(fRc = True) ],
1942 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'stdout-non-existing' ],
1943 sUser = sUser, sPassword = sPassword),
1944 tdTestResultExec(fRc = True, iExitCode = 1) ],
1945 # StdErr.
1946 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'c:\\windows\\system32' ],
1947 sUser = sUser, sPassword = sPassword),
1948 tdTestResultExec(fRc = True) ],
1949 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'stderr-non-existing' ],
1950 sUser = sUser, sPassword = sPassword),
1951 tdTestResultExec(fRc = True, iExitCode = 1) ],
1952 # StdOut + StdErr.
1953 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'c:\\windows\\system32' ],
1954 sUser = sUser, sPassword = sPassword),
1955 tdTestResultExec(fRc = True) ],
1956 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir', '/S', 'stdouterr-non-existing' ],
1957 sUser = sUser, sPassword = sPassword),
1958 tdTestResultExec(fRc = True, iExitCode = 1) ]
1959 # FIXME: Failing tests.
1960 # Environment variables.
1961 # [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'set', 'TEST_NONEXIST' ],
1962 # sUser = sUser, sPassword = sPassword),
1963 # tdTestResultExec(fRc = True, iExitCode = 1) ]
1964 # [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'set', 'windir' ],
1965 # sUser = sUser, sPassword = sPassword,
1966 # aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
1967 # tdTestResultExec(fRc = True, sBuf = 'windir=C:\\WINDOWS\r\n') ],
1968 # [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
1969 # sUser = sUser, sPassword = sPassword,
1970 # aEnv = [ 'TEST_FOO=BAR' ],
1971 # aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
1972 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ],
1973 # [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
1974 # sUser = sUser, sPassword = sPassword,
1975 # aEnv = [ 'TEST_FOO=BAR', 'TEST_BAZ=BAR' ],
1976 # aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
1977 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ]
1978
1979 ## @todo Create some files (or get files) we know the output size of to validate output length!
1980 ## @todo Add task which gets killed at some random time while letting the guest output something.
1981 ];
1982
1983 # Manual test, not executed automatically.
1984 aaManual = [
1985 [ tdTestExec(sCmd = sImageOut, aArgs = [ sImageOut, '/C', 'dir /S C:\\Windows' ],
1986 sUser = sUser, sPassword = sPassword,
1987 aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
1988 tdTestResultExec(fRc = True, cbStdOut = 497917) ] ];
1989 else:
1990 reporter.log('No OS-specific tests for non-Windows yet!');
1991
1992 # Build up the final test array for the first batch.
1993 aaTests = [];
1994 aaTests.extend(aaInvalid);
1995 if aaExec is not None:
1996 aaTests.extend(aaExec);
1997 fRc = True;
1998
1999 #
2000 # Single execution stuff. Nice for debugging.
2001 #
2002 fManual = False;
2003 if fManual:
2004 curTest = aaTests[1][0]; # tdTestExec, use an index, later.
2005 curRes = aaTests[1][1]; # tdTestResultExec
2006 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2007 fRc, curGuestSession = curTest.createSession('testGuestCtrlExec: Single test 1');
2008 if fRc is False:
2009 reporter.error('Single test failed: Could not create session');
2010 else:
2011 fRc = self.gctrlExecDoTest(0, curTest, curRes, curGuestSession);
2012 curTest.closeSession();
2013
2014 curTest = aaTests[2][0]; # tdTestExec, use an index, later.
2015 curRes = aaTests[2][1]; # tdTestResultExec
2016 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2017 fRc, curGuestSession = curTest.createSession('testGuestCtrlExec: Single test 2');
2018 if fRc is False:
2019 reporter.error('Single test failed: Could not create session');
2020 else:
2021 fRc = self.gctrlExecDoTest(0, curTest, curRes, curGuestSession);
2022 curTest.closeSession();
2023
2024 curTest = aaTests[3][0]; # tdTestExec, use an index, later.
2025 curRes = aaTests[3][1]; # tdTestResultExec
2026 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2027 fRc, curGuestSession = curTest.createSession('testGuestCtrlExec: Single test 3');
2028 if fRc is False:
2029 reporter.error('Single test failed: Could not create session');
2030 else:
2031 fRc = self.gctrlExecDoTest(0, curTest, curRes, curGuestSession);
2032 curTest.closeSession();
2033 return (fRc, oTxsSession);
2034 else:
2035 aaManual = aaManual; # Workaround for pylint #W0612.
2036
2037 if fRc is False:
2038 return (fRc, oTxsSession);
2039
2040 #
2041 # First batch: One session per guest process.
2042 #
2043 for (i, aTest) in enumerate(aaTests):
2044 curTest = aTest[0]; # tdTestExec, use an index, later.
2045 curRes = aTest[1]; # tdTestResultExec
2046 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2047 fRc, curGuestSession = curTest.createSession('testGuestCtrlExec: Test #%d' % (i,));
2048 if fRc is False:
2049 reporter.error('Test #%d failed: Could not create session' % (i,));
2050 break;
2051 fRc = self.gctrlExecDoTest(i, curTest, curRes, curGuestSession);
2052 if fRc is False:
2053 break;
2054 fRc = curTest.closeSession();
2055 if fRc is False:
2056 break;
2057
2058 # No sessions left?
2059 if fRc is True:
2060 cSessions = len(self.oTstDrv.oVBoxMgr.getArray(oSession.o.console.guest, 'sessions'));
2061 if cSessions is not 0:
2062 reporter.error('Found %d stale session(s), expected 0' % (cSessions,));
2063 fRc = False;
2064
2065 if fRc is False:
2066 return (fRc, oTxsSession);
2067
2068 reporter.log('Now using one guest session for all tests ...');
2069
2070 #
2071 # Second batch: One session for *all* guest processes.
2072 #
2073 oGuest = oSession.o.console.guest;
2074 try:
2075 reporter.log('Creating session for all tests ...');
2076 curGuestSession = oGuest.createSession(sUser, sPassword, '', 'testGuestCtrlExec: One session for all tests');
2077 try:
2078 fWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
2079 waitResult = curGuestSession.waitForArray(fWaitFor, 30 * 1000);
2080 if waitResult != vboxcon.GuestSessionWaitResult_Start \
2081 and waitResult != vboxcon.GuestSessionWaitResult_WaitFlagNotSupported:
2082 reporter.error('Session did not start successfully, returned wait result: %d' \
2083 % (waitResult));
2084 return (False, oTxsSession);
2085 reporter.log('Session successfully started');
2086 except:
2087 # Just log, don't assume an error here (will be done in the main loop then).
2088 reporter.logXcpt('Waiting for guest session to start failed:');
2089 return (False, oTxsSession);
2090 # Note: Not waiting for the guest session to start here
2091 # is intentional. This must be handled by the process execution
2092 # call then.
2093 for (i, aTest) in enumerate(aaTests):
2094 curTest = aTest[0]; # tdTestExec, use an index, later.
2095 curRes = aTest[1]; # tdTestResultExec
2096 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2097 fRc = self.gctrlExecDoTest(i, curTest, curRes, curGuestSession);
2098 if fRc is False:
2099 break;
2100 try:
2101 reporter.log2('Closing guest session ...');
2102 curGuestSession.close();
2103 curGuestSession = None;
2104 except:
2105 # Just log, don't assume an error here (will be done in the main loop then).
2106 reporter.logXcpt('Closing guest session failed:');
2107 fRc = False;
2108 except:
2109 reporter.logXcpt('Could not create one session:');
2110
2111 # No sessions left?
2112 if fRc is True:
2113 cSessions = len(self.oTstDrv.oVBoxMgr.getArray(oSession.o.console.guest, 'sessions'));
2114 if cSessions is not 0:
2115 reporter.error('Found %d stale session(s), expected 0' % (cSessions,));
2116 fRc = False;
2117
2118 return (fRc, oTxsSession);
2119
2120 def testGuestCtrlExecErrorLevel(self, oSession, oTxsSession, oTestVm):
2121 """
2122 Tests handling of error levels from started guest processes.
2123 """
2124
2125 if oTestVm.isWindows():
2126 sUser = "Administrator";
2127 else:
2128 sUser = "vbox";
2129 sPassword = "password";
2130
2131 if oTestVm.isWindows():
2132 # Outputting stuff.
2133 sImage = "C:\\windows\\system32\\cmd.exe";
2134 else:
2135 reporter.error('Implement me!'); ## @todo Implement non-Windows bits.
2136 return (False, oTxsSession);
2137
2138 aaTests = [];
2139 if oTestVm.isWindows():
2140 aaTests.extend([
2141 # Simple.
2142 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'wrongcommand' ],
2143 sUser = sUser, sPassword = sPassword),
2144 tdTestResultExec(fRc = True, iExitCode = 1) ],
2145 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'exit', '22' ],
2146 sUser = sUser, sPassword = sPassword),
2147 tdTestResultExec(fRc = True, iExitCode = 22) ],
2148 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'set', 'ERRORLEVEL=234' ],
2149 sUser = sUser, sPassword = sPassword),
2150 tdTestResultExec(fRc = True, iExitCode = 0) ],
2151 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'echo', '%WINDIR%' ],
2152 sUser = sUser, sPassword = sPassword),
2153 tdTestResultExec(fRc = True, iExitCode = 0) ],
2154 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'set', 'ERRORLEVEL=0' ],
2155 sUser = sUser, sPassword = sPassword),
2156 tdTestResultExec(fRc = True, iExitCode = 0) ],
2157 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\windows\\system32' ],
2158 sUser = sUser, sPassword = sPassword),
2159 tdTestResultExec(fRc = True, iExitCode = 0) ],
2160 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\windows\\system32\\kernel32.dll' ],
2161 sUser = sUser, sPassword = sPassword),
2162 tdTestResultExec(fRc = True, iExitCode = 0) ],
2163 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-file' ],
2164 sUser = sUser, sPassword = sPassword),
2165 tdTestResultExec(fRc = True, iExitCode = 1) ],
2166 [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-dir\\' ],
2167 sUser = sUser, sPassword = sPassword),
2168 tdTestResultExec(fRc = True, iExitCode = 1) ]
2169 # FIXME: Failing tests.
2170 # With stdout.
2171 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\windows\\system32' ],
2172 # sUser = sUser, sPassword = sPassword, aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut ]),
2173 # tdTestResultExec(fRc = True, iExitCode = 0) ],
2174 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-file' ],
2175 # sUser = sUser, sPassword = sPassword, aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut ]),
2176 # tdTestResultExec(fRc = True, iExitCode = 1) ],
2177 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-dir\\' ],
2178 # sUser = sUser, sPassword = sPassword, aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut ]),
2179 # tdTestResultExec(fRc = True, iExitCode = 1) ],
2180 # With stderr.
2181 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\windows\\system32' ],
2182 # sUser = sUser, sPassword = sPassword, aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2183 # tdTestResultExec(fRc = True, iExitCode = 0) ],
2184 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-file' ],
2185 # sUser = sUser, sPassword = sPassword, aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2186 # tdTestResultExec(fRc = True, iExitCode = 1) ],
2187 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-dir\\' ],
2188 # sUser = sUser, sPassword = sPassword, aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2189 # tdTestResultExec(fRc = True, iExitCode = 1) ],
2190 # With stdout/stderr.
2191 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\windows\\system32' ],
2192 # sUser = sUser, sPassword = sPassword,
2193 # aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2194 # tdTestResultExec(fRc = True, iExitCode = 0) ],
2195 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-file' ],
2196 # sUser = sUser, sPassword = sPassword,
2197 # aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2198 # tdTestResultExec(fRc = True, iExitCode = 1) ],
2199 # [ tdTestExec(sCmd = sImage, aArgs = [ sImage, '/C', 'dir', 'c:\\nonexisting-dir\\' ],
2200 # sUser = sUser, sPassword = sPassword,
2201 # aFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2202 # tdTestResultExec(fRc = True, iExitCode = 1) ]
2203 ## @todo Test stdin!
2204 ]);
2205 else:
2206 reporter.log('No OS-specific tests for non-Windows yet!');
2207
2208 fRc = True;
2209 for (i, aTest) in enumerate(aaTests):
2210 curTest = aTest[0]; # tdTestExec, use an index, later.
2211 curRes = aTest[1]; # tdTestResult
2212 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2213 fRc, curGuestSession = curTest.createSession('testGuestCtrlExecErrorLevel: Test #%d' % (i,));
2214 if fRc is False:
2215 reporter.error('Test #%d failed: Could not create session' % (i,));
2216 break;
2217 fRc = self.gctrlExecDoTest(i, curTest, curRes, curGuestSession);
2218 curTest.closeSession();
2219 if fRc is False:
2220 break;
2221
2222 return (fRc, oTxsSession);
2223
2224 def testGuestCtrlExecTimeout(self, oSession, oTxsSession, oTestVm):
2225 """
2226 Tests handling of timeouts of started guest processes.
2227 """
2228
2229 if oTestVm.isWindows():
2230 sUser = "Administrator";
2231 else:
2232 sUser = "vbox";
2233 sPassword = "password";
2234 sDomain = "";
2235
2236 if oTestVm.isWindows():
2237 # Outputting stuff.
2238 sImage = "C:\\windows\\system32\\cmd.exe";
2239 else:
2240 reporter.error('Implement me!'); ## @todo Implement non-Windows bits.
2241 return (False, oTxsSession);
2242
2243 fRc = True;
2244 try:
2245 oGuest = oSession.o.console.guest;
2246 oGuestSession = oGuest.createSession(sUser, sPassword, sDomain, "testGuestCtrlExecTimeout");
2247 oGuestSession.waitForArray([ vboxcon.GuestSessionWaitForFlag_Start ], 30 * 1000);
2248 # Create a process which never terminates and should timeout when
2249 # waiting for termination.
2250 try:
2251 curProc = oGuestSession.processCreate(sImage, [sImage,] if self.oTstDrv.fpApiVer >= 5.0 else [], \
2252 [], [], 30 * 1000);
2253 reporter.log('Waiting for process 1 being started ...');
2254 waitRes = curProc.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
2255 if waitRes != vboxcon.ProcessWaitResult_Start:
2256 reporter.error('Waiting for process 1 to start failed, got status %d');
2257 fRc = False;
2258 if fRc:
2259 reporter.log('Waiting for process 1 to time out within 1ms ...');
2260 waitRes = curProc.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate ], 1);
2261 if waitRes != vboxcon.ProcessWaitResult_Timeout:
2262 reporter.error('Waiting for process 1 did not time out when it should (1)');
2263 fRc = False;
2264 else:
2265 reporter.log('Waiting for process 1 timed out (1), good');
2266 if fRc:
2267 reporter.log('Waiting for process 1 to time out within 5000ms ...');
2268 waitRes = curProc.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate ], 5000);
2269 if waitRes != vboxcon.ProcessWaitResult_Timeout:
2270 reporter.error('Waiting for process 1 did not time out when it should, got wait result %d' % (waitRes,));
2271 fRc = False;
2272 else:
2273 reporter.log('Waiting for process 1 timed out (5000), good');
2274 ## @todo Add curProc.terminate() as soon as it's implemented.
2275 except:
2276 reporter.errorXcpt('Exception for process 1:');
2277 fRc = False;
2278 # Create a lengthly running guest process which will be killed by VBoxService on the
2279 # guest because it ran out of execution time (5 seconds).
2280 if fRc:
2281 try:
2282 curProc = oGuestSession.processCreate(sImage, [sImage,] if self.oTstDrv.fpApiVer >= 5.0 else [], \
2283 [], [], 5 * 1000);
2284 reporter.log('Waiting for process 2 being started ...');
2285 waitRes = curProc.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
2286 if waitRes != vboxcon.ProcessWaitResult_Start:
2287 reporter.error('Waiting for process 1 to start failed, got status %d');
2288 fRc = False;
2289 if fRc:
2290 reporter.log('Waiting for process 2 to get killed because it ran out of execution time ...');
2291 waitRes = curProc.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate ], 30 * 1000);
2292 if waitRes != vboxcon.ProcessWaitResult_Timeout:
2293 reporter.error('Waiting for process 2 did not time out when it should, got wait result %d' \
2294 % (waitRes,));
2295 fRc = False;
2296 if fRc:
2297 reporter.log('Waiting for process 2 indicated an error, good');
2298 if curProc.status != vboxcon.ProcessStatus_TimedOutKilled:
2299 reporter.error('Status of process 2 wrong; excepted %d, got %d' \
2300 % (vboxcon.ProcessStatus_TimedOutKilled, curProc.status));
2301 fRc = False;
2302 else:
2303 reporter.log('Status of process 2 correct (%d)' % (vboxcon.ProcessStatus_TimedOutKilled,));
2304 ## @todo Add curProc.terminate() as soon as it's implemented.
2305 except:
2306 reporter.errorXcpt('Exception for process 2:');
2307 fRc = False;
2308 oGuestSession.close();
2309 except:
2310 reporter.errorXcpt('Could not handle session:');
2311 fRc = False;
2312
2313 return (fRc, oTxsSession);
2314
2315 def testGuestCtrlDirCreate(self, oSession, oTxsSession, oTestVm):
2316 """
2317 Tests creation of guest directories.
2318 """
2319
2320 if oTestVm.isWindows():
2321 sUser = "Administrator";
2322 else:
2323 sUser = "vbox";
2324 sPassword = "password";
2325
2326 if oTestVm.isWindows():
2327 sScratch = "C:\\Temp\\vboxtest\\testGuestCtrlDirCreate\\";
2328
2329 aaTests = [];
2330 if oTestVm.isWindows():
2331 aaTests.extend([
2332 # Invalid stuff.
2333 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = '' ),
2334 tdTestResult(fRc = False) ],
2335 # More unusual stuff.
2336 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = '..\\..\\' ),
2337 tdTestResult(fRc = False) ],
2338 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = '../../' ),
2339 tdTestResult(fRc = False) ],
2340 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = 'z:\\' ),
2341 tdTestResult(fRc = False) ],
2342 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = '\\\\uncrulez\\foo' ),
2343 tdTestResult(fRc = False) ],
2344 # Creating directories.
2345 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = sScratch ),
2346 tdTestResult(fRc = False) ],
2347 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = os.path.join(sScratch, 'foo\\bar\\baz'),
2348 aFlags = [ vboxcon.DirectoryCreateFlag_Parents ] ),
2349 tdTestResult(fRc = True) ],
2350 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword, sDirectory = os.path.join(sScratch, 'foo\\bar\\baz'),
2351 aFlags = [ vboxcon.DirectoryCreateFlag_Parents ] ),
2352 tdTestResult(fRc = True) ],
2353 # Long (+ random) stuff.
2354 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword,
2355 sDirectory = os.path.join(sScratch,
2356 "".join(random.choice(string.ascii_lowercase) for i in range(32))) ),
2357 tdTestResult(fRc = True) ],
2358 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword,
2359 sDirectory = os.path.join(sScratch,
2360 "".join(random.choice(string.ascii_lowercase) for i in range(128))) ),
2361 tdTestResult(fRc = True) ],
2362 # Following two should fail on Windows (paths too long). Both should timeout.
2363 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword,
2364 sDirectory = os.path.join(sScratch,
2365 "".join(random.choice(string.ascii_lowercase) for i in range(255))) ),
2366 tdTestResult(fRc = False) ],
2367 [ tdTestDirCreate(sUser = sUser, sPassword = sPassword,
2368 sDirectory = os.path.join(sScratch,
2369 "".join(random.choice(string.ascii_lowercase) for i in range(1024))) ),
2370 tdTestResult(fRc = False) ]
2371 ]);
2372 else:
2373 reporter.log('No OS-specific tests for non-Windows yet!');
2374
2375 fRc = True;
2376 for (i, aTest) in enumerate(aaTests):
2377 curTest = aTest[0]; # tdTestExec, use an index, later.
2378 curRes = aTest[1]; # tdTestResult
2379 reporter.log('Testing #%d, sDirectory="%s" ...' % (i, curTest.sDirectory));
2380 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2381 fRc, curGuestSession = curTest.createSession('testGuestCtrlDirCreate: Test #%d' % (i,));
2382 if fRc is False:
2383 reporter.error('Test #%d failed: Could not create session' % (i,));
2384 break;
2385 fRc = self.gctrlCreateDir(curTest, curRes, curGuestSession);
2386 curTest.closeSession();
2387 if fRc is False:
2388 reporter.error('Test #%d failed' % (i,));
2389 fRc = False;
2390 break;
2391
2392 return (fRc, oTxsSession);
2393
2394 def testGuestCtrlDirCreateTemp(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
2395 """
2396 Tests creation of temporary directories.
2397 """
2398
2399 if oTestVm.isWindows():
2400 sUser = "Administrator";
2401 else:
2402 sUser = "vbox";
2403 sPassword = "password";
2404
2405 # if oTestVm.isWindows():
2406 # sScratch = "C:\\Temp\\vboxtest\\testGuestCtrlDirCreateTemp\\";
2407
2408 aaTests = [];
2409 if oTestVm.isWindows():
2410 aaTests.extend([
2411 # Invalid stuff.
2412 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sDirectory = ''),
2413 tdTestResult(fRc = False) ],
2414 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sDirectory = 'C:\\Windows',
2415 fMode = 1234),
2416 tdTestResult(fRc = False) ],
2417 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = '',
2418 sDirectory = 'C:\\Windows', fMode = 1234),
2419 tdTestResult(fRc = False) ],
2420 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'xXx',
2421 sDirectory = 'C:\\Windows', fMode = 0700),
2422 tdTestResult(fRc = False) ],
2423 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'xxx',
2424 sDirectory = 'C:\\Windows', fMode = 0700),
2425 tdTestResult(fRc = False) ],
2426 # More unusual stuff.
2427 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'foo',
2428 sDirectory = 'z:\\'),
2429 tdTestResult(fRc = False) ],
2430 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'foo',
2431 sDirectory = '\\\\uncrulez\\foo'),
2432 tdTestResult(fRc = False) ],
2433 # Non-existing stuff.
2434 [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'bar',
2435 sDirectory = 'c:\\Apps\\nonexisting\\foo'),
2436 tdTestResult(fRc = False) ],
2437 # FIXME: Failing test. Non Windows path
2438 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'bar',
2439 # sDirectory = '/tmp/non/existing'),
2440 # tdTestResult(fRc = False) ]
2441 ]);
2442 else:
2443 reporter.log('No OS-specific tests for non-Windows yet!');
2444
2445 # FIXME: Failing tests.
2446 # aaTests.extend([
2447 # Non-secure variants.
2448 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2449 # sDirectory = sScratch),
2450 # tdTestResult(fRc = True) ],
2451 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2452 # sDirectory = sScratch),
2453 # tdTestResult(fRc = True) ],
2454 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'X',
2455 # sDirectory = sScratch),
2456 # tdTestResult(fRc = True) ],
2457 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'X',
2458 # sDirectory = sScratch),
2459 # tdTestResult(fRc = True) ],
2460 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2461 # sDirectory = sScratch,
2462 # fMode = 0700),
2463 # tdTestResult(fRc = True) ],
2464 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2465 # sDirectory = sScratch,
2466 # fMode = 0700),
2467 # tdTestResult(fRc = True) ],
2468 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2469 # sDirectory = sScratch,
2470 # fMode = 0755),
2471 # tdTestResult(fRc = True) ],
2472 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2473 # sDirectory = sScratch,
2474 # fMode = 0755),
2475 # tdTestResult(fRc = True) ],
2476 # Secure variants.
2477 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2478 # sDirectory = sScratch, fSecure = True),
2479 # tdTestResult(fRc = True) ],
2480 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2481 # sDirectory = sScratch, fSecure = True),
2482 # tdTestResult(fRc = True) ],
2483 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2484 # sDirectory = sScratch, fSecure = True),
2485 # tdTestResult(fRc = True) ],
2486 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2487 # sDirectory = sScratch, fSecure = True),
2488 # tdTestResult(fRc = True) ],
2489 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2490 # sDirectory = sScratch,
2491 # fSecure = True, fMode = 0700),
2492 # tdTestResult(fRc = True) ],
2493 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2494 # sDirectory = sScratch,
2495 # fSecure = True, fMode = 0700),
2496 # tdTestResult(fRc = True) ],
2497 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2498 # sDirectory = sScratch,
2499 # fSecure = True, fMode = 0755),
2500 # tdTestResult(fRc = True) ],
2501 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = 'XXX',
2502 # sDirectory = sScratch,
2503 # fSecure = True, fMode = 0755),
2504 # tdTestResult(fRc = True) ],
2505 # Random stuff.
2506 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword,
2507 # sTemplate = "XXX-".join(random.choice(string.ascii_lowercase) for i in range(32)),
2508 # sDirectory = sScratch,
2509 # fSecure = True, fMode = 0755),
2510 # tdTestResult(fRc = True) ],
2511 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = "".join('X' for i in range(32)),
2512 # sDirectory = sScratch,
2513 # fSecure = True, fMode = 0755),
2514 # tdTestResult(fRc = True) ],
2515 # [ tdTestDirCreateTemp(sUser = sUser, sPassword = sPassword, sTemplate = "".join('X' for i in range(128)),
2516 # sDirectory = sScratch,
2517 # fSecure = True, fMode = 0755),
2518 # tdTestResult(fRc = True) ]
2519 # ]);
2520
2521 fRc = True;
2522 for (i, aTest) in enumerate(aaTests):
2523 curTest = aTest[0]; # tdTestExec, use an index, later.
2524 curRes = aTest[1]; # tdTestResult
2525 reporter.log('Testing #%d, sTemplate="%s", fMode=%#o, path="%s", secure="%s" ...' %
2526 (i, curTest.sTemplate, curTest.fMode, curTest.sDirectory, curTest.fSecure));
2527 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2528 fRc, curGuestSession = curTest.createSession('testGuestCtrlDirCreateTemp: Test #%d' % (i,));
2529 if fRc is False:
2530 reporter.error('Test #%d failed: Could not create session' % (i,));
2531 break;
2532 sDirTemp = "";
2533 try:
2534 sDirTemp = curGuestSession.directoryCreateTemp(curTest.sTemplate, curTest.fMode,
2535 curTest.sDirectory, curTest.fSecure);
2536 except:
2537 if curRes.fRc is True:
2538 reporter.errorXcpt('Creating temp directory "%s" failed:' % (curTest.sDirectory,));
2539 fRc = False;
2540 break;
2541 else:
2542 reporter.logXcpt('Creating temp directory "%s" failed expectedly, skipping:' % (curTest.sDirectory,));
2543 curTest.closeSession();
2544 if sDirTemp != "":
2545 reporter.log2('Temporary directory is: %s' % (sDirTemp,));
2546 if self.oTstDrv.fpApiVer >= 5.0:
2547 fExists = curGuestSession.directoryExists(sDirTemp, False);
2548 else:
2549 fExists = curGuestSession.directoryExists(sDirTemp);
2550 if fExists is False:
2551 reporter.error('Test #%d failed: Temporary directory "%s" does not exists' % (i, sDirTemp));
2552 fRc = False;
2553 break;
2554 return (fRc, oTxsSession);
2555
2556 def testGuestCtrlDirRead(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
2557 """
2558 Tests opening and reading (enumerating) guest directories.
2559 """
2560
2561 if oTestVm.isWindows():
2562 sUser = "Administrator";
2563 else:
2564 sUser = "vbox";
2565 sPassword = "password";
2566
2567 aaTests = [];
2568 if oTestVm.isWindows():
2569 aaTests.extend([
2570 # Invalid stuff.
2571 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = ''),
2572 tdTestResultDirRead(fRc = False) ],
2573 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'C:\\Windows', aFlags = [ 1234 ]),
2574 tdTestResultDirRead(fRc = False) ],
2575 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'C:\\Windows', sFilter = '*.foo'),
2576 tdTestResultDirRead(fRc = False) ],
2577 # More unusual stuff.
2578 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'z:\\'),
2579 tdTestResultDirRead(fRc = False) ],
2580 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = '\\\\uncrulez\\foo'),
2581 tdTestResultDirRead(fRc = False) ],
2582 # Non-existing stuff.
2583 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'c:\\Apps\\nonexisting'),
2584 tdTestResultDirRead(fRc = False) ],
2585 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'c:\\Apps\\testDirRead'),
2586 tdTestResultDirRead(fRc = False) ]
2587 ]);
2588
2589 if oTestVm.sVmName == 'tst-xppro':
2590 aaTests.extend([
2591 # Reading directories.
2592 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = '../../Windows/Fonts'),
2593 tdTestResultDirRead(fRc = True, numFiles = 191) ],
2594 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'c:\\Windows\\Help'),
2595 tdTestResultDirRead(fRc = True, numDirs = 13, numFiles = 569) ],
2596 [ tdTestDirRead(sUser = sUser, sPassword = sPassword, sDirectory = 'c:\\Windows\\Web'),
2597 tdTestResultDirRead(fRc = True, numDirs = 3, numFiles = 55) ]
2598 ]);
2599 else:
2600 reporter.log('No OS-specific tests for non-Windows yet!');
2601
2602 fRc = True;
2603 for (i, aTest) in enumerate(aaTests):
2604 curTest = aTest[0]; # tdTestExec, use an index, later.
2605 curRes = aTest[1]; # tdTestResult
2606 reporter.log('Testing #%d, dir="%s" ...' % (i, curTest.sDirectory));
2607 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2608 fRc, curGuestSession = curTest.createSession('testGuestCtrlDirRead: Test #%d' % (i,));
2609 if fRc is False:
2610 reporter.error('Test #%d failed: Could not create session' % (i,));
2611 break;
2612 (fRc2, cDirs, cFiles) = self.gctrlReadDir(curTest, curRes, curGuestSession);
2613 curTest.closeSession();
2614 reporter.log2('Test #%d: Returned %d directories, %d files total' % (i, cDirs, cFiles));
2615 if fRc2 is curRes.fRc:
2616 if fRc2 is True:
2617 if curRes.numFiles != cFiles:
2618 reporter.error('Test #%d failed: Got %d files, expected %d' % (i, cFiles, curRes.numFiles));
2619 fRc = False;
2620 break;
2621 if curRes.numDirs != cDirs:
2622 reporter.error('Test #%d failed: Got %d directories, expected %d' % (i, cDirs, curRes.numDirs));
2623 fRc = False;
2624 break;
2625 else:
2626 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, curRes.fRc));
2627 fRc = False;
2628 break;
2629
2630 return (fRc, oTxsSession);
2631
2632 def testGuestCtrlFileRemove(self, oSession, oTxsSession, oTestVm):
2633 """
2634 Tests removing guest files.
2635 """
2636
2637 if oTestVm.isWindows():
2638 sUser = "Administrator";
2639 else:
2640 sUser = "vbox";
2641 sPassword = "password";
2642
2643 aaTests = [];
2644 if oTestVm.isWindows():
2645 aaTests.extend([
2646 # Invalid stuff.
2647 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = ''), tdTestResult(fRc = False) ],
2648 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows'), tdTestResult(fRc = False) ],
2649 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows'), tdTestResult(fRc = False) ],
2650 # More unusual stuff.
2651 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'z:\\'), tdTestResult(fRc = False) ],
2652 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = '\\\\uncrulez\\foo'),
2653 tdTestResult(fRc = False) ],
2654 # Non-existing stuff.
2655 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Apps\\nonexisting'),
2656 tdTestResult(fRc = False) ],
2657 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Apps\\testFileRemove'),
2658 tdTestResult(fRc = False) ],
2659 # Try to delete system files.
2660 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\pagefile.sys'),
2661 tdTestResult(fRc = False) ],
2662 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\kernel32.sys'),
2663 tdTestResult(fRc = False) ]
2664 ]);
2665
2666 if oTestVm.sVmName == 'tst-xppro':
2667 aaTests.extend([
2668 # Try delete some unimportant media stuff.
2669 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\Media\\chimes.wav'),
2670 tdTestResult(fRc = True) ],
2671 # Second attempt should fail.
2672 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\Media\\chimes.wav'),
2673 tdTestResult(fRc = False) ],
2674 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\Media\\chord.wav'),
2675 tdTestResult(fRc = True) ],
2676 [ tdTestFileRemove(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\Media\\chord.wav'),
2677 tdTestResult(fRc = False) ]
2678 ]);
2679 else:
2680 reporter.log('No OS-specific tests for non-Windows yet!');
2681
2682 fRc = True;
2683 for (i, aTest) in enumerate(aaTests):
2684 curTest = aTest[0]; # tdTestExec, use an index, later.
2685 curRes = aTest[1]; # tdTestResult
2686 reporter.log('Testing #%d, file="%s" ...' % (i, curTest.sFile));
2687 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2688 fRc, curGuestSession = curTest.createSession('testGuestCtrlFileRemove: Test #%d' % (i,));
2689 if fRc is False:
2690 reporter.error('Test #%d failed: Could not create session' % (i,));
2691 break;
2692 try:
2693 if self.oTstDrv.fpApiVer >= 5.0:
2694 curGuestSession.fsObjRemove(curTest.sFile);
2695 else:
2696 curGuestSession.fileRemove(curTest.sFile);
2697 except:
2698 if curRes.fRc is True:
2699 reporter.errorXcpt('Removing file "%s" failed:' % (curTest.sFile,));
2700 fRc = False;
2701 break;
2702 else:
2703 reporter.logXcpt('Removing file "%s" failed expectedly, skipping:' % (curTest.sFile,));
2704 curTest.closeSession();
2705 return (fRc, oTxsSession);
2706
2707 def testGuestCtrlFileStat(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
2708 """
2709 Tests querying file information through stat.
2710 """
2711
2712 if oTestVm.isWindows():
2713 sUser = "Administrator";
2714 else:
2715 sUser = "vbox";
2716 sPassword = "password";
2717
2718 aaTests = [];
2719 if oTestVm.isWindows():
2720 aaTests.extend([
2721 # Invalid stuff.
2722 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = ''),
2723 tdTestResultFileStat(fRc = False) ],
2724 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows'),
2725 tdTestResultFileStat(fRc = False) ],
2726 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows'),
2727 tdTestResultFileStat(fRc = False) ],
2728 # More unusual stuff.
2729 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'z:\\'),
2730 tdTestResultFileStat(fRc = False) ],
2731 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = '\\\\uncrulez\\foo'),
2732 tdTestResultFileStat(fRc = False) ],
2733 # Non-existing stuff.
2734 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Apps\\nonexisting'),
2735 tdTestResultFileStat(fRc = False) ],
2736 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Apps\\testDirRead'),
2737 tdTestResultFileStat(fRc = False) ]
2738 ]);
2739
2740 if oTestVm.sVmName == 'tst-xppro':
2741 aaTests.extend([
2742 # Directories; should fail.
2743 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = '../../Windows/Fonts'),
2744 tdTestResultFileStat(fRc = False) ],
2745 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\Help'),
2746 tdTestResultFileStat(fRc = False) ],
2747 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\system32'),
2748 tdTestResultFileStat(fRc = False) ],
2749 # Regular files.
2750 [ tdTestFileStat(sUser = sUser, sPassword = sPassword, sFile = 'c:\\Windows\\system32\\kernel32.dll'),
2751 tdTestResultFileStat(fRc = False, cbSize = 926720, eFileType = vboxcon.FsObjType_File) ]
2752 ]);
2753 else:
2754 reporter.log('No OS-specific tests for non-Windows yet!');
2755
2756 fRc = True;
2757 for (i, aTest) in enumerate(aaTests):
2758 curTest = aTest[0]; # tdTestExec, use an index, later.
2759 curRes = aTest[1]; # tdTestResult
2760 reporter.log('Testing #%d, sFile="%s" ...' % (i, curTest.sFile));
2761 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2762 fRc, curGuestSession = curTest.createSession('testGuestCtrlFileStat: Test #%d' % (i,));
2763 if fRc is False:
2764 reporter.error('Test #%d failed: Could not create session' % (i,));
2765 break;
2766 fileObjInfo = None;
2767 try:
2768 if self.oTstDrv.fpApiVer >= 5.0:
2769 fileObjInfo = curGuestSession.fsObjQueryInfo(curTest.sFile, True);
2770 else:
2771 fileObjInfo = curGuestSession.fileQueryInfo(curTest.sFile);
2772 except:
2773 if curRes.fRc is True:
2774 reporter.errorXcpt('Querying file information for "%s" failed:' % (curTest.sFile,));
2775 fRc = False;
2776 break;
2777 else:
2778 reporter.logXcpt('Querying file information for "%s" failed expectedly, skipping:' % (curTest.sFile,));
2779 curTest.closeSession();
2780 if fileObjInfo is not None:
2781 eFileType = fileObjInfo.type;
2782 if curRes.eFileType != eFileType:
2783 reporter.error('Test #%d failed: Got file type %d, expected %d' % (i, eFileType, curRes.eFileType));
2784 fRc = False;
2785 break;
2786 cbFile = long(fileObjInfo.objectSize);
2787 if curRes.cbSize != cbFile:
2788 reporter.error('Test #%d failed: Got %d bytes size, expected %d bytes' % (i, cbFile, curRes.cbSize));
2789 fRc = False;
2790 break;
2791 ## @todo Add more checks later.
2792
2793 return (fRc, oTxsSession);
2794
2795 def testGuestCtrlFileRead(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
2796 """
2797 Tests reading from guest files.
2798 """
2799
2800 if oTestVm.isWindows():
2801 sUser = "Administrator";
2802 else:
2803 sUser = "vbox";
2804 sPassword = "password";
2805
2806 if oTxsSession.syncMkDir('${SCRATCH}/testGuestCtrlFileRead') is False:
2807 reporter.error('Could not create scratch directory on guest');
2808 return (False, oTxsSession);
2809
2810 aaTests = [];
2811 aaTests.extend([
2812 # Invalid stuff.
2813 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, cbToReadWrite = 0),
2814 tdTestResultFileReadWrite(fRc = False) ],
2815 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = ''),
2816 tdTestResultFileReadWrite(fRc = False) ],
2817 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'non-existing.file'),
2818 tdTestResultFileReadWrite(fRc = False) ],
2819 # Wrong open mode.
2820 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'non-existing.file', \
2821 sOpenMode = 'rt', sDisposition = 'oe'),
2822 tdTestResultFileReadWrite(fRc = False) ],
2823 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = '\\\\uncrulez\\non-existing.file', \
2824 sOpenMode = 'tr', sDisposition = 'oe'),
2825 tdTestResultFileReadWrite(fRc = False) ],
2826 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = '../../non-existing.file', \
2827 sOpenMode = 'wr', sDisposition = 'oe'),
2828 tdTestResultFileReadWrite(fRc = False) ],
2829 # Wrong disposition.
2830 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'non-existing.file', \
2831 sOpenMode = 'r', sDisposition = 'e'),
2832 tdTestResultFileReadWrite(fRc = False) ],
2833 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = '\\\\uncrulez\\non-existing.file', \
2834 sOpenMode = 'r', sDisposition = 'o'),
2835 tdTestResultFileReadWrite(fRc = False) ],
2836 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = '../../non-existing.file', \
2837 sOpenMode = 'r', sDisposition = 'c'),
2838 tdTestResultFileReadWrite(fRc = False) ],
2839 # Opening non-existing file when it should exist.
2840 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'non-existing.file', \
2841 sOpenMode = 'r', sDisposition = 'oe'),
2842 tdTestResultFileReadWrite(fRc = False) ],
2843 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = '\\\\uncrulez\\non-existing.file', \
2844 sOpenMode = 'r', sDisposition = 'oe'),
2845 tdTestResultFileReadWrite(fRc = False) ],
2846 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = '../../non-existing.file', \
2847 sOpenMode = 'r', sDisposition = 'oe'),
2848 tdTestResultFileReadWrite(fRc = False) ]
2849 ]);
2850
2851 if oTestVm.isWindows():
2852 aaTests.extend([
2853 # Create a file which must not exist (but it hopefully does).
2854 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows\\System32\\calc.exe', \
2855 sOpenMode = 'w', sDisposition = 'ce'),
2856 tdTestResultFileReadWrite(fRc = False) ],
2857 # Open a file which must exist.
2858 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows\\System32\\kernel32.dll', \
2859 sOpenMode = 'r', sDisposition = 'oe'),
2860 tdTestResultFileReadWrite(fRc = True) ],
2861 # Try truncating a file which already is opened with a different sharing mode (and thus should fail).
2862 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows\\System32\\kernel32.dll', \
2863 sOpenMode = 'w', sDisposition = 'ot'),
2864 tdTestResultFileReadWrite(fRc = False) ]
2865 ]);
2866
2867 if oTestVm.sKind == "WindowsXP":
2868 aaTests.extend([
2869 # Reading from beginning.
2870 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows\\System32\\eula.txt', \
2871 sOpenMode = 'r', sDisposition = 'oe', cbToReadWrite = 33),
2872 tdTestResultFileReadWrite(fRc = True, aBuf = 'Microsoft Windows XP Professional', \
2873 cbProcessed = 33, cbOffset = 33) ],
2874 # Reading from offset.
2875 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = 'C:\\Windows\\System32\\eula.txt', \
2876 sOpenMode = 'r', sDisposition = 'oe', cbOffset = 17782, cbToReadWrite = 26),
2877 tdTestResultFileReadWrite(fRc = True, aBuf = 'LINKS TO THIRD PARTY SITES', \
2878 cbProcessed = 26, cbOffset = 17782 + 26) ]
2879 ]);
2880
2881 fRc = True;
2882 for (i, aTest) in enumerate(aaTests):
2883 curTest = aTest[0]; # tdTestFileReadWrite, use an index, later.
2884 curRes = aTest[1]; # tdTestResult
2885 reporter.log('Testing #%d, sFile="%s", cbToReadWrite=%d, sOpenMode="%s", sDisposition="%s", cbOffset=%d ...' % \
2886 (i, curTest.sFile, curTest.cbToReadWrite, curTest.sOpenMode, curTest.sDisposition, curTest.cbOffset));
2887 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
2888 fRc, curGuestSession = curTest.createSession('testGuestCtrlFileRead: Test #%d' % (i,));
2889 if fRc is False:
2890 reporter.error('Test #%d failed: Could not create session' % (i,));
2891 break;
2892 try:
2893 if curTest.cbOffset > 0: # The offset parameter is gone.
2894 if self.oTstDrv.fpApiVer >= 5.0:
2895 curFile = curGuestSession.fileOpenEx(curTest.sFile, curTest.getAccessMode(), curTest.getOpenAction(),
2896 curTest.getSharingMode(), curTest.lCreationMode, []);
2897 curFile.seek(curTest.cbOffset, vboxcon.FileSeekOrigin_Begin);
2898 else:
2899 curFile = curGuestSession.fileOpenEx(curTest.sFile, curTest.sOpenMode, curTest.sDisposition, \
2900 curTest.sSharingMode, curTest.lCreationMode, curTest.cbOffset);
2901 curOffset = long(curFile.offset);
2902 resOffset = long(curTest.cbOffset);
2903 if curOffset != resOffset:
2904 reporter.error('Test #%d failed: Initial offset on open does not match: Got %d, expected %d' \
2905 % (i, curOffset, resOffset));
2906 fRc = False;
2907 else:
2908 if self.oTstDrv.fpApiVer >= 5.0:
2909 curFile = curGuestSession.fileOpen(curTest.sFile, curTest.getAccessMode(), curTest.getOpenAction(),
2910 curTest.lCreationMode);
2911 else:
2912 curFile = curGuestSession.fileOpen(curTest.sFile, curTest.sOpenMode, curTest.sDisposition, \
2913 curTest.lCreationMode);
2914 if fRc \
2915 and curTest.cbToReadWrite > 0:
2916 ## @todo Split this up in 64K reads. Later.
2917 ## @todo Test timeouts.
2918 aBufRead = curFile.read(curTest.cbToReadWrite, 30 * 1000);
2919 if curRes.cbProcessed > 0 \
2920 and curRes.cbProcessed is not len(aBufRead):
2921 reporter.error('Test #%d failed: Read buffer length does not match: Got %d, expected %d' \
2922 % (i, len(aBufRead), curRes.cbProcessed));
2923 fRc = False;
2924 if fRc:
2925 if curRes.aBuf is not None \
2926 and bytes(curRes.aBuf) != bytes(aBufRead):
2927 reporter.error('Test #%d failed: Got buffer\n%s (%d bytes), expected\n%s (%d bytes)' \
2928 % (i, map(hex, map(ord, aBufRead)), len(aBufRead), \
2929 map(hex, map(ord, curRes.aBuf)), len(curRes.aBuf)));
2930 reporter.error('Test #%d failed: Got buffer\n%s, expected\n%s' \
2931 % (i, aBufRead, curRes.aBuf));
2932 fRc = False;
2933 # Test final offset.
2934 curOffset = long(curFile.offset);
2935 resOffset = long(curRes.cbOffset);
2936 if curOffset != resOffset:
2937 reporter.error('Test #%d failed: Final offset does not match: Got %d, expected %d' \
2938 % (i, curOffset, resOffset));
2939 fRc = False;
2940 curFile.close();
2941 except:
2942 reporter.logXcpt('Opening "%s" failed:' % (curTest.sFile,));
2943 fRc = False;
2944
2945 curTest.closeSession();
2946
2947 if fRc != curRes.fRc:
2948 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc, curRes.fRc));
2949 fRc = False;
2950 break;
2951
2952 return (fRc, oTxsSession);
2953
2954 def testGuestCtrlFileWrite(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
2955 """
2956 Tests writing to guest files.
2957 """
2958
2959 if oTestVm.isWindows():
2960 sUser = "Administrator";
2961 else:
2962 sUser = "vbox";
2963 sPassword = "password";
2964
2965 if oTestVm.isWindows():
2966 sScratch = "C:\\Temp\\vboxtest\\testGuestCtrlFileWrite\\";
2967
2968 if oTxsSession.syncMkDir('${SCRATCH}/testGuestCtrlFileWrite') is False:
2969 reporter.error('Could not create scratch directory on guest');
2970 return (False, oTxsSession);
2971
2972 aaTests = [];
2973
2974 cScratchBuf = 512;
2975 aScratchBuf = array('b', [random.randint(-128, 127) for i in range(cScratchBuf)]);
2976 aaTests.extend([
2977 # Write to a non-existing file.
2978 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = sScratch + 'testGuestCtrlFileWrite.txt', \
2979 sOpenMode = 'w+', sDisposition = 'ce', cbToReadWrite = cScratchBuf,
2980 aBuf = aScratchBuf),
2981 tdTestResultFileReadWrite(fRc = True, aBuf = aScratchBuf, \
2982 cbProcessed = cScratchBuf, cbOffset = cScratchBuf) ]
2983 ]);
2984
2985 aScratchBuf2 = array('b', [random.randint(-128, 127) for i in range(cScratchBuf)]);
2986 aaTests.extend([
2987 # Append the same amount of data to the just created file.
2988 [ tdTestFileReadWrite(sUser = sUser, sPassword = sPassword, sFile = sScratch + 'testGuestCtrlFileWrite.txt', \
2989 sOpenMode = 'w+', sDisposition = 'oa', cbToReadWrite = cScratchBuf,
2990 cbOffset = cScratchBuf, aBuf = aScratchBuf2),
2991 tdTestResultFileReadWrite(fRc = True, aBuf = aScratchBuf2, \
2992 cbProcessed = cScratchBuf, cbOffset = cScratchBuf * 2) ],
2993 ]);
2994
2995 fRc = True;
2996 for (i, aTest) in enumerate(aaTests):
2997 curTest = aTest[0]; # tdTestFileReadWrite, use an index, later.
2998 curRes = aTest[1]; # tdTestResult
2999 reporter.log('Testing #%d, sFile="%s", cbToReadWrite=%d, sOpenMode="%s", sDisposition="%s", cbOffset=%d ...' % \
3000 (i, curTest.sFile, curTest.cbToReadWrite, curTest.sOpenMode, curTest.sDisposition, curTest.cbOffset));
3001 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
3002 fRc, curGuestSession = curTest.createSession('testGuestCtrlFileWrite: Test #%d' % (i,));
3003 if fRc is False:
3004 reporter.error('Test #%d failed: Could not create session' % (i,));
3005 break;
3006 try:
3007 if curTest.cbOffset > 0: # The offset parameter is gone.
3008 if self.oTstDrv.fpApiVer >= 5.0:
3009 curFile = curGuestSession.fileOpenEx(curTest.sFile, curTest.getAccessMode(), curTest.getOpenAction(),
3010 curTest.getSharingMode(), []);
3011 curFile.seek(curTest.cbOffset, vboxcon.FileSeekOrigin_Begin);
3012 else:
3013 curFile = curGuestSession.fileOpenEx(curTest.sFile, curTest.sOpenMode, curTest.sDisposition, \
3014 curTest.sSharingMode, curTest.lCreationMode, curTest.cbOffset);
3015 curOffset = long(curFile.offset);
3016 resOffset = long(curTest.cbOffset);
3017 if curOffset != resOffset:
3018 reporter.error('Test #%d failed: Initial offset on open does not match: Got %d, expected %d' \
3019 % (i, curOffset, resOffset));
3020 fRc = False;
3021 else:
3022 if self.oTstDrv.fpApiVer >= 5.0:
3023 curFile = curGuestSession.fileOpen(curTest.sFile, curTest.getAccessMode(), curTest.getOpenAction(),
3024 curTest.lCreationMode);
3025 else:
3026 curFile = curGuestSession.fileOpen(curTest.sFile, curTest.sOpenMode, curTest.sDisposition, \
3027 curTest.lCreationMode);
3028 if fRc \
3029 and curTest.cbToReadWrite > 0:
3030 ## @todo Split this up in 64K writes. Later.
3031 ## @todo Test timeouts.
3032 cBytesWritten = curFile.write(curTest.aBuf, 30 * 1000);
3033 if curRes.cbProcessed > 0 \
3034 and curRes.cbProcessed != cBytesWritten:
3035 reporter.error('Test #%d failed: Written buffer length does not match: Got %d, expected %d' \
3036 % (i, cBytesWritten, curRes.cbProcessed));
3037 fRc = False;
3038 if fRc:
3039 # Verify written content by seeking back to the initial offset and
3040 # re-read & compare the written data.
3041 try:
3042 if self.oTstDrv.fpApiVer >= 5.0:
3043 curFile.seek(-(curTest.cbToReadWrite), vboxcon.FileSeekOrigin_Current);
3044 else:
3045 curFile.seek(-(curTest.cbToReadWrite), vboxcon.FileSeekType_Current);
3046 except:
3047 reporter.logXcpt('Seeking back to initial write position failed:');
3048 fRc = False;
3049 if fRc \
3050 and long(curFile.offset) != curTest.cbOffset:
3051 reporter.error('Test #%d failed: Initial write position does not match current position, \
3052 got %d, expected %d' \
3053 % (i, long(curFile.offset), curTest.cbOffset));
3054 fRc = False;
3055 if fRc:
3056 aBufRead = curFile.read(curTest.cbToReadWrite, 30 * 1000);
3057 if len(aBufRead) != curTest.cbToReadWrite:
3058 reporter.error('Test #%d failed: Got buffer length %d, expected %d' \
3059 % (i, len(aBufRead), curTest.cbToReadWrite));
3060 fRc = False;
3061 if fRc \
3062 and curRes.aBuf is not None \
3063 and buffer(curRes.aBuf) != aBufRead:
3064 reporter.error('Test #%d failed: Got buffer\n%s, expected\n%s' \
3065 % (i, aBufRead, curRes.aBuf));
3066 fRc = False;
3067 # Test final offset.
3068 curOffset = long(curFile.offset);
3069 resOffset = long(curRes.cbOffset);
3070 if curOffset != resOffset:
3071 reporter.error('Test #%d failed: Final offset does not match: Got %d, expected %d' \
3072 % (i, curOffset, resOffset));
3073 fRc = False;
3074 curFile.close();
3075 except:
3076 reporter.logXcpt('Opening "%s" failed:' % (curTest.sFile,));
3077 fRc = False;
3078
3079 curTest.closeSession();
3080
3081 if fRc != curRes.fRc:
3082 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc, curRes.fRc));
3083 fRc = False;
3084 break;
3085
3086 return (fRc, oTxsSession);
3087
3088 def testGuestCtrlCopyTo(self, oSession, oTxsSession, oTestVm):
3089 """
3090 Tests copying files from host to the guest.
3091 """
3092
3093 if oTestVm.isWindows():
3094 sUser = "Administrator";
3095 else:
3096 sUser = "vbox";
3097 sPassword = "password";
3098
3099 if oTestVm.isWindows():
3100 sScratch = "C:\\Temp\\vboxtest\\testGuestCtrlCopyTo\\";
3101
3102 if oTxsSession.syncMkDir('${SCRATCH}/testGuestCtrlCopyTo') is False:
3103 reporter.error('Could not create scratch directory on guest');
3104 return (False, oTxsSession);
3105
3106 # Some stupid trickery to guess the location of the iso.
3107 sVBoxValidationKitISO = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../VBoxValidationKit.iso'));
3108 if not os.path.isfile(sVBoxValidationKitISO):
3109 sVBoxValidationKitISO = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../VBoxTestSuite.iso'));
3110 if not os.path.isfile(sVBoxValidationKitISO):
3111 sCur = os.getcwd();
3112 for i in range(0, 10):
3113 sVBoxValidationKitISO = os.path.join(sCur, 'validationkit/VBoxValidationKit.iso');
3114 if os.path.isfile(sVBoxValidationKitISO):
3115 break;
3116 sVBoxValidationKitISO = os.path.join(sCur, 'testsuite/VBoxTestSuite.iso');
3117 if os.path.isfile(sVBoxValidationKitISO):
3118 break;
3119 sCur = os.path.abspath(os.path.join(sCur, '..'));
3120 if i is None: pass; # shut up pychecker/pylint.
3121 if os.path.isfile(sVBoxValidationKitISO):
3122 reporter.log('Validation Kit .ISO found at: %s' % (sVBoxValidationKitISO,));
3123 else:
3124 reporter.log('Warning: Validation Kit .ISO not found -- some tests might fail');
3125
3126 aaTests = [];
3127 if oTestVm.isWindows():
3128 aaTests.extend([
3129 # Destination missing.
3130 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = ''), tdTestResult(fRc = False) ],
3131 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows',
3132 aFlags = [ 1234 ] ), tdTestResult(fRc = False) ],
3133 # Source missing.
3134 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sDst = ''), tdTestResult(fRc = False) ],
3135 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sDst = 'C:\\Windows',
3136 aFlags = [ 1234 ] ), tdTestResult(fRc = False) ],
3137 # Nothing to copy (source and/or destination is empty).
3138 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = 'z:\\'), tdTestResult(fRc = False) ],
3139 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = '\\\\uncrulez\\foo'),
3140 tdTestResult(fRc = False) ],
3141 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = 'non-exist',
3142 sDst = os.path.join(sScratch, 'non-exist.dll')), tdTestResult(fRc = False) ],
3143 # Copying single files.
3144 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO,
3145 sDst = 'C:\\non-exist\\'), tdTestResult(fRc = False) ],
3146 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO,
3147 sDst = 'C:\\non\\exist\\'), tdTestResult(fRc = False) ],
3148 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO,
3149 sDst = 'C:\\non\\exist\\renamedfile.dll'), tdTestResult(fRc = False) ],
3150 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO,
3151 sDst = os.path.join(sScratch, 'HostGuestAdditions.iso')), tdTestResult(fRc = True) ],
3152 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO,
3153 sDst = os.path.join(sScratch, 'HostGuestAdditions.iso')), tdTestResult(fRc = True) ],
3154 # Destination is a directory, should fail.
3155 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO,
3156 sDst = sScratch), tdTestResult(fRc = False) ]
3157 ## @todo Add testing the CopyTo flags here!
3158 ]);
3159
3160 if self.oTstDrv.sHost == 'win':
3161 ## @todo Check for Windows (7) host.
3162 aaTests.extend([
3163 # Copying directories with contain files we don't have read access to.
3164 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\security',
3165 sDst = sScratch), tdTestResult(fRc = False) ],
3166 # Copying directories with regular files.
3167 [ tdTestCopyTo(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\Help',
3168 sDst = sScratch), tdTestResult(fRc = True) ]
3169 ]);
3170 else:
3171 reporter.log('No OS-specific tests for non-Windows yet!');
3172
3173 fRc = True;
3174 for (i, aTest) in enumerate(aaTests):
3175 curTest = aTest[0]; # tdTestExec, use an index, later.
3176 curRes = aTest[1]; # tdTestResult
3177 reporter.log('Testing #%d, sSrc="%s", sDst="%s", aFlags="%s" ...' % \
3178 (i, curTest.sSrc, curTest.sDst, curTest.aFlags));
3179 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
3180 fRc, curGuestSession = curTest.createSession('testGuestCtrlCopyTo: Test #%d' % (i,));
3181 if fRc is False:
3182 reporter.error('Test #%d failed: Could not create session' % (i,));
3183 break;
3184 fRc2 = self.gctrlCopyTo(curTest, curGuestSession);
3185 curTest.closeSession();
3186 if fRc2 is curRes.fRc:
3187 ## @todo Verify the copied results (size, checksum?).
3188 pass;
3189 else:
3190 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, curRes.fRc));
3191 fRc = False;
3192 break;
3193
3194 return (fRc, oTxsSession);
3195
3196 def testGuestCtrlCopyFrom(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
3197 """
3198 Tests copying files from guest to the host.
3199 """
3200
3201 if oTestVm.isWindows():
3202 sUser = "Administrator";
3203 else:
3204 sUser = "vbox";
3205 sPassword = "password";
3206
3207 sScratch = os.path.join(self.oTstDrv.sScratchPath, "testGctrlCopyFrom");
3208 try:
3209 os.makedirs(sScratch);
3210 except OSError as e:
3211 if e.errno != errno.EEXIST:
3212 reporter.error('Failed: Unable to create scratch directory \"%s\"' % (sScratch,));
3213 return (False, oTxsSession);
3214 reporter.log('Scratch path is: %s' % (sScratch,));
3215
3216 aaTests = [];
3217 if oTestVm.isWindows():
3218 aaTests.extend([
3219 # Destination missing.
3220 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = ''),
3221 tdTestResult(fRc = False) ],
3222 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows',
3223 aFlags = [ 1234 ] ),
3224 tdTestResult(fRc = False) ],
3225 # Source missing.
3226 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sDst = ''),
3227 tdTestResult(fRc = False) ],
3228 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sDst = 'C:\\Windows',
3229 aFlags = [ 1234 ] ),
3230 tdTestResult(fRc = False) ],
3231 # Nothing to copy (sDst is empty / unreachable).
3232 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'z:\\'),
3233 tdTestResult(fRc = False) ],
3234 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = '\\\\uncrulez\\foo'),
3235
3236 tdTestResult(fRc = False) ],
3237 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'non-exist',
3238 sDst = os.path.join(sScratch, 'non-exist.dll')),
3239 tdTestResult(fRc = False) ]
3240 ## @todo Add testing the CopyFrom aFlags here!
3241 ]);
3242
3243 if self.oTstDrv.sHost == 'win':
3244 aaTests.extend([
3245 # FIXME: Failing test.
3246 # Copying single files.
3247 # [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\system32\\ole32.dll',
3248 # sDst = 'C:\\non-exist\\'), tdTestResult(fRc = False) ],
3249 # [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\system32\\ole32.dll',
3250 # sDst = 'C:\\non\\exist\\'), tdTestResult(fRc = False) ],
3251 # [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\system32\\ole32.dll',
3252 # sDst = 'C:\\non\\exist\\renamedfile.dll'), tdTestResult(fRc = False) ],
3253 # [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\system32\\ole32.dll',
3254 # sDst = os.path.join(sScratch, 'renamedfile.dll')), tdTestResult(fRc = True) ],
3255 # [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\system32\\ole32.dll',
3256 # sDst = os.path.join(sScratch, 'renamedfile.dll')), tdTestResult(fRc = True) ],
3257 # Destination is a directory, should fail.
3258 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\system32\\ole32.dll',
3259 sDst = sScratch), tdTestResult(fRc = False) ],
3260 # Copying directories.
3261 [ tdTestCopyFrom(sUser = sUser, sPassword = sPassword, sSrc = 'C:\\Windows\\Web',
3262 sDst = sScratch), tdTestResult(fRc = True) ]
3263 ## @todo Add testing the CopyFrom aFlags here!
3264 ]);
3265 else:
3266 reporter.log('No OS-specific tests for non-Windows yet!');
3267
3268 fRc = True;
3269 for (i, aTest) in enumerate(aaTests):
3270 curTest = aTest[0]; # tdTestExec, use an index, later.
3271 curRes = aTest[1]; # tdTestResult
3272 reporter.log('Testing #%d, sSrc="%s", sDst="%s", aFlags="%s" ...' % \
3273 (i, curTest.sSrc, curTest.sDst, curTest.aFlags));
3274 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
3275 fRc, curGuestSession = curTest.createSession('testGuestCtrlCopyFrom: Test #%d' % (i,));
3276 if fRc is False:
3277 reporter.error('Test #%d failed: Could not create session' % (i,));
3278 break;
3279 fRc2 = self.gctrlCopyFrom(curTest, curRes, curGuestSession);
3280 curTest.closeSession();
3281 if fRc2 is curRes.fRc:
3282 ## @todo Verify the copied results (size, checksum?).
3283 pass;
3284 else:
3285 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, curRes.fRc));
3286 fRc = False;
3287 break;
3288
3289 return (fRc, oTxsSession);
3290
3291 def testGuestCtrlUpdateAdditions(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914
3292 """
3293 Tests updating the Guest Additions inside the guest.
3294 """
3295
3296 if oTestVm.isWindows():
3297 sUser = "Administrator";
3298 else:
3299 sUser = "vbox";
3300 sPassword = "password";
3301
3302 # Some stupid trickery to guess the location of the iso.
3303 sVBoxValidationKitISO = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../VBoxValidationKit.iso'));
3304 if not os.path.isfile(sVBoxValidationKitISO):
3305 sVBoxValidationKitISO = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../VBoxTestSuite.iso'));
3306 if not os.path.isfile(sVBoxValidationKitISO):
3307 sCur = os.getcwd();
3308 for i in range(0, 10):
3309 sVBoxValidationKitISO = os.path.join(sCur, 'validationkit/VBoxValidationKit.iso');
3310 if os.path.isfile(sVBoxValidationKitISO):
3311 break;
3312 sVBoxValidationKitISO = os.path.join(sCur, 'testsuite/VBoxTestSuite.iso');
3313 if os.path.isfile(sVBoxValidationKitISO):
3314 break;
3315 sCur = os.path.abspath(os.path.join(sCur, '..'));
3316 if i is None: pass; # shut up pychecker/pylint.
3317 if os.path.isfile(sVBoxValidationKitISO):
3318 reporter.log('Validation Kit .ISO found at: %s' % (sVBoxValidationKitISO,));
3319 else:
3320 reporter.log('Warning: Validation Kit .ISO not found -- some tests might fail');
3321
3322 sScratch = os.path.join(self.oTstDrv.sScratchPath, "testGctrlUpdateAdditions");
3323 try:
3324 os.makedirs(sScratch);
3325 except OSError as e:
3326 if e.errno != errno.EEXIST:
3327 reporter.error('Failed: Unable to create scratch directory \"%s\"' % (sScratch,));
3328 return (False, oTxsSession);
3329 reporter.log('Scratch path is: %s' % (sScratch,));
3330
3331 aaTests = [];
3332 if oTestVm.isWindows():
3333 aaTests.extend([
3334 # Source is missing.
3335 [ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword, sSrc = ''),
3336 tdTestResult(fRc = False) ],
3337 # Wrong aFlags.
3338 [ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword, sSrc = self.oTstDrv.getGuestAdditionsIso(),
3339 aFlags = [ 1234 ]),
3340 tdTestResult(fRc = False) ],
3341 # Non-existing .ISO.
3342 [ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword, sSrc = "non-existing.iso"),
3343 tdTestResult(fRc = False) ],
3344 # Wrong .ISO.
3345 [ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword, sSrc = sVBoxValidationKitISO),
3346 tdTestResult(fRc = False) ],
3347 # The real thing.
3348 [ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword, sSrc = self.oTstDrv.getGuestAdditionsIso()),
3349 tdTestResult(fRc = True) ],
3350 # Test the (optional) installer arguments. This will extract the
3351 # installer into our guest's scratch directory.
3352 [ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword, sSrc = self.oTstDrv.getGuestAdditionsIso(),
3353 aArgs = [ '/extract', '/D=' + sScratch ]),
3354 tdTestResult(fRc = True) ]
3355 # Some debg ISO. Only enable locally.
3356 #[ tdTestUpdateAdditions(sUser = sUser, sPassword = sPassword,
3357 # sSrc = "V:\\Downloads\\VBoxGuestAdditions-r80354.iso"),
3358 # tdTestResult(fRc = True) ]
3359 ]);
3360 else:
3361 reporter.log('No OS-specific tests for non-Windows yet!');
3362
3363 fRc = True;
3364 for (i, aTest) in enumerate(aaTests):
3365 curTest = aTest[0]; # tdTestExec, use an index, later.
3366 curRes = aTest[1]; # tdTestResult
3367 reporter.log('Testing #%d, sSrc="%s", aFlags="%s" ...' % \
3368 (i, curTest.sSrc, curTest.aFlags));
3369 curTest.setEnvironment(oSession, oTxsSession, oTestVm);
3370 fRc, _ = curTest.createSession('Test #%d' % (i,));
3371 if fRc is False:
3372 reporter.error('Test #%d failed: Could not create session' % (i,));
3373 break;
3374 try:
3375 curProgress = curTest.oTest.oGuest.updateGuestAdditions(curTest.sSrc, curTest.aArgs, curTest.aFlags);
3376 if curProgress is not None:
3377 oProgress = vboxwrappers.ProgressWrapper(curProgress, self.oTstDrv.oVBoxMgr, self, "gctrlUpGA");
3378 try:
3379 iRc = oProgress.waitForOperation(0, fIgnoreErrors = True);
3380 if iRc != 0:
3381 reporter.log('Waiting for updating Guest Additions failed');
3382 fRc = False;
3383 except:
3384 reporter.logXcpt('Updating Guest Additions waiting exception for sSrc="%s", aFlags="%s":' \
3385 % (curTest.sSrc, curTest.aFlags));
3386 fRc = False;
3387 except:
3388 # Just log, don't assume an error here (will be done in the main loop then).
3389 reporter.logXcpt('Updating Guest Additions exception for sSrc="%s", aFlags="%s":' \
3390 % (curTest.sSrc, curTest.aFlags));
3391 fRc = False;
3392 curTest.closeSession();
3393 if fRc is curRes.fRc:
3394 if fRc:
3395 ## @todo Verify if Guest Additions were really updated (build, revision, ...).
3396 pass;
3397 else:
3398 reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc, curRes.fRc));
3399 fRc = False;
3400 break;
3401
3402 return (fRc, oTxsSession);
3403
3404
3405
3406class tdAddGuestCtrl(vbox.TestDriver): # pylint: disable=R0902,R0904
3407 """
3408 Guest control using VBoxService on the guest.
3409 """
3410
3411 def __init__(self):
3412 vbox.TestDriver.__init__(self);
3413 self.oTestVmSet = self.oTestVmManager.getStandardVmSet('nat');
3414 self.fQuick = False; # Don't skip lengthly tests by default.
3415 self.addSubTestDriver(SubTstDrvAddGuestCtrl(self));
3416
3417 #
3418 # Overridden methods.
3419 #
3420 def showUsage(self):
3421 """
3422 Shows the testdriver usage.
3423 """
3424 rc = vbox.TestDriver.showUsage(self);
3425 reporter.log('');
3426 reporter.log('tdAddGuestCtrl Options:');
3427 reporter.log(' --quick');
3428 reporter.log(' Same as --virt-modes hwvirt --cpu-counts 1.');
3429 return rc;
3430
3431 def parseOption(self, asArgs, iArg): # pylint: disable=R0912,R0915
3432 """
3433 Parses the testdriver arguments from the command line.
3434 """
3435 if asArgs[iArg] == '--quick':
3436 self.parseOption(['--virt-modes', 'hwvirt'], 0);
3437 self.parseOption(['--cpu-counts', '1'], 0);
3438 self.fQuick = True;
3439 else:
3440 return vbox.TestDriver.parseOption(self, asArgs, iArg);
3441 return iArg + 1;
3442
3443 def actionConfig(self):
3444 if not self.importVBoxApi(): # So we can use the constant below.
3445 return False;
3446
3447 eNic0AttachType = vboxcon.NetworkAttachmentType_NAT;
3448 sGaIso = self.getGuestAdditionsIso();
3449 return self.oTestVmSet.actionConfig(self, eNic0AttachType = eNic0AttachType, sDvdImage = sGaIso);
3450
3451 def actionExecute(self):
3452 return self.oTestVmSet.actionExecute(self, self.testOneCfg);
3453
3454 #
3455 # Test execution helpers.
3456 #
3457 def testOneCfg(self, oVM, oTestVm): # pylint: disable=R0915
3458 """
3459 Runs the specified VM thru the tests.
3460
3461 Returns a success indicator on the general test execution. This is not
3462 the actual test result.
3463 """
3464
3465 self.logVmInfo(oVM);
3466
3467 fRc = True;
3468 oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(oTestVm.sVmName, fCdWait = False);
3469 reporter.log("TxsSession: %s" % (oTxsSession,));
3470 if oSession is not None:
3471 self.addTask(oSession);
3472
3473 fManual = False; # Manual override for local testing. (Committed version shall be False.)
3474 if not fManual:
3475 fRc, oTxsSession = self.aoSubTstDrvs[0].testIt(oTestVm, oSession, oTxsSession);
3476 else:
3477 fRc, oTxsSession = self.testGuestCtrlManual(oSession, oTxsSession, oTestVm);
3478
3479 # Cleanup.
3480 self.removeTask(oTxsSession);
3481 if not fManual:
3482 self.terminateVmBySession(oSession);
3483 else:
3484 fRc = False;
3485 return fRc;
3486
3487 def gctrlReportError(self, progress):
3488 """
3489 Helper function to report an error of a
3490 given progress object.
3491 """
3492 if progress is None:
3493 reporter.log('No progress object to print error for');
3494 else:
3495 errInfo = progress.errorInfo;
3496 if errInfo:
3497 reporter.log('%s' % (errInfo.text,));
3498 return False;
3499
3500 def gctrlGetRemainingTime(self, msTimeout, msStart):
3501 """
3502 Helper function to return the remaining time (in ms)
3503 based from a timeout value and the start time (both in ms).
3504 """
3505 if msTimeout is 0:
3506 return 0xFFFFFFFE; # Wait forever.
3507 msElapsed = base.timestampMilli() - msStart;
3508 if msElapsed > msTimeout:
3509 return 0; # No time left.
3510 return msTimeout - msElapsed;
3511
3512 def testGuestCtrlManual(self, oSession, oTxsSession, oTestVm): # pylint: disable=R0914,R0915,W0613,W0612
3513 """
3514 For manually testing certain bits.
3515 """
3516
3517 reporter.log('Manual testing ...');
3518 fRc = True;
3519
3520 sUser = 'Administrator';
3521 sPassword = 'password';
3522
3523 oGuest = oSession.o.console.guest;
3524 oGuestSession = oGuest.createSession(sUser,
3525 sPassword,
3526 "", "Manual Test");
3527
3528 aWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
3529 _ = oGuestSession.waitForArray(aWaitFor, 30 * 1000);
3530
3531 sCmd = 'c:\\windows\\system32\\cmd.exe';
3532 aArgs = [ sCmd, '/C', 'dir', '/S', 'c:\\windows' ];
3533 aEnv = [];
3534 aFlags = [];
3535
3536 for _ in range(100):
3537 oProc = oGuestSession.processCreate(sCmd, aArgs if self.fpApiVer >= 5.0 else aArgs[1:],
3538 aEnv, aFlags, 30 * 1000);
3539
3540 aWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate ];
3541 _ = oProc.waitForArray(aWaitFor, 30 * 1000);
3542
3543 oGuestSession.close();
3544 oGuestSession = None;
3545
3546 time.sleep(5);
3547
3548 oSession.o.console.PowerDown();
3549
3550 return (fRc, oTxsSession);
3551
3552if __name__ == '__main__':
3553 sys.exit(tdAddGuestCtrl().main(sys.argv));
3554
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette