VirtualBox

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

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

Guest Control/tests: Disabled IGuestSession::[directory|file]CopyToGuest(), needs some more (local) debugging first.

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