VirtualBox

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

Last change on this file since 71519 was 71519, checked in by vboxsync, 7 years ago

Guest Control/ValidationKit: Makes use of the now implemented IGuestSession::directoryCopyToGuest() and IGuestSession::directoryCopyFromGuest() APIs, enabled some formerly disabled tests. More to come.

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

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