VirtualBox

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

Last change on this file since 103211 was 103211, checked in by vboxsync, 12 months ago

Validation Kit/tdAddGuestCtrl.py: Expand the resolved path within locateGstBinary() so that it can be found by the Guest Control session as well [Pylint fixes]. bugref:10586

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 288.5 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# pylint: disable=too-many-lines
4
5"""
6VirtualBox Validation Kit - Guest Control Tests.
7"""
8
9__copyright__ = \
10"""
11Copyright (C) 2010-2023 Oracle and/or its affiliates.
12
13This file is part of VirtualBox base platform packages, as
14available from https://www.virtualbox.org.
15
16This program is free software; you can redistribute it and/or
17modify it under the terms of the GNU General Public License
18as published by the Free Software Foundation, in version 3 of the
19License.
20
21This program is distributed in the hope that it will be useful, but
22WITHOUT ANY WARRANTY; without even the implied warranty of
23MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24General Public License for more details.
25
26You should have received a copy of the GNU General Public License
27along with this program; if not, see <https://www.gnu.org/licenses>.
28
29The contents of this file may alternatively be used under the terms
30of the Common Development and Distribution License Version 1.0
31(CDDL), a copy of it is provided in the "COPYING.CDDL" file included
32in the VirtualBox distribution, in which case the provisions of the
33CDDL are applicable instead of those of the GPL.
34
35You may elect to license modified versions of this file under the
36terms and conditions of either the GPL or the CDDL or both.
37
38SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
39"""
40__version__ = "$Revision: 103211 $"
41
42# Standard Python imports.
43import errno
44import os
45import random
46import string
47import struct
48import sys
49import threading
50import time
51
52# Only the main script needs to modify the path.
53try: __file__ # pylint: disable=used-before-assignment
54except: __file__ = sys.argv[0];
55g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))));
56sys.path.append(g_ksValidationKitDir);
57
58# Validation Kit imports.
59from testdriver import reporter;
60from testdriver import base;
61from testdriver import testfileset;
62from testdriver import vbox;
63from testdriver import vboxcon;
64from testdriver import vboxtestfileset;
65from testdriver import vboxwrappers;
66from common import utils;
67
68# Python 3 hacks:
69if sys.version_info[0] >= 3:
70 long = int # pylint: disable=redefined-builtin,invalid-name
71 xrange = range; # pylint: disable=redefined-builtin,invalid-name
72
73def limitString(sString, cLimit = 128):
74 """
75 Returns a string with ellipsis ("...") when exceeding the specified limit.
76 Useful for toning down logging. By default strings will be shortened at 128 characters.
77 """
78 if not isinstance(sString, str):
79 sString = str(sString);
80 cLen = len(sString);
81 if not cLen:
82 return '';
83 return (sString[:cLimit] + '...[%d more]' % (cLen - cLimit)) if cLen > cLimit else sString;
84
85class GuestStream(bytearray):
86 """
87 Class for handling a guest process input/output stream.
88
89 @todo write stdout/stderr tests.
90 """
91 def appendStream(self, stream, convertTo = '<b'):
92 """
93 Appends and converts a byte sequence to this object;
94 handy for displaying a guest stream.
95 """
96 self.extend(struct.pack(convertTo, stream));
97
98
99class tdCtxCreds(object):
100 """
101 Provides credentials to pass to the guest.
102 """
103 def __init__(self, sUser = None, sPassword = None, sDomain = None):
104 self.oTestVm = None;
105 self.sUser = sUser;
106 self.sPassword = sPassword;
107 self.sDomain = sDomain;
108
109 def applyDefaultsIfNotSet(self, oTestVm):
110 """
111 Applies credential defaults, based on the test VM (guest OS), if
112 no credentials were set yet.
113
114 Returns success status.
115 """
116 self.oTestVm = oTestVm;
117 if not self.oTestVm:
118 reporter.log('VM object is invalid -- did VBoxSVC or a client crash?');
119 return False;
120
121 if self.sUser is None:
122 self.sUser = self.oTestVm.getTestUser();
123
124 if self.sPassword is None:
125 self.sPassword = self.oTestVm.getTestUserPassword(self.sUser);
126
127 if self.sDomain is None:
128 self.sDomain = '';
129
130 return True;
131
132class tdTestGuestCtrlBase(object):
133 """
134 Base class for all guest control tests.
135
136 Note: This test ASSUMES that working Guest Additions
137 were installed and running on the guest to be tested.
138 """
139 def __init__(self, oCreds = None):
140 self.oGuest = None; ##< IGuest.
141 self.oTestVm = None;
142 self.oCreds = oCreds ##< type: tdCtxCreds
143 self.timeoutMS = 30 * 1000; ##< 30s timeout
144 self.oGuestSession = None; ##< IGuestSession reference or None.
145
146 def setEnvironment(self, oSession, oTxsSession, oTestVm):
147 """
148 Sets the test environment required for this test.
149
150 Returns success status.
151 """
152 _ = oTxsSession;
153
154 fRc = True;
155 try:
156 self.oGuest = oSession.o.console.guest;
157 self.oTestVm = oTestVm;
158 except:
159 fRc = reporter.errorXcpt();
160
161 if self.oCreds is None:
162 self.oCreds = tdCtxCreds();
163
164 fRc = fRc and self.oCreds.applyDefaultsIfNotSet(self.oTestVm);
165
166 if not fRc:
167 reporter.log('Error setting up Guest Control testing environment!');
168
169 return fRc;
170
171 def uploadLogData(self, oTstDrv, aData, sFileName, sDesc):
172 """
173 Uploads (binary) data to a log file for manual (later) inspection.
174 """
175 reporter.log('Creating + uploading log data file "%s"' % sFileName);
176 sHstFileName = os.path.join(oTstDrv.sScratchPath, sFileName);
177 try:
178 with open(sHstFileName, "wb") as oCurTestFile:
179 oCurTestFile.write(aData);
180 except:
181 return reporter.error('Unable to create temporary file for "%s"' % (sDesc,));
182 return reporter.addLogFile(sHstFileName, 'misc/other', sDesc);
183
184 def createSession(self, sName, fIsError = True):
185 """
186 Creates (opens) a guest session.
187 Returns (True, IGuestSession) on success or (False, None) on failure.
188 """
189 if self.oGuestSession is None:
190 if sName is None:
191 sName = "<untitled>";
192
193 reporter.log('Creating session "%s" ...' % (sName,));
194 try:
195 self.oGuestSession = self.oGuest.createSession(self.oCreds.sUser,
196 self.oCreds.sPassword,
197 self.oCreds.sDomain,
198 sName);
199 except:
200 # Just log, don't assume an error here (will be done in the main loop then).
201 reporter.maybeErrXcpt(fIsError, 'Creating a guest session "%s" failed; sUser="%s", pw="%s", sDomain="%s":'
202 % (sName, self.oCreds.sUser, self.oCreds.sPassword, self.oCreds.sDomain));
203 return (False, None);
204
205 tsStartMs = base.timestampMilli();
206 while base.timestampMilli() - tsStartMs < self.timeoutMS:
207 reporter.log('Waiting for session "%s" to start within %dms...' % (sName, self.timeoutMS));
208 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start, ];
209 try:
210 waitResult = self.oGuestSession.waitForArray(aeWaitFor, self.timeoutMS);
211
212 # Log session status changes.
213 if waitResult is vboxcon.GuestSessionWaitResult_Status:
214 reporter.log('Session "%s" indicated status change (status is now %d)' \
215 % (sName, self.oGuestSession.status));
216 if self.oGuestSession.status is vboxcon.GuestSessionStatus_Started:
217 # We indicate an error here, as we intentionally waited for the session start
218 # in the wait call above and got back a status change instead.
219 reporter.error('Session "%s" successfully started (thru status change)' % (sName,));
220 break;
221 continue; # Continue waiting for the session to start.
222
223 #
224 # Be nice to Guest Additions < 4.3: They don't support session handling and
225 # therefore return WaitFlagNotSupported.
226 #
227 if waitResult not in (vboxcon.GuestSessionWaitResult_Start, \
228 vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
229 # Just log, don't assume an error here (will be done in the main loop then).
230 reporter.maybeErr(fIsError, 'Session did not start successfully, returned wait result: %d' \
231 % (waitResult,));
232 return (False, None);
233 reporter.log('Session "%s" successfully started' % (sName,));
234
235 #
236 # Make sure that the test VM configuration and Guest Control use the same path separator style for the guest.
237 #
238 sGstSep = '\\' if self.oGuestSession.pathStyle is vboxcon.PathStyle_DOS else '/';
239 if self.oTestVm.pathSep() != sGstSep:
240 reporter.error('Configured test VM uses a different path style (%s) than Guest Control (%s)' \
241 % (self.oTestVm.pathSep(), sGstSep));
242 break;
243 except:
244 # Just log, don't assume an error here (will be done in the main loop then).
245 reporter.maybeErrXcpt(fIsError, 'Waiting for guest session "%s" (usr=%s;pw=%s;dom=%s) to start failed:'
246 % (sName, self.oCreds.sUser, self.oCreds.sPassword, self.oCreds.sDomain,));
247 return (False, None);
248 else:
249 reporter.log('Warning: Session already set; this is probably not what you want');
250 return (True, self.oGuestSession);
251
252 def setSession(self, oGuestSession):
253 """
254 Sets the current guest session and closes
255 an old one if necessary.
256 """
257 if self.oGuestSession is not None:
258 self.closeSession();
259 self.oGuestSession = oGuestSession;
260 return self.oGuestSession;
261
262 def closeSession(self, fIsError = True):
263 """
264 Closes the guest session.
265 """
266 if self.oGuestSession is not None:
267 try:
268 sName = self.oGuestSession.name;
269 except:
270 return reporter.errorXcpt();
271
272 reporter.log('Closing session "%s" ...' % (sName,));
273 try:
274 self.oGuestSession.close();
275 self.oGuestSession = None;
276 except:
277 # Just log, don't assume an error here (will be done in the main loop then).
278 reporter.maybeErrXcpt(fIsError, 'Closing guest session "%s" failed:' % (sName,));
279 return False;
280 return True;
281
282class tdTestCopyFrom(tdTestGuestCtrlBase):
283 """
284 Test for copying files from the guest to the host.
285 """
286 def __init__(self, sSrc = "", sDst = "", oCreds = None, afFlags = None, oSrc = None):
287 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
288 self.sSrc = sSrc;
289 self.sDst = sDst;
290 self.afFlags = afFlags;
291 self.oSrc = oSrc # type: testfileset.TestFsObj
292 if oSrc and not sSrc:
293 self.sSrc = oSrc.sPath;
294
295class tdTestCopyFromDir(tdTestCopyFrom):
296
297 def __init__(self, sSrc = "", sDst = "", oCreds = None, afFlags = None, oSrc = None, fIntoDst = False):
298 tdTestCopyFrom.__init__(self, sSrc, sDst, oCreds, afFlags, oSrc);
299 self.fIntoDst = fIntoDst; # hint to the verification code that sDst == oSrc, rather than sDst+oSrc.sNAme == oSrc.
300
301class tdTestCopyFromFile(tdTestCopyFrom):
302 pass;
303
304class tdTestRemoveHostDir(object):
305 """
306 Test step that removes a host directory tree.
307 """
308 def __init__(self, sDir):
309 self.sDir = sDir;
310
311 def execute(self, oTstDrv, oVmSession, oTxsSession, oTestVm, sMsgPrefix):
312 _ = oTstDrv; _ = oVmSession; _ = oTxsSession; _ = oTestVm; _ = sMsgPrefix;
313 if os.path.exists(self.sDir):
314 if base.wipeDirectory(self.sDir) != 0:
315 return False;
316 try:
317 os.rmdir(self.sDir);
318 except:
319 return reporter.errorXcpt('%s: sDir=%s' % (sMsgPrefix, self.sDir,));
320 return True;
321
322
323
324class tdTestCopyTo(tdTestGuestCtrlBase):
325 """
326 Test for copying files from the host to the guest.
327 """
328 def __init__(self, sSrc = "", sDst = "", oCreds = None, afFlags = None):
329 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
330 self.sSrc = sSrc;
331 self.sDst = sDst;
332 self.afFlags = afFlags;
333
334class tdTestCopyToFile(tdTestCopyTo):
335 pass;
336
337class tdTestCopyToDir(tdTestCopyTo):
338 pass;
339
340class tdTestDirCreate(tdTestGuestCtrlBase):
341 """
342 Test for directoryCreate call.
343 """
344 def __init__(self, sDirectory = "", oCreds = None, fMode = 0, afFlags = None):
345 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
346 self.sDirectory = sDirectory;
347 self.fMode = fMode;
348 self.afFlags = afFlags;
349
350class tdTestDirCreateTemp(tdTestGuestCtrlBase):
351 """
352 Test for the directoryCreateTemp call.
353 """
354 def __init__(self, sDirectory = "", sTemplate = "", oCreds = None, fMode = 0, fSecure = False):
355 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
356 self.sDirectory = sDirectory;
357 self.sTemplate = sTemplate;
358 self.fMode = fMode;
359 self.fSecure = fSecure;
360
361class tdTestDirOpen(tdTestGuestCtrlBase):
362 """
363 Test for the directoryOpen call.
364 """
365 def __init__(self, sDirectory = "", oCreds = None, sFilter = "", afFlags = None):
366 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
367 self.sDirectory = sDirectory;
368 self.sFilter = sFilter;
369 self.afFlags = afFlags or [];
370
371class tdTestDirRead(tdTestDirOpen):
372 """
373 Test for the opening, reading and closing a certain directory.
374 """
375 def __init__(self, sDirectory = "", oCreds = None, sFilter = "", afFlags = None):
376 tdTestDirOpen.__init__(self, sDirectory, oCreds, sFilter, afFlags);
377
378class tdTestExec(tdTestGuestCtrlBase):
379 """
380 Specifies exactly one guest control execution test.
381 Has a default timeout of 5 minutes (for safety).
382 """
383 def __init__(self, sCmd = "", sCwd = "", asArgs = None, aEnv = None, afFlags = None, # pylint: disable=too-many-arguments
384 timeoutMS = 5 * 60 * 1000, oCreds = None, fWaitForExit = True):
385 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
386 self.sCmd = sCmd;
387 self.sCwd = sCwd;
388 self.asArgs = asArgs if asArgs is not None else [sCmd,];
389 self.aEnv = aEnv;
390 self.afFlags = afFlags or [];
391 self.timeoutMS = timeoutMS;
392 self.fWaitForExit = fWaitForExit;
393 self.uExitStatus = 0;
394 self.iExitCode = 0;
395 self.cbStdOut = 0;
396 self.cbStdErr = 0;
397 self.sBuf = '';
398
399class tdTestFileExists(tdTestGuestCtrlBase):
400 """
401 Test for the file exists API call (fileExists).
402 """
403 def __init__(self, sFile = "", oCreds = None):
404 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
405 self.sFile = sFile;
406
407class tdTestFileRemove(tdTestGuestCtrlBase):
408 """
409 Test querying guest file information.
410 """
411 def __init__(self, sFile = "", oCreds = None):
412 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
413 self.sFile = sFile;
414
415class tdTestRemoveBase(tdTestGuestCtrlBase):
416 """
417 Removal base.
418 """
419 def __init__(self, sPath, fRcExpect = True, oCreds = None):
420 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
421 self.sPath = sPath;
422 self.fRcExpect = fRcExpect;
423
424 def execute(self, oSubTstDrv):
425 """
426 Executes the test, returns True/False.
427 """
428 _ = oSubTstDrv;
429 return True;
430
431 def checkRemoved(self, sType):
432 """ Check that the object was removed using fObjExists. """
433 try:
434 fExists = self.oGuestSession.fsObjExists(self.sPath, False);
435 except:
436 return reporter.errorXcpt('fsObjExists failed on "%s" after deletion (type: %s)' % (self.sPath, sType));
437 if fExists:
438 return reporter.error('fsObjExists says "%s" still exists after deletion (type: %s)!' % (self.sPath, sType));
439 return True;
440
441class tdTestRemoveFile(tdTestRemoveBase):
442 """
443 Remove a single file.
444 """
445 def __init__(self, sPath, fRcExpect = True, oCreds = None):
446 tdTestRemoveBase.__init__(self, sPath, fRcExpect, oCreds);
447
448 def execute(self, oSubTstDrv):
449 reporter.log2('Deleting file "%s" ...' % (limitString(self.sPath),));
450 try:
451 if oSubTstDrv.oTstDrv.fpApiVer >= 5.0:
452 self.oGuestSession.fsObjRemove(self.sPath);
453 else:
454 self.oGuestSession.fileRemove(self.sPath);
455 except:
456 reporter.maybeErrXcpt(self.fRcExpect, 'Removing "%s" failed' % (self.sPath,));
457 return not self.fRcExpect;
458 if not self.fRcExpect:
459 return reporter.error('Expected removing "%s" to failed, but it succeeded' % (self.sPath,));
460
461 return self.checkRemoved('file');
462
463class tdTestRemoveDir(tdTestRemoveBase):
464 """
465 Remove a single directory if empty.
466 """
467 def __init__(self, sPath, fRcExpect = True, oCreds = None):
468 tdTestRemoveBase.__init__(self, sPath, fRcExpect, oCreds);
469
470 def execute(self, oSubTstDrv):
471 _ = oSubTstDrv;
472 reporter.log2('Deleting directory "%s" ...' % (limitString(self.sPath),));
473 try:
474 self.oGuestSession.directoryRemove(self.sPath);
475 except:
476 reporter.maybeErrXcpt(self.fRcExpect, 'Removing "%s" (as a directory) failed' % (self.sPath,));
477 return not self.fRcExpect;
478 if not self.fRcExpect:
479 return reporter.error('Expected removing "%s" (dir) to failed, but it succeeded' % (self.sPath,));
480
481 return self.checkRemoved('directory');
482
483class tdTestRemoveTree(tdTestRemoveBase):
484 """
485 Recursively remove a directory tree.
486 """
487 def __init__(self, sPath, afFlags = None, fRcExpect = True, fNotExist = False, oCreds = None):
488 tdTestRemoveBase.__init__(self, sPath, fRcExpect, oCreds = None);
489 self.afFlags = afFlags if afFlags is not None else [];
490 self.fNotExist = fNotExist; # Hack for the ContentOnly scenario where the dir does not exist.
491
492 def execute(self, oSubTstDrv):
493 reporter.log2('Deleting tree "%s" ...' % (limitString(self.sPath),));
494 try:
495 oProgress = self.oGuestSession.directoryRemoveRecursive(self.sPath, self.afFlags);
496 except:
497 reporter.maybeErrXcpt(self.fRcExpect, 'Removing directory tree "%s" failed (afFlags=%s)'
498 % (self.sPath, self.afFlags));
499 return not self.fRcExpect;
500
501 oWrappedProgress = vboxwrappers.ProgressWrapper(oProgress, oSubTstDrv.oTstDrv.oVBoxMgr, oSubTstDrv.oTstDrv,
502 "remove-tree: %s" % (self.sPath,));
503 oWrappedProgress.wait();
504 if not oWrappedProgress.isSuccess():
505 oWrappedProgress.logResult(fIgnoreErrors = not self.fRcExpect);
506 return not self.fRcExpect;
507 if not self.fRcExpect:
508 return reporter.error('Expected removing "%s" (tree) to failed, but it succeeded' % (self.sPath,));
509
510 if vboxcon.DirectoryRemoveRecFlag_ContentAndDir not in self.afFlags and not self.fNotExist:
511 # Cannot use directoryExists here as it is buggy.
512 try:
513 if oSubTstDrv.oTstDrv.fpApiVer >= 5.0:
514 oFsObjInfo = self.oGuestSession.fsObjQueryInfo(self.sPath, False);
515 else:
516 oFsObjInfo = self.oGuestSession.fileQueryInfo(self.sPath);
517 eType = oFsObjInfo.type;
518 except:
519 return reporter.errorXcpt('sPath=%s' % (self.sPath,));
520 if eType != vboxcon.FsObjType_Directory:
521 return reporter.error('Found file type %d, expected directory (%d) for %s after rmtree/OnlyContent'
522 % (eType, vboxcon.FsObjType_Directory, self.sPath,));
523 return True;
524
525 return self.checkRemoved('tree');
526
527
528class tdTestFileStat(tdTestGuestCtrlBase):
529 """
530 Test querying guest file information.
531 """
532 def __init__(self, sFile = "", oCreds = None, cbSize = 0, eFileType = 0):
533 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
534 self.sFile = sFile;
535 self.cbSize = cbSize;
536 self.eFileType = eFileType;
537
538class tdTestFileIO(tdTestGuestCtrlBase):
539 """
540 Test for the IGuestFile object.
541 """
542 def __init__(self, sFile = "", oCreds = None):
543 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
544 self.sFile = sFile;
545
546class tdTestFileQuerySize(tdTestGuestCtrlBase):
547 """
548 Test for the file size query API call (fileQuerySize).
549 """
550 def __init__(self, sFile = "", oCreds = None):
551 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
552 self.sFile = sFile;
553
554class tdTestFileOpen(tdTestGuestCtrlBase):
555 """
556 Tests opening a guest files.
557 """
558 def __init__(self, sFile = "", eAccessMode = None, eAction = None, eSharing = None,
559 fCreationMode = 0o660, oCreds = None):
560 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
561 self.sFile = sFile;
562 self.eAccessMode = eAccessMode if eAccessMode is not None else vboxcon.FileAccessMode_ReadOnly;
563 self.eAction = eAction if eAction is not None else vboxcon.FileOpenAction_OpenExisting;
564 self.eSharing = eSharing if eSharing is not None else vboxcon.FileSharingMode_All;
565 self.fCreationMode = fCreationMode;
566 self.afOpenFlags = [];
567 self.oOpenedFile = None;
568
569 def toString(self):
570 """ Get a summary string. """
571 return 'eAccessMode=%s eAction=%s sFile=%s' % (self.eAccessMode, self.eAction, self.sFile);
572
573 def doOpenStep(self, fExpectSuccess):
574 """
575 Does the open step, putting the resulting file in oOpenedFile.
576 """
577 try:
578 self.oOpenedFile = self.oGuestSession.fileOpenEx(self.sFile, self.eAccessMode, self.eAction,
579 self.eSharing, self.fCreationMode, self.afOpenFlags);
580 except:
581 reporter.maybeErrXcpt(fExpectSuccess, 'fileOpenEx(%s, %s, %s, %s, %s, %s)'
582 % (self.sFile, self.eAccessMode, self.eAction, self.eSharing,
583 self.fCreationMode, self.afOpenFlags,));
584 return False;
585 return True;
586
587 def doStepsOnOpenedFile(self, fExpectSuccess, oSubTst):
588 """ Overridden by children to do more testing. """
589 _ = fExpectSuccess; _ = oSubTst;
590 return True;
591
592 def doCloseStep(self):
593 """ Closes the file. """
594 if self.oOpenedFile:
595 try:
596 self.oOpenedFile.close();
597 except:
598 return reporter.errorXcpt('close([%s, %s, %s, %s, %s, %s])'
599 % (self.sFile, self.eAccessMode, self.eAction, self.eSharing,
600 self.fCreationMode, self.afOpenFlags,));
601 self.oOpenedFile = None;
602 return True;
603
604 def doSteps(self, fExpectSuccess, oSubTst):
605 """ Do the tests. """
606 fRc = self.doOpenStep(fExpectSuccess);
607 if fRc is True:
608 fRc = self.doStepsOnOpenedFile(fExpectSuccess, oSubTst);
609 if self.oOpenedFile:
610 fRc = self.doCloseStep() and fRc;
611 return fRc;
612
613
614class tdTestFileOpenCheckSize(tdTestFileOpen):
615 """
616 Opens a file and checks the size.
617 """
618 def __init__(self, sFile = "", eAccessMode = None, eAction = None, eSharing = None,
619 fCreationMode = 0o660, cbOpenExpected = 0, oCreds = None):
620 tdTestFileOpen.__init__(self, sFile, eAccessMode, eAction, eSharing, fCreationMode, oCreds);
621 self.cbOpenExpected = cbOpenExpected;
622
623 def toString(self):
624 return 'cbOpenExpected=%s %s' % (self.cbOpenExpected, tdTestFileOpen.toString(self),);
625
626 def doStepsOnOpenedFile(self, fExpectSuccess, oSubTst):
627 #
628 # Call parent.
629 #
630 fRc = tdTestFileOpen.doStepsOnOpenedFile(self, fExpectSuccess, oSubTst);
631
632 #
633 # Check the size. Requires 6.0 or later (E_NOTIMPL in 5.2).
634 #
635 if oSubTst.oTstDrv.fpApiVer >= 6.0:
636 try:
637 oFsObjInfo = self.oOpenedFile.queryInfo();
638 except:
639 return reporter.errorXcpt('queryInfo([%s, %s, %s, %s, %s, %s])'
640 % (self.sFile, self.eAccessMode, self.eAction, self.eSharing,
641 self.fCreationMode, self.afOpenFlags,));
642 if oFsObjInfo is None:
643 return reporter.error('IGuestFile::queryInfo returned None');
644 try:
645 cbFile = oFsObjInfo.objectSize;
646 except:
647 return reporter.errorXcpt();
648 if cbFile != self.cbOpenExpected:
649 return reporter.error('Wrong file size after open (%d): %s, expected %s (file %s) (#1)'
650 % (self.eAction, cbFile, self.cbOpenExpected, self.sFile));
651
652 try:
653 cbFile = self.oOpenedFile.querySize();
654 except:
655 return reporter.errorXcpt('querySize([%s, %s, %s, %s, %s, %s])'
656 % (self.sFile, self.eAccessMode, self.eAction, self.eSharing,
657 self.fCreationMode, self.afOpenFlags,));
658 if cbFile != self.cbOpenExpected:
659 return reporter.error('Wrong file size after open (%d): %s, expected %s (file %s) (#2)'
660 % (self.eAction, cbFile, self.cbOpenExpected, self.sFile));
661
662 return fRc;
663
664
665class tdTestFileOpenAndWrite(tdTestFileOpen):
666 """
667 Opens the file and writes one or more chunks to it.
668
669 The chunks are a list of tuples(offset, bytes), where offset can be None
670 if no seeking should be performed.
671 """
672 def __init__(self, sFile = "", eAccessMode = None, eAction = None, eSharing = None, # pylint: disable=too-many-arguments
673 fCreationMode = 0o660, atChunks = None, fUseAtApi = False, abContent = None, oCreds = None):
674 tdTestFileOpen.__init__(self, sFile, eAccessMode if eAccessMode is not None else vboxcon.FileAccessMode_WriteOnly,
675 eAction, eSharing, fCreationMode, oCreds);
676 assert atChunks is not None;
677 self.atChunks = atChunks # type: list(tuple(int,bytearray))
678 self.fUseAtApi = fUseAtApi;
679 self.fAppend = ( eAccessMode in (vboxcon.FileAccessMode_AppendOnly, vboxcon.FileAccessMode_AppendRead)
680 or eAction == vboxcon.FileOpenAction_AppendOrCreate);
681 self.abContent = abContent # type: bytearray
682
683 def toString(self):
684 sChunks = ', '.join('%s LB %s' % (tChunk[0], len(tChunk[1]),) for tChunk in self.atChunks);
685 sApi = 'writeAt' if self.fUseAtApi else 'write';
686 return '%s [%s] %s' % (sApi, sChunks, tdTestFileOpen.toString(self),);
687
688 def doStepsOnOpenedFile(self, fExpectSuccess, oSubTst):
689 #
690 # Call parent.
691 #
692 fRc = tdTestFileOpen.doStepsOnOpenedFile(self, fExpectSuccess, oSubTst);
693
694 #
695 # Do the writing.
696 #
697 for offFile, abBuf in self.atChunks:
698 if self.fUseAtApi:
699 #
700 # writeAt:
701 #
702 assert offFile is not None;
703 reporter.log2('writeAt(%s, %s bytes)' % (offFile, len(abBuf),));
704 if self.fAppend:
705 if self.abContent is not None: # Try avoid seek as it updates the cached offset in GuestFileImpl.
706 offExpectAfter = len(self.abContent);
707 else:
708 try:
709 offSave = self.oOpenedFile.seek(0, vboxcon.FileSeekOrigin_Current);
710 offExpectAfter = self.oOpenedFile.seek(0, vboxcon.FileSeekOrigin_End);
711 self.oOpenedFile.seek(offSave, vboxcon.FileSeekOrigin_Begin);
712 except:
713 return reporter.errorXcpt();
714 offExpectAfter += len(abBuf);
715 else:
716 offExpectAfter = offFile + len(abBuf);
717
718 try:
719 cbWritten = self.oOpenedFile.writeAt(offFile, abBuf, 30*1000);
720 except:
721 return reporter.errorXcpt('writeAt(%s, %s bytes)' % (offFile, len(abBuf),));
722
723 else:
724 #
725 # write:
726 #
727 if self.fAppend:
728 if self.abContent is not None: # Try avoid seek as it updates the cached offset in GuestFileImpl.
729 offExpectAfter = len(self.abContent);
730 else:
731 try:
732 offSave = self.oOpenedFile.seek(0, vboxcon.FileSeekOrigin_Current);
733 offExpectAfter = self.oOpenedFile.seek(0, vboxcon.FileSeekOrigin_End);
734 self.oOpenedFile.seek(offSave, vboxcon.FileSeekOrigin_Begin);
735 except:
736 return reporter.errorXcpt('seek(0,End)');
737 if offFile is not None:
738 try:
739 self.oOpenedFile.seek(offFile, vboxcon.FileSeekOrigin_Begin);
740 except:
741 return reporter.errorXcpt('seek(%s,Begin)' % (offFile,));
742 else:
743 try:
744 offFile = self.oOpenedFile.seek(0, vboxcon.FileSeekOrigin_Current);
745 except:
746 return reporter.errorXcpt();
747 if not self.fAppend:
748 offExpectAfter = offFile;
749 offExpectAfter += len(abBuf);
750
751 reporter.log2('write(%s bytes @ %s)' % (len(abBuf), offFile,));
752 try:
753 cbWritten = self.oOpenedFile.write(abBuf, 30*1000);
754 except:
755 return reporter.errorXcpt('write(%s bytes @ %s)' % (len(abBuf), offFile));
756
757 #
758 # Check how much was written, ASSUMING nothing we push thru here is too big:
759 #
760 if cbWritten != len(abBuf):
761 fRc = reporter.errorXcpt('Wrote less than expected: %s out of %s, expected all to be written'
762 % (cbWritten, len(abBuf),));
763 if not self.fAppend:
764 offExpectAfter -= len(abBuf) - cbWritten;
765
766 #
767 # Update the file content tracker if we've got one and can:
768 #
769 if self.abContent is not None:
770 if cbWritten < len(abBuf):
771 abBuf = abBuf[:cbWritten];
772
773 #
774 # In append mode, the current file offset shall be disregarded and the
775 # write always goes to the end of the file, regardless of writeAt or write.
776 # Note that RTFileWriteAt only naturally behaves this way on linux and
777 # (probably) windows, so VBoxService makes that behaviour generic across
778 # all OSes.
779 #
780 if self.fAppend:
781 reporter.log2('len(self.abContent)=%s + %s' % (len(self.abContent), cbWritten, ));
782 self.abContent.extend(abBuf);
783 else:
784 if offFile is None:
785 offFile = offExpectAfter - cbWritten;
786 reporter.log2('len(self.abContent)=%s + %s @ %s' % (len(self.abContent), cbWritten, offFile, ));
787 if offFile > len(self.abContent):
788 self.abContent.extend(bytearray(offFile - len(self.abContent)));
789 self.abContent[offFile:offFile + cbWritten] = abBuf;
790 reporter.log2('len(self.abContent)=%s' % (len(self.abContent),));
791
792 #
793 # Check the resulting file offset with IGuestFile::offset.
794 #
795 try:
796 offApi = self.oOpenedFile.offset; # Must be gotten first!
797 offSeek = self.oOpenedFile.seek(0, vboxcon.FileSeekOrigin_Current);
798 except:
799 fRc = reporter.errorXcpt();
800 else:
801 reporter.log2('offApi=%s offSeek=%s offExpectAfter=%s' % (offApi, offSeek, offExpectAfter,));
802 if offSeek != offExpectAfter:
803 fRc = reporter.error('Seek offset is %s, expected %s after %s bytes write @ %s (offApi=%s)'
804 % (offSeek, offExpectAfter, len(abBuf), offFile, offApi,));
805 if offApi != offExpectAfter:
806 fRc = reporter.error('IGuestFile::offset is %s, expected %s after %s bytes write @ %s (offSeek=%s)'
807 % (offApi, offExpectAfter, len(abBuf), offFile, offSeek,));
808 # for each chunk - end
809 return fRc;
810
811
812class tdTestFileOpenAndCheckContent(tdTestFileOpen):
813 """
814 Opens the file and checks the content using the read API.
815 """
816 def __init__(self, sFile = "", eSharing = None, abContent = None, cbContentExpected = None, oCreds = None):
817 tdTestFileOpen.__init__(self, sFile = sFile, eSharing = eSharing, oCreds = oCreds);
818 self.abContent = abContent # type: bytearray
819 self.cbContentExpected = cbContentExpected;
820
821 def toString(self):
822 return 'check content %s (%s) %s' % (len(self.abContent), self.cbContentExpected, tdTestFileOpen.toString(self),);
823
824 def doStepsOnOpenedFile(self, fExpectSuccess, oSubTst):
825 #
826 # Call parent.
827 #
828 fRc = tdTestFileOpen.doStepsOnOpenedFile(self, fExpectSuccess, oSubTst);
829
830 #
831 # Check the expected content size.
832 #
833 if self.cbContentExpected is not None:
834 if len(self.abContent) != self.cbContentExpected:
835 fRc = reporter.error('Incorrect abContent size: %s, expected %s'
836 % (len(self.abContent), self.cbContentExpected,));
837
838 #
839 # Read the file and compare it with the content.
840 #
841 offFile = 0;
842 while True:
843 try:
844 abChunk = self.oOpenedFile.read(512*1024, 30*1000);
845 except:
846 return reporter.errorXcpt('read(512KB) @ %s' % (offFile,));
847 cbChunk = len(abChunk);
848 if cbChunk == 0:
849 if offFile != len(self.abContent):
850 fRc = reporter.error('Unexpected EOF @ %s, len(abContent)=%s' % (offFile, len(self.abContent),));
851 break;
852 if offFile + cbChunk > len(self.abContent):
853 fRc = reporter.error('File is larger than expected: at least %s bytes, expected %s bytes'
854 % (offFile + cbChunk, len(self.abContent),));
855 elif not utils.areBytesEqual(abChunk, self.abContent[offFile:(offFile + cbChunk)]):
856 fRc = reporter.error('Mismatch in range %s LB %s!' % (offFile, cbChunk,));
857 offFile += cbChunk;
858
859 return fRc;
860
861
862class tdTestSession(tdTestGuestCtrlBase):
863 """
864 Test the guest session handling.
865 """
866 def __init__(self, sUser = None, sPassword = None, sDomain = None, sSessionName = ""):
867 tdTestGuestCtrlBase.__init__(self, oCreds = tdCtxCreds(sUser, sPassword, sDomain));
868 self.sSessionName = sSessionName;
869
870 def getSessionCount(self, oVBoxMgr):
871 """
872 Helper for returning the number of currently
873 opened guest sessions of a VM.
874 """
875 if self.oGuest is None:
876 return 0;
877 try:
878 aoSession = oVBoxMgr.getArray(self.oGuest, 'sessions')
879 except:
880 reporter.errorXcpt('sSessionName: %s' % (self.sSessionName,));
881 return 0;
882 return len(aoSession);
883
884
885class tdTestSessionEx(tdTestGuestCtrlBase):
886 """
887 Test the guest session.
888 """
889 def __init__(self, aoSteps = None, enmUser = None):
890 tdTestGuestCtrlBase.__init__(self);
891 assert enmUser is None; # For later.
892 self.enmUser = enmUser;
893 self.aoSteps = aoSteps if aoSteps is not None else [];
894
895 def execute(self, oTstDrv, oVmSession, oTxsSession, oTestVm, sMsgPrefix):
896 """
897 Executes the test.
898 """
899 #
900 # Create a session.
901 #
902 assert self.enmUser is None; # For later.
903 self.oCreds = tdCtxCreds();
904 fRc = self.setEnvironment(oVmSession, oTxsSession, oTestVm);
905 if not fRc:
906 return False;
907 reporter.log2('%s: %s steps' % (sMsgPrefix, len(self.aoSteps),));
908 fRc, oCurSession = self.createSession(sMsgPrefix);
909 if fRc is True:
910 #
911 # Execute the tests.
912 #
913 try:
914 fRc = self.executeSteps(oTstDrv, oCurSession, sMsgPrefix);
915 except:
916 fRc = reporter.errorXcpt('%s: Unexpected exception executing test steps' % (sMsgPrefix,));
917
918 #
919 # Close the session.
920 #
921 fRc2 = self.closeSession();
922 if fRc2 is False:
923 fRc = reporter.error('%s: Session could not be closed' % (sMsgPrefix,));
924 else:
925 fRc = reporter.error('%s: Session creation failed' % (sMsgPrefix,));
926 return fRc;
927
928 def executeSteps(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
929 """
930 Executes just the steps.
931 Returns True on success, False on test failure.
932 """
933 fRc = True;
934 for (i, oStep) in enumerate(self.aoSteps):
935 fRc2 = oStep.execute(oTstDrv, oGstCtrlSession, sMsgPrefix + ', step #%d' % i);
936 if fRc2 is True:
937 pass;
938 elif fRc2 is None:
939 reporter.log('%s: skipping remaining %d steps' % (sMsgPrefix, len(self.aoSteps) - i - 1,));
940 break;
941 else:
942 fRc = False;
943 return fRc;
944
945 @staticmethod
946 def executeListTestSessions(aoTests, oTstDrv, oVmSession, oTxsSession, oTestVm, sMsgPrefix):
947 """
948 Works thru a list of tdTestSessionEx object.
949 """
950 fRc = True;
951 for (i, oCurTest) in enumerate(aoTests):
952 try:
953 fRc2 = oCurTest.execute(oTstDrv, oVmSession, oTxsSession, oTestVm, '%s / %#d' % (sMsgPrefix, i,));
954 if fRc2 is not True:
955 fRc = False;
956 except:
957 fRc = reporter.errorXcpt('%s: Unexpected exception executing test #%d' % (sMsgPrefix, i ,));
958
959 return (fRc, oTxsSession);
960
961
962class tdSessionStepBase(object):
963 """
964 Base class for the guest control session test steps.
965 """
966
967 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
968 """
969 Executes the test step.
970
971 Returns True on success.
972 Returns False on failure (must be reported as error).
973 Returns None if to skip the remaining steps.
974 """
975 _ = oTstDrv;
976 _ = oGstCtrlSession;
977 return reporter.error('%s: Missing execute implementation: %s' % (sMsgPrefix, self,));
978
979
980class tdStepRequireMinimumApiVer(tdSessionStepBase):
981 """
982 Special test step which will cause executeSteps to skip the remaining step
983 if the VBox API is too old:
984 """
985 def __init__(self, fpMinApiVer):
986 self.fpMinApiVer = fpMinApiVer;
987
988 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
989 """ Returns None if API version is too old, otherwise True. """
990 if oTstDrv.fpApiVer >= self.fpMinApiVer:
991 return True;
992 _ = oGstCtrlSession;
993 _ = sMsgPrefix;
994 return None; # Special return value. Don't use elsewhere.
995
996
997#
998# Scheduling Environment Changes with the Guest Control Session.
999#
1000
1001class tdStepSessionSetEnv(tdSessionStepBase):
1002 """
1003 Guest session environment: schedule putenv
1004 """
1005 def __init__(self, sVar, sValue, hrcExpected = 0):
1006 self.sVar = sVar;
1007 self.sValue = sValue;
1008 self.hrcExpected = hrcExpected;
1009
1010 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
1011 """
1012 Executes the step.
1013 Returns True on success, False on test failure.
1014 """
1015 reporter.log2('tdStepSessionSetEnv: sVar=%s sValue=%s hrcExpected=%#x' % (self.sVar, self.sValue, self.hrcExpected,));
1016 try:
1017 if oTstDrv.fpApiVer >= 5.0:
1018 oGstCtrlSession.environmentScheduleSet(self.sVar, self.sValue);
1019 else:
1020 oGstCtrlSession.environmentSet(self.sVar, self.sValue);
1021 except vbox.ComException as oXcpt:
1022 # Is this an expected failure?
1023 if vbox.ComError.equal(oXcpt, self.hrcExpected):
1024 return True;
1025 return reporter.errorXcpt('%s: Expected hrc=%#x (%s) got %#x (%s) instead (setenv %s=%s)'
1026 % (sMsgPrefix, self.hrcExpected, vbox.ComError.toString(self.hrcExpected),
1027 vbox.ComError.getXcptResult(oXcpt),
1028 vbox.ComError.toString(vbox.ComError.getXcptResult(oXcpt)),
1029 self.sVar, self.sValue,));
1030 except:
1031 return reporter.errorXcpt('%s: Unexpected exception in tdStepSessionSetEnv::execute (%s=%s)'
1032 % (sMsgPrefix, self.sVar, self.sValue,));
1033
1034 # Should we succeed?
1035 if self.hrcExpected != 0:
1036 return reporter.error('%s: Expected hrcExpected=%#x, got S_OK (putenv %s=%s)'
1037 % (sMsgPrefix, self.hrcExpected, self.sVar, self.sValue,));
1038 return True;
1039
1040class tdStepSessionUnsetEnv(tdSessionStepBase):
1041 """
1042 Guest session environment: schedule unset.
1043 """
1044 def __init__(self, sVar, hrcExpected = 0):
1045 self.sVar = sVar;
1046 self.hrcExpected = hrcExpected;
1047
1048 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
1049 """
1050 Executes the step.
1051 Returns True on success, False on test failure.
1052 """
1053 reporter.log2('tdStepSessionUnsetEnv: sVar=%s hrcExpected=%#x' % (self.sVar, self.hrcExpected,));
1054 try:
1055 if oTstDrv.fpApiVer >= 5.0:
1056 oGstCtrlSession.environmentScheduleUnset(self.sVar);
1057 else:
1058 oGstCtrlSession.environmentUnset(self.sVar);
1059 except vbox.ComException as oXcpt:
1060 # Is this an expected failure?
1061 if vbox.ComError.equal(oXcpt, self.hrcExpected):
1062 return True;
1063 return reporter.errorXcpt('%s: Expected hrc=%#x (%s) got %#x (%s) instead (unsetenv %s)'
1064 % (sMsgPrefix, self.hrcExpected, vbox.ComError.toString(self.hrcExpected),
1065 vbox.ComError.getXcptResult(oXcpt),
1066 vbox.ComError.toString(vbox.ComError.getXcptResult(oXcpt)),
1067 self.sVar,));
1068 except:
1069 return reporter.errorXcpt('%s: Unexpected exception in tdStepSessionUnsetEnv::execute (%s)'
1070 % (sMsgPrefix, self.sVar,));
1071
1072 # Should we succeed?
1073 if self.hrcExpected != 0:
1074 return reporter.error('%s: Expected hrcExpected=%#x, got S_OK (unsetenv %s)'
1075 % (sMsgPrefix, self.hrcExpected, self.sVar,));
1076 return True;
1077
1078class tdStepSessionBulkEnv(tdSessionStepBase):
1079 """
1080 Guest session environment: Bulk environment changes.
1081 """
1082 def __init__(self, asEnv = None, hrcExpected = 0):
1083 self.asEnv = asEnv if asEnv is not None else [];
1084 self.hrcExpected = hrcExpected;
1085
1086 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
1087 """
1088 Executes the step.
1089 Returns True on success, False on test failure.
1090 """
1091 reporter.log2('tdStepSessionBulkEnv: asEnv=%s hrcExpected=%#x' % (self.asEnv, self.hrcExpected,));
1092 try:
1093 if oTstDrv.fpApiVer >= 5.0:
1094 oTstDrv.oVBoxMgr.setArray(oGstCtrlSession, 'environmentChanges', self.asEnv);
1095 else:
1096 oTstDrv.oVBoxMgr.setArray(oGstCtrlSession, 'environment', self.asEnv);
1097 except vbox.ComException as oXcpt:
1098 # Is this an expected failure?
1099 if vbox.ComError.equal(oXcpt, self.hrcExpected):
1100 return True;
1101 return reporter.errorXcpt('%s: Expected hrc=%#x (%s) got %#x (%s) instead (asEnv=%s)'
1102 % (sMsgPrefix, self.hrcExpected, vbox.ComError.toString(self.hrcExpected),
1103 vbox.ComError.getXcptResult(oXcpt),
1104 vbox.ComError.toString(vbox.ComError.getXcptResult(oXcpt)),
1105 self.asEnv,));
1106 except:
1107 return reporter.errorXcpt('%s: Unexpected exception writing the environmentChanges property (asEnv=%s).'
1108 % (sMsgPrefix, self.asEnv));
1109 return True;
1110
1111class tdStepSessionClearEnv(tdStepSessionBulkEnv):
1112 """
1113 Guest session environment: clears the scheduled environment changes.
1114 """
1115 def __init__(self):
1116 tdStepSessionBulkEnv.__init__(self);
1117
1118
1119class tdStepSessionCheckEnv(tdSessionStepBase):
1120 """
1121 Check the currently scheduled environment changes of a guest control session.
1122 """
1123 def __init__(self, asEnv = None):
1124 self.asEnv = asEnv if asEnv is not None else [];
1125
1126 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
1127 """
1128 Executes the step.
1129 Returns True on success, False on test failure.
1130 """
1131 reporter.log2('tdStepSessionCheckEnv: asEnv=%s' % (self.asEnv,));
1132
1133 #
1134 # Get the environment change list.
1135 #
1136 try:
1137 if oTstDrv.fpApiVer >= 5.0:
1138 asCurEnv = oTstDrv.oVBoxMgr.getArray(oGstCtrlSession, 'environmentChanges');
1139 else:
1140 asCurEnv = oTstDrv.oVBoxMgr.getArray(oGstCtrlSession, 'environment');
1141 except:
1142 return reporter.errorXcpt('%s: Unexpected exception reading the environmentChanges property.' % (sMsgPrefix,));
1143
1144 #
1145 # Compare it with the expected one by trying to remove each expected value
1146 # and the list anything unexpected.
1147 #
1148 fRc = True;
1149 asCopy = list(asCurEnv); # just in case asCurEnv is immutable
1150 for sExpected in self.asEnv:
1151 try:
1152 asCopy.remove(sExpected);
1153 except:
1154 fRc = reporter.error('%s: Expected "%s" to be in the resulting environment' % (sMsgPrefix, sExpected,));
1155 for sUnexpected in asCopy:
1156 fRc = reporter.error('%s: Unexpected "%s" in the resulting environment' % (sMsgPrefix, sUnexpected,));
1157
1158 if fRc is not True:
1159 reporter.log2('%s: Current environment: %s' % (sMsgPrefix, asCurEnv));
1160 return fRc;
1161
1162
1163#
1164# File system object statistics (i.e. stat()).
1165#
1166
1167class tdStepStat(tdSessionStepBase):
1168 """
1169 Stats a file system object.
1170 """
1171 def __init__(self, sPath, hrcExpected = 0, fFound = True, fFollowLinks = True, enmType = None, oTestFsObj = None):
1172 self.sPath = sPath;
1173 self.hrcExpected = hrcExpected;
1174 self.fFound = fFound;
1175 self.fFollowLinks = fFollowLinks;
1176 self.enmType = enmType if enmType is not None else vboxcon.FsObjType_File;
1177 self.cbExactSize = None;
1178 self.cbMinSize = None;
1179 self.oTestFsObj = oTestFsObj # type: testfileset.TestFsObj
1180
1181 def execute(self, oTstDrv, oGstCtrlSession, sMsgPrefix):
1182 """
1183 Execute the test step.
1184 """
1185 reporter.log2('tdStepStat: sPath=%s enmType=%s hrcExpected=%s fFound=%s fFollowLinks=%s'
1186 % (limitString(self.sPath), self.enmType, self.hrcExpected, self.fFound, self.fFollowLinks,));
1187
1188 # Don't execute non-file tests on older VBox version.
1189 if oTstDrv.fpApiVer >= 5.0 or self.enmType == vboxcon.FsObjType_File or not self.fFound:
1190 #
1191 # Call the API.
1192 #
1193 try:
1194 if oTstDrv.fpApiVer >= 5.0:
1195 oFsInfo = oGstCtrlSession.fsObjQueryInfo(self.sPath, self.fFollowLinks);
1196 else:
1197 oFsInfo = oGstCtrlSession.fileQueryInfo(self.sPath);
1198 except vbox.ComException as oXcpt:
1199 ## @todo: The error reporting in the API just plain sucks! Most of the errors are
1200 ## VBOX_E_IPRT_ERROR and there seems to be no way to distinguish between
1201 ## non-existing files/path and a lot of other errors. Fix API and test!
1202 if not self.fFound:
1203 return True;
1204 if vbox.ComError.equal(oXcpt, self.hrcExpected): # Is this an expected failure?
1205 return True;
1206 return reporter.errorXcpt('%s: Unexpected exception for exiting path "%s" (enmType=%s, hrcExpected=%s):'
1207 % (sMsgPrefix, self.sPath, self.enmType, self.hrcExpected,));
1208 except:
1209 return reporter.errorXcpt('%s: Unexpected exception in tdStepStat::execute (%s)'
1210 % (sMsgPrefix, self.sPath,));
1211 if oFsInfo is None:
1212 return reporter.error('%s: "%s" got None instead of IFsObjInfo instance!' % (sMsgPrefix, self.sPath,));
1213
1214 #
1215 # Check type expectations.
1216 #
1217 try:
1218 enmType = oFsInfo.type;
1219 except:
1220 return reporter.errorXcpt('%s: Unexpected exception in reading "IFsObjInfo::type"' % (sMsgPrefix,));
1221 if enmType != self.enmType:
1222 return reporter.error('%s: "%s" has type %s, expected %s'
1223 % (sMsgPrefix, self.sPath, enmType, self.enmType));
1224
1225 #
1226 # Check size expectations.
1227 # Note! This is unicode string here on windows, for some reason.
1228 # long long mapping perhaps?
1229 #
1230 try:
1231 cbObject = long(oFsInfo.objectSize);
1232 except:
1233 return reporter.errorXcpt('%s: Unexpected exception in reading "IFsObjInfo::objectSize"'
1234 % (sMsgPrefix,));
1235 if self.cbExactSize is not None \
1236 and cbObject != self.cbExactSize:
1237 return reporter.error('%s: "%s" has size %s bytes, expected %s bytes'
1238 % (sMsgPrefix, self.sPath, cbObject, self.cbExactSize));
1239 if self.cbMinSize is not None \
1240 and cbObject < self.cbMinSize:
1241 return reporter.error('%s: "%s" has size %s bytes, expected as least %s bytes'
1242 % (sMsgPrefix, self.sPath, cbObject, self.cbMinSize));
1243 return True;
1244
1245class tdStepStatDir(tdStepStat):
1246 """ Checks for an existing directory. """
1247 def __init__(self, sDirPath, oTestDir = None):
1248 tdStepStat.__init__(self, sPath = sDirPath, enmType = vboxcon.FsObjType_Directory, oTestFsObj = oTestDir);
1249
1250class tdStepStatDirEx(tdStepStatDir):
1251 """ Checks for an existing directory given a TestDir object. """
1252 def __init__(self, oTestDir): # type: (testfileset.TestDir)
1253 tdStepStatDir.__init__(self, oTestDir.sPath, oTestDir);
1254
1255class tdStepStatFile(tdStepStat):
1256 """ Checks for an existing file """
1257 def __init__(self, sFilePath = None, oTestFile = None):
1258 tdStepStat.__init__(self, sPath = sFilePath, enmType = vboxcon.FsObjType_File, oTestFsObj = oTestFile);
1259
1260class tdStepStatFileEx(tdStepStatFile):
1261 """ Checks for an existing file given a TestFile object. """
1262 def __init__(self, oTestFile): # type: (testfileset.TestFile)
1263 tdStepStatFile.__init__(self, oTestFile.sPath, oTestFile);
1264
1265class tdStepStatFileSize(tdStepStat):
1266 """ Checks for an existing file of a given expected size.. """
1267 def __init__(self, sFilePath, cbExactSize = 0):
1268 tdStepStat.__init__(self, sPath = sFilePath, enmType = vboxcon.FsObjType_File);
1269 self.cbExactSize = cbExactSize;
1270
1271class tdStepStatFileNotFound(tdStepStat):
1272 """ Checks for an existing directory. """
1273 def __init__(self, sPath):
1274 tdStepStat.__init__(self, sPath = sPath, fFound = False);
1275
1276class tdStepStatPathNotFound(tdStepStat):
1277 """ Checks for an existing directory. """
1278 def __init__(self, sPath):
1279 tdStepStat.__init__(self, sPath = sPath, fFound = False);
1280
1281
1282#
1283#
1284#
1285
1286class tdTestSessionFileRefs(tdTestGuestCtrlBase):
1287 """
1288 Tests session file (IGuestFile) reference counting.
1289 """
1290 def __init__(self, cRefs = 0):
1291 tdTestGuestCtrlBase.__init__(self);
1292 self.cRefs = cRefs;
1293
1294class tdTestSessionDirRefs(tdTestGuestCtrlBase):
1295 """
1296 Tests session directory (IGuestDirectory) reference counting.
1297 """
1298 def __init__(self, cRefs = 0):
1299 tdTestGuestCtrlBase.__init__(self);
1300 self.cRefs = cRefs;
1301
1302class tdTestSessionProcRefs(tdTestGuestCtrlBase):
1303 """
1304 Tests session process (IGuestProcess) reference counting.
1305 """
1306 def __init__(self, cRefs = 0):
1307 tdTestGuestCtrlBase.__init__(self);
1308 self.cRefs = cRefs;
1309
1310class tdTestUpdateAdditions(tdTestGuestCtrlBase):
1311 """
1312 Test updating the Guest Additions inside the guest.
1313 """
1314 def __init__(self, sSrc = "", asArgs = None, afFlags = None, oCreds = None):
1315 tdTestGuestCtrlBase.__init__(self, oCreds = oCreds);
1316 self.sSrc = sSrc;
1317 self.asArgs = asArgs;
1318 self.afFlags = afFlags;
1319
1320class tdTestResult(object):
1321 """
1322 Base class for test results.
1323 """
1324 def __init__(self, fRc = False):
1325 ## The overall test result.
1326 self.fRc = fRc;
1327
1328class tdTestResultFailure(tdTestResult):
1329 """
1330 Base class for test results.
1331 """
1332 def __init__(self):
1333 tdTestResult.__init__(self, fRc = False);
1334
1335class tdTestResultSuccess(tdTestResult):
1336 """
1337 Base class for test results.
1338 """
1339 def __init__(self):
1340 tdTestResult.__init__(self, fRc = True);
1341
1342class tdTestResultDirRead(tdTestResult):
1343 """
1344 Test result for reading guest directories.
1345 """
1346 def __init__(self, fRc = False, cFiles = 0, cDirs = 0, cOthers = None):
1347 tdTestResult.__init__(self, fRc = fRc);
1348 self.cFiles = cFiles;
1349 self.cDirs = cDirs;
1350 self.cOthers = cOthers;
1351
1352class tdTestResultExec(tdTestResult):
1353 """
1354 Holds a guest process execution test result,
1355 including the exit code, status + afFlags.
1356 """
1357 def __init__(self, fRc = False, uExitStatus = 500, iExitCode = 0, sBuf = None, cbBuf = 0, cbStdOut = None, cbStdErr = None):
1358 tdTestResult.__init__(self);
1359 ## The overall test result.
1360 self.fRc = fRc;
1361 ## Process exit stuff.
1362 self.uExitStatus = uExitStatus;
1363 self.iExitCode = iExitCode;
1364 ## Desired buffer length returned back from stdout/stderr.
1365 self.cbBuf = cbBuf;
1366 ## Desired buffer result from stdout/stderr. Use with caution!
1367 self.sBuf = sBuf;
1368 self.cbStdOut = cbStdOut;
1369 self.cbStdErr = cbStdErr;
1370
1371class tdTestResultFileStat(tdTestResult):
1372 """
1373 Test result for stat'ing guest files.
1374 """
1375 def __init__(self, fRc = False,
1376 cbSize = 0, eFileType = 0):
1377 tdTestResult.__init__(self, fRc = fRc);
1378 self.cbSize = cbSize;
1379 self.eFileType = eFileType;
1380 ## @todo Add more information.
1381
1382class tdTestResultFileReadWrite(tdTestResult):
1383 """
1384 Test result for reading + writing guest directories.
1385 """
1386 def __init__(self, fRc = False,
1387 cbProcessed = 0, offFile = 0, abBuf = None):
1388 tdTestResult.__init__(self, fRc = fRc);
1389 self.cbProcessed = cbProcessed;
1390 self.offFile = offFile;
1391 self.abBuf = abBuf;
1392
1393class tdTestResultSession(tdTestResult):
1394 """
1395 Test result for guest session counts.
1396 """
1397 def __init__(self, fRc = False, cNumSessions = 0):
1398 tdTestResult.__init__(self, fRc = fRc);
1399 self.cNumSessions = cNumSessions;
1400
1401class tdDebugSettings(object):
1402 """
1403 Contains local test debug settings.
1404 """
1405 def __init__(self, sVBoxServiceExeHst = None):
1406 self.sVBoxServiceExeHst = sVBoxServiceExeHst;
1407 self.sGstVBoxServiceLogPath = '';
1408
1409class SubTstDrvAddGuestCtrl(base.SubTestDriverBase):
1410 """
1411 Sub-test driver for executing guest control (VBoxService, IGuest) tests.
1412 """
1413
1414 def __init__(self, oTstDrv):
1415 base.SubTestDriverBase.__init__(self, oTstDrv, 'add-guest-ctrl', 'Guest Control');
1416
1417 ## @todo base.TestBase.
1418 self.asTestsDef = [
1419 'debug',
1420 'session_basic', 'session_env', 'session_file_ref', 'session_dir_ref', 'session_proc_ref', 'session_reboot',
1421 'exec_basic', 'exec_timeout',
1422 'dir_create', 'dir_create_temp', 'dir_read',
1423 'file_open', 'file_remove', 'file_stat', 'file_read', 'file_write',
1424 'copy_to', 'copy_from',
1425 'update_additions',
1426 '3d'
1427 ];
1428
1429 # Possible paths for the Guest Control Helper binary.
1430 self.asGstCtlHelperPaths = [
1431 # Debugging stuff (SCP'd over to the guest).
1432 '/tmp/VBoxGuestControlHelper',
1433 'C:\\Temp\\VBoxGuestControlHelper',
1434 # Validation Kit .ISO.
1435 '${CDROM}/vboxvalidationkit/${OS/ARCH}/VBoxGuestControlHelper${EXESUFF}',
1436 '${CDROM}/${OS/ARCH}/VBoxGuestControlHelper${EXESUFF}',
1437 # Test VMs.
1438 '/opt/apps/VBoxGuestControlHelper',
1439 '/opt/apps/VBoxGuestControlHelper',
1440 '/apps/VBoxGuestControlHelper',
1441 'C:\\Apps\\VBoxGuestControlHelper${EXESUFF}'
1442 ];
1443 # Full path to the Guest Control Helper binary we're going to use. Only gets resolved once.
1444 self.sGstCtlHelperExe = '';
1445
1446 self.asTests = self.asTestsDef;
1447 self.fSkipKnownBugs = False;
1448 self.oTestFiles = None # type: vboxtestfileset.TestFileSet
1449 self.oDebug = tdDebugSettings();
1450 self.sPathVBoxServiceExeGst = '';
1451 self.tpAdditionsVer = ();
1452
1453 def parseOption(self, asArgs, iArg): # pylint: disable=too-many-branches,too-many-statements
1454 if asArgs[iArg] == '--add-guest-ctrl-tests':
1455 iArg += 1;
1456 iNext = self.oTstDrv.requireMoreArgs(1, asArgs, iArg);
1457 if asArgs[iArg] == 'all': # Nice for debugging scripts.
1458 self.asTests = self.asTestsDef;
1459 else:
1460 self.asTests = asArgs[iArg].split(':');
1461 for s in self.asTests:
1462 if s not in self.asTestsDef:
1463 raise base.InvalidOption('The "--add-guest-ctrl-tests" value "%s" is not valid; valid values are: %s'
1464 % (s, ' '.join(self.asTestsDef)));
1465 return iNext;
1466 if asArgs[iArg] == '--add-guest-ctrl-skip-known-bugs':
1467 self.fSkipKnownBugs = True;
1468 return iArg + 1;
1469 if asArgs[iArg] == '--no-add-guest-ctrl-skip-known-bugs':
1470 self.fSkipKnownBugs = False;
1471 return iArg + 1;
1472 if asArgs[iArg] == '--add-guest-ctrl-debug-img':
1473 iArg += 1;
1474 iNext = self.oTstDrv.requireMoreArgs(1, asArgs, iArg);
1475 self.oDebug.sVBoxServiceExeHst = asArgs[iArg];
1476 return iNext;
1477 return iArg;
1478
1479 def showUsage(self):
1480 base.SubTestDriverBase.showUsage(self);
1481 reporter.log(' --add-guest-ctrl-tests <s1[:s2[:]]>');
1482 reporter.log(' Default: %s (all)' % (':'.join(self.asTestsDef)));
1483 reporter.log(' --add-guest-ctrl-skip-known-bugs');
1484 reporter.log(' Skips known bugs. Default: --no-add-guest-ctrl-skip-known-bugs');
1485 reporter.log('Debugging:');
1486 reporter.log(' --add-guest-ctrl-debug-img');
1487 reporter.log(' Sets VBoxService image to deploy for debugging');
1488 return True;
1489
1490 def testIt(self, oTestVm, oSession, oTxsSession):
1491 """
1492 Executes the test.
1493
1494 Returns fRc, oTxsSession. The latter may have changed.
1495 """
1496
1497 self.sPathVBoxServiceExeGst = oTestVm.pathJoin(self.oTstDrv.getGuestSystemAdminDir(oTestVm), 'VBoxService') \
1498 + base.exeSuff();
1499
1500 # For some tests we need know the Guest Additions version, so fetch it now.
1501 self.tpAdditionsVer = self.oTstDrv.getGuestAdditionsVersion(oSession);
1502
1503 reporter.log("Active tests: %s" % (self.asTests,));
1504
1505 # The tests. Must-succeed tests should be first.
1506 atTests = [
1507 ( True, self.prepareGuestForDebugging, None, 'Manual Debugging',),
1508 ( True, self.prepareGuestForTesting, None, 'Preparations',),
1509 ( True, self.testGuestCtrlSession, 'session_basic', 'Session Basics',),
1510 ( True, self.testGuestCtrlExec, 'exec_basic', 'Execution',),
1511 ( False, self.testGuestCtrlExecTimeout, 'exec_timeout', 'Execution Timeouts',),
1512 ( False, self.testGuestCtrlSessionEnvironment, 'session_env', 'Session Environment',),
1513 ( False, self.testGuestCtrlSessionFileRefs, 'session_file_ref', 'Session File References',),
1514 #( False, self.testGuestCtrlSessionDirRefs, 'session_dir_ref', 'Session Directory References',),
1515 ( False, self.testGuestCtrlSessionProcRefs, 'session_proc_ref', 'Session Process References',),
1516 ( False, self.testGuestCtrlDirCreate, 'dir_create', 'Creating directories',),
1517 ( False, self.testGuestCtrlDirCreateTemp, 'dir_create_temp', 'Creating temporary directories',),
1518 ( False, self.testGuestCtrlDirRead, 'dir_read', 'Reading directories',),
1519 ( False, self.testGuestCtrlCopyTo, 'copy_to', 'Copy to guest',),
1520 ( False, self.testGuestCtrlCopyFrom, 'copy_from', 'Copy from guest',),
1521 ( False, self.testGuestCtrlFileStat, 'file_stat', 'Querying file information (stat)',),
1522 ( False, self.testGuestCtrlFileOpen, 'file_open', 'File open',),
1523 ( False, self.testGuestCtrlFileRead, 'file_read', 'File read',),
1524 ( False, self.testGuestCtrlFileWrite, 'file_write', 'File write',),
1525 ( False, self.testGuestCtrlFileRemove, 'file_remove', 'Removing files',), # Destroys prepped files.
1526 ( False, self.testGuestCtrlUpdateAdditions, 'update_additions', 'Updating Guest Additions',),
1527 # @todo r=aeichner Only enable it again when this really works,
1528 # the 3D tests should probably live in a separate file
1529 # ( False, self.testGuestCtrl3D, '3d', '3D acceleration',),
1530 ];
1531
1532 if not self.fSkipKnownBugs:
1533 atTests.extend([
1534 # @todo Seems to (mainly?) fail on Linux guests, primarily running with systemd as service supervisor.
1535 # Needs to be investigated and fixed.
1536 ( False, self.testGuestCtrlSessionReboot, 'session_reboot', 'Session w/ Guest Reboot',), # May zap /tmp.
1537 ]);
1538
1539 fRc = True;
1540 for fMustSucceed, fnHandler, sShortNm, sTestNm in atTests:
1541
1542 # If for whatever reason the VM object became invalid, bail out.
1543 if not oTestVm:
1544 reporter.error('Test VM object invalid (VBoxSVC or client process crashed?), aborting tests');
1545 fRc = False;
1546 break;
1547
1548 reporter.testStart(sTestNm);
1549 if sShortNm is None or sShortNm in self.asTests:
1550 # Returns (fRc, oTxsSession, oSession) - but only the first one is mandatory.
1551 aoResult = fnHandler(oSession, oTxsSession, oTestVm);
1552 if aoResult is None or isinstance(aoResult, bool):
1553 fRcTest = aoResult;
1554 else:
1555 fRcTest = aoResult[0];
1556 if len(aoResult) > 1:
1557 oTxsSession = aoResult[1];
1558 if len(aoResult) > 2:
1559 oSession = aoResult[2];
1560 assert len(aoResult) == 3;
1561 else:
1562 fRcTest = None;
1563
1564 if fRcTest is False and reporter.testErrorCount() == 0:
1565 fRcTest = reporter.error('Buggy test! Returned False w/o logging the error!');
1566 if reporter.testDone(fRcTest is None)[1] != 0:
1567 fRcTest = False;
1568 fRc = False;
1569
1570 # Stop execution if this is a must-succeed test and it failed.
1571 if fRcTest is False and fMustSucceed is True:
1572 reporter.log('Skipping any remaining tests since the previous one failed.');
1573 break;
1574
1575 # Upload VBoxService logs on failure.
1576 if reporter.testErrorCount() > 0 \
1577 and self.oDebug.sGstVBoxServiceLogPath:
1578 sVBoxServiceLogsTarGz = 'ga-vboxservice-logs-%s.tar.gz' % oTestVm.sVmName;
1579 sGstVBoxServiceLogsTarGz = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), sVBoxServiceLogsTarGz);
1580 if self.oTstDrv.txsPackFile(oSession, oTxsSession, \
1581 sGstVBoxServiceLogsTarGz, self.oDebug.sGstVBoxServiceLogPath, fIgnoreErrors = True):
1582 self.oTstDrv.txsDownloadFiles(oSession, oTxsSession, [ (sGstVBoxServiceLogsTarGz, sVBoxServiceLogsTarGz) ], \
1583 fIgnoreErrors = True);
1584
1585 return (fRc, oTxsSession);
1586
1587 def prepareGuestForDebugging(self, oSession, oTxsSession, oTestVm): # pylint: disable=unused-argument
1588 """
1589 Prepares a guest for (manual) debugging.
1590
1591 This involves copying over and invoking a the locally built VBoxService binary.
1592 """
1593
1594 if self.oDebug.sVBoxServiceExeHst is None: # If no debugging enabled, bail out.
1595 reporter.log('Skipping debugging');
1596 return True;
1597
1598 reporter.log('Preparing for debugging ...');
1599
1600 try:
1601 self.vboxServiceControl(oTxsSession, oTestVm, fStart = False);
1602
1603 self.oTstDrv.sleep(5); # Fudge factor -- wait until the service stopped.
1604
1605 reporter.log('Uploading "%s" to "%s" ...' % (self.oDebug.sVBoxServiceExeHst, self.sPathVBoxServiceExeGst));
1606 oTxsSession.syncUploadFile(self.oDebug.sVBoxServiceExeHst, self.sPathVBoxServiceExeGst);
1607
1608 if oTestVm.isLinux():
1609 oTxsSession.syncChMod(self.sPathVBoxServiceExeGst, 0o755);
1610
1611 self.vboxServiceControl(oTxsSession, oTestVm, fStart = True);
1612
1613 self.oTstDrv.sleep(5); # Fudge factor -- wait until the service is ready.
1614
1615 except:
1616 return reporter.errorXcpt('Unable to prepare for debugging');
1617
1618 return True;
1619
1620 def locateGstBinary(self, oTxsSession, asPaths):
1621 """
1622 Locates a guest binary on the guest by checking the paths in \a asPaths.
1623
1624 Returns a tuple (success, path).
1625 """
1626 for sCurPath in asPaths:
1627 reporter.log2('Checking for \"%s\" ...' % (sCurPath));
1628 if oTxsSession.syncIsFile(sCurPath, fIgnoreErrors = True):
1629 return (True, oTxsSession.syncExpandString(sCurPath));
1630 reporter.error('Unable to find guest binary in any of these places:\n%s' % ('\n'.join(asPaths),));
1631 return (False, "");
1632
1633 #
1634 # VBoxService handling.
1635 #
1636 def vboxServiceControl(self, oTxsSession, oTestVm, fStart):
1637 """
1638 Controls VBoxService on the guest by starting or stopping the service.
1639 Returns success indicator.
1640 """
1641
1642 fRc = True;
1643
1644 if oTestVm.isWindows():
1645 sPathSC = os.path.join(self.oTstDrv.getGuestSystemDir(oTestVm), 'sc.exe');
1646 if oTestVm.sKind in ('WindowsNT3x', 'WindowsNT4', 'Windows2000',): # W2K too?
1647 sPathSC = os.path.join(self.oTstDrv.getGuestSystemDir(oTestVm), 'net.exe');
1648 if fStart is True:
1649 fRc = self.oTstDrv.txsRunTest(oTxsSession, 'Starting VBoxService', 30 * 1000,
1650 sPathSC, (sPathSC, 'start', 'VBoxService'));
1651 else:
1652 fRc = self.oTstDrv.txsRunTest(oTxsSession, 'Stopping VBoxService', 30 * 1000,
1653 sPathSC, (sPathSC, 'stop', 'VBoxService'));
1654 elif oTestVm.isLinux():
1655 sPathService = "/sbin/rcvboxadd-service";
1656 if fStart is True:
1657 fRc = self.oTstDrv.txsRunTest(oTxsSession, 'Starting VBoxService', 30 * 1000,
1658 sPathService, (sPathService, 'start'));
1659 else:
1660 fRc = self.oTstDrv.txsRunTest(oTxsSession, 'Stopping VBoxService', 30 * 1000,
1661 sPathService, (sPathService, 'stop'));
1662 else:
1663 reporter.log('Controlling VBoxService not supported for this guest yet');
1664
1665 return fRc;
1666
1667 def waitForGuestFacility(self, oSession, eFacilityType, sDesc,
1668 eFacilityStatus, cMsTimeout = 30 * 1000):
1669 """
1670 Waits for a guest facility to enter a certain status.
1671 By default the "Active" status is being used.
1672
1673 Returns success status.
1674 """
1675
1676 reporter.log('Waiting for Guest Additions facility "%s" to change to status %s (%dms timeout)...'
1677 % (sDesc, str(eFacilityStatus), cMsTimeout));
1678
1679 fRc = False;
1680
1681 eStatusOld = None;
1682 tsStart = base.timestampMilli();
1683 while base.timestampMilli() - tsStart < cMsTimeout:
1684 try:
1685 eStatus, _ = oSession.o.console.guest.getFacilityStatus(eFacilityType);
1686 reporter.log('Current status is %s' % (str(eStatus)));
1687 if eStatusOld is None:
1688 eStatusOld = eStatus;
1689 except:
1690 reporter.errorXcpt('Getting facility status failed');
1691 break;
1692 if eStatus != eStatusOld:
1693 reporter.log('Status changed to %s' % (str(eStatus)));
1694 eStatusOld = eStatus;
1695 if eStatus == eFacilityStatus:
1696 fRc = True;
1697 break;
1698 self.oTstDrv.sleep(5); # Do some busy waiting.
1699
1700 if not fRc:
1701 reporter.error('Waiting for Guest Additions facility "%s" timed out' % (sDesc));
1702 else:
1703 reporter.log('Guest Additions facility "%s" reached requested status %s after %dms'
1704 % (sDesc, str(eFacilityStatus), base.timestampMilli() - tsStart));
1705
1706 return fRc;
1707
1708 #
1709 # Guest test files.
1710 #
1711
1712 def prepareGuestForTesting(self, oSession, oTxsSession, oTestVm):
1713 """
1714 Prepares the VM for testing, uploading a bunch of files and stuff via TXS.
1715 Returns success indicator.
1716 """
1717 _ = oSession;
1718
1719 #
1720 # Make sure the temporary directory exists.
1721 #
1722 for sDir in [self.oTstDrv.getGuestTempDir(oTestVm), ]:
1723 if oTxsSession.syncMkDirPath(sDir, 0o777) is not True:
1724 return reporter.error('Failed to create directory "%s"!' % (sDir,));
1725
1726 # Query the TestExecService (TXS) version first to find out on what we run.
1727 fGotTxsVer = self.oTstDrv.txsVer(oSession, oTxsSession, 30 * 100, fIgnoreErrors = True);
1728
1729 # Whether to enable verbose logging for VBoxService.
1730 fEnableVerboseLogging = False;
1731
1732 # On Windows guests we always can enable verbose logging. NT4 and W2K doesn't have reg.exe nor (at least NT4) sc.exe.
1733 if oTestVm.isWindows() and oTestVm.sKind not in ('WindowsNT4', 'Windows2000',):
1734 fEnableVerboseLogging = True;
1735
1736 # Old TxS versions had a bug which caused an infinite loop when executing stuff containing "$xxx",
1737 # so check if we got the version here first and skip enabling verbose logging nonetheless if needed.
1738 if not fGotTxsVer:
1739 reporter.log('Too old TxS service running')
1740 fEnableVerboseLogging = False;
1741
1742 # Some older Linux test VMs (like tst-rhel5) don't have a pre-configured 'vbox' user.
1743 # So make sure that this user exists and has the appropriate password set. Ignore any errors.
1744 if oTestVm.isLinux():
1745 sCmdUserAdd = oTestVm.pathJoin(self.oTstDrv.getGuestSystemAdminDir(oTestVm, sPathPrefix = '/usr'), 'useradd');
1746 asArgs = [ sCmdUserAdd, '-m', 'vbox' ];
1747 self.oTstDrv.txsRunTest(oTxsSession, sCmdUserAdd, 5 * 60 * 1000, sCmdUserAdd, asArgs,
1748 fCheckSessionStatus = False);
1749 # We must supply the password in an encrypted form using chpasswd (via stdin).
1750 sCmdChPasswd = oTestVm.pathJoin(self.oTstDrv.getGuestSystemAdminDir(oTestVm, sPathPrefix = '/usr'), 'chpasswd');
1751 asArgs = [ sCmdChPasswd ];
1752 self.oTstDrv.txsRunTestStdIn(oTxsSession, sCmdChPasswd, 5 * 60 * 1000, sCmdChPasswd, asArgs,
1753 sStdIn = 'vbox:password\n', fIgnoreErrors = True);
1754
1755 #
1756 # Enable VBoxService verbose logging.
1757 #
1758 reporter.log('Enabling verbose VBoxService logging: %s' % (fEnableVerboseLogging));
1759 if fEnableVerboseLogging:
1760 self.oDebug.sGstVBoxServiceLogPath = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), "VBoxService");
1761 if oTxsSession.syncMkDirPath(self.oDebug.sGstVBoxServiceLogPath, 0o777) is not True:
1762 return reporter.error('Failed to create directory "%s"!' % (self.oDebug.sGstVBoxServiceLogPath,));
1763 sPathLogFile = oTestVm.pathJoin(self.oDebug.sGstVBoxServiceLogPath, 'VBoxService.log');
1764
1765 reporter.log('VBoxService logs will be stored in "%s"' % (self.oDebug.sGstVBoxServiceLogPath,));
1766
1767 fRestartVBoxService = False;
1768 if oTestVm.isWindows() and oTestVm.sKind not in ('WindowsNT4', 'Windows2000',):
1769 sPathRegExe = oTestVm.pathJoin(self.oTstDrv.getGuestSystemDir(oTestVm), 'reg.exe');
1770 sImagePath = '%s -vvvv --logfile %s' % (self.sPathVBoxServiceExeGst, sPathLogFile);
1771 fRestartVBoxService = self.oTstDrv.txsRunTest(oTxsSession, 'Enabling VBoxService verbose logging (via registry)',
1772 30 * 1000,
1773 sPathRegExe,
1774 (sPathRegExe, 'add',
1775 'HKLM\\SYSTEM\\CurrentControlSet\\Services\\VBoxService',
1776 '/v', 'ImagePath', '/t', 'REG_SZ', '/d', sImagePath, '/f'));
1777 elif oTestVm.isLinux():
1778 sPathSed = oTestVm.pathJoin(self.oTstDrv.getGuestSystemDir(oTestVm), 'sed');
1779 fRestartVBoxService = self.oTstDrv.txsRunTest(oTxsSession, 'Enabling VBoxService verbose logging', 30 * 1000,
1780 sPathSed,
1781 (sPathSed, '-i', '-e', 's/'
1782 '\\$2 \\$3'
1783 '/'
1784 '\\$2 \\$3 -vvvv --logfile \\/var\\/tmp\\/VBoxService\\/VBoxService.log'
1785 '/g',
1786 '/sbin/rcvboxadd-service'));
1787 else:
1788 reporter.log('Verbose logging for VBoxService not supported for this guest yet');
1789
1790 if fRestartVBoxService:
1791 # Wait for VBoxService to start up properly so, we can shut it down again and restart.
1792 fRc = self.waitForGuestFacility(oSession, vboxcon.AdditionsFacilityType_VBoxService, "VBoxService",
1793 vboxcon.AdditionsFacilityStatus_Active);
1794 if not fRc:
1795 reporter.log('VBoxService didn\'t startup in time');
1796 return False;
1797
1798 self.vboxServiceControl(oTxsSession, oTestVm, fStart = False);
1799 self.oTstDrv.sleep(5);
1800 self.vboxServiceControl(oTxsSession, oTestVm, fStart = True);
1801
1802 # Wait for VBoxService to start up in any case.
1803 reporter.testStart('Waiting for VBoxService to get started');
1804 fRc = self.waitForGuestFacility(oSession, vboxcon.AdditionsFacilityType_VBoxService, "VBoxService",
1805 vboxcon.AdditionsFacilityStatus_Active);
1806 reporter.testDone();
1807 if not fRc:
1808 return False;
1809
1810 #
1811 # Generate and upload some random files and dirs to the guest.
1812 # Note! Make sure we don't run into too-long-path issues when using
1813 # the test files on the host if.
1814 #
1815 cchGst = len(self.oTstDrv.getGuestTempDir(oTestVm)) + 1 + len('addgst-1') + 1;
1816 cchHst = len(self.oTstDrv.sScratchPath) + 1 + len('copyto/addgst-1') + 1;
1817 cchMaxPath = 230;
1818 if cchHst > cchGst:
1819 cchMaxPath -= cchHst - cchGst;
1820 reporter.log('cchMaxPath=%s (cchHst=%s, cchGst=%s)' % (cchMaxPath, cchHst, cchGst,));
1821 self.oTestFiles = vboxtestfileset.TestFileSet(oTestVm,
1822 self.oTstDrv.getGuestTempDir(oTestVm), 'addgst-1',
1823 # Make sure that we use a lowest common denominator across all supported
1824 # platforms, to make testing the randomly generated file paths work
1825 # reliably.
1826 cchMaxPath = cchMaxPath, asCompatibleWith = [ ('cross') ]);
1827 return self.oTestFiles.upload(oTxsSession, self.oTstDrv);
1828
1829
1830 #
1831 # gctrlXxxx stuff.
1832 #
1833
1834 def gctrlCopyFileFrom(self, oGuestSession, oTest, fExpected):
1835 """
1836 Helper function to copy a single file from the guest to the host.
1837 """
1838
1839 # As we pass-in randomly generated file names, the source sometimes can be empty, which
1840 # in turn will result in a (correct) error by the API. Simply skip this function then.
1841 if not oTest.sSrc:
1842 reporter.log2('Skipping guest file "%s"' % (limitString(oTest.sSrc)));
1843 return fExpected;
1844
1845 #
1846 # Do the copying.
1847 #
1848 reporter.log2('Copying guest file "%s" to host "%s"' % (limitString(oTest.sSrc), limitString(oTest.sDst)));
1849 try:
1850 if self.oTstDrv.fpApiVer >= 5.0:
1851 oCurProgress = oGuestSession.fileCopyFromGuest(oTest.sSrc, oTest.sDst, oTest.afFlags);
1852 else:
1853 oCurProgress = oGuestSession.copyFrom(oTest.sSrc, oTest.sDst, oTest.afFlags);
1854 except:
1855 reporter.maybeErrXcpt(fExpected, 'Copy from exception for sSrc="%s", sDst="%s":' % (oTest.sSrc, oTest.sDst,));
1856 return False;
1857 if oCurProgress is None:
1858 return reporter.error('No progress object returned');
1859 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlFileCopyFrom");
1860 oProgress.wait();
1861 if not oProgress.isSuccess():
1862 oProgress.logResult(fIgnoreErrors = not fExpected);
1863 return False;
1864
1865 #
1866 # Check the result if we can.
1867 #
1868 if oTest.oSrc:
1869 assert isinstance(oTest.oSrc, testfileset.TestFile);
1870 sDst = oTest.sDst;
1871 if os.path.isdir(sDst):
1872 sDst = os.path.join(sDst, oTest.oSrc.sName);
1873 try:
1874 oFile = open(sDst, 'rb'); # pylint: disable=consider-using-with
1875 except:
1876 # Don't report expected non-existing paths / files as an error.
1877 return reporter.maybeErrXcpt(fExpected, 'open(%s) failed during verfication (file / path not found)' % (sDst,));
1878 fEqual = oTest.oSrc.equalFile(oFile);
1879 oFile.close();
1880 if not fEqual:
1881 return reporter.error('Content differs for "%s"' % (sDst,));
1882
1883 return True;
1884
1885 def __compareTestDir(self, oDir, sHostPath): # type: (testfileset.TestDir, str) -> bool
1886 """
1887 Recursively compare the content of oDir and sHostPath.
1888
1889 Returns True on success, False + error logging on failure.
1890
1891 Note! This ASSUMES that nothing else was copied to sHostPath!
1892 """
1893 #
1894 # First check out all the entries and files in the directory.
1895 #
1896 dLeftUpper = dict(oDir.dChildrenUpper);
1897 try:
1898 asEntries = os.listdir(sHostPath);
1899 except:
1900 return reporter.errorXcpt('os.listdir(%s) failed' % (sHostPath,));
1901
1902 fRc = True;
1903 for sEntry in asEntries:
1904 sEntryUpper = sEntry.upper();
1905 if sEntryUpper not in dLeftUpper:
1906 fRc = reporter.error('Unexpected entry "%s" in "%s"' % (sEntry, sHostPath,));
1907 else:
1908 oFsObj = dLeftUpper[sEntryUpper];
1909 del dLeftUpper[sEntryUpper];
1910
1911 if isinstance(oFsObj, testfileset.TestFile):
1912 sFilePath = os.path.join(sHostPath, oFsObj.sName);
1913 try:
1914 oFile = open(sFilePath, 'rb'); # pylint: disable=consider-using-with
1915 except:
1916 fRc = reporter.errorXcpt('open(%s) failed during verfication' % (sFilePath,));
1917 else:
1918 fEqual = oFsObj.equalFile(oFile);
1919 oFile.close();
1920 if not fEqual:
1921 fRc = reporter.error('Content differs for "%s"' % (sFilePath,));
1922
1923 # List missing entries:
1924 for sKey in dLeftUpper:
1925 oEntry = dLeftUpper[sKey];
1926 fRc = reporter.error('%s: Missing %s "%s" (src path: %s)'
1927 % (sHostPath, oEntry.sName,
1928 'file' if isinstance(oEntry, testfileset.TestFile) else 'directory', oEntry.sPath));
1929
1930 #
1931 # Recurse into subdirectories.
1932 #
1933 for oFsObj in oDir.aoChildren:
1934 if isinstance(oFsObj, testfileset.TestDir):
1935 fRc = self.__compareTestDir(oFsObj, os.path.join(sHostPath, oFsObj.sName)) and fRc;
1936 return fRc;
1937
1938 def gctrlCopyDirFrom(self, oGuestSession, oTest, fExpected):
1939 """
1940 Helper function to copy a directory from the guest to the host.
1941 """
1942
1943 # As we pass-in randomly generated directories, the source sometimes can be empty, which
1944 # in turn will result in a (correct) error by the API. Simply skip this function then.
1945 if not oTest.sSrc:
1946 reporter.log2('Skipping guest dir "%s"' % (limitString(oTest.sSrc)));
1947 return fExpected;
1948
1949 #
1950 # Do the copying.
1951 #
1952 reporter.log2('Copying guest dir "%s" to host "%s"' % (limitString(oTest.sSrc), limitString(oTest.sDst)));
1953 try:
1954 if self.oTstDrv.fpApiVer >= 7.0:
1955 ## @todo Make the following new flags implicit for 7.0 for now. Develop dedicated tests for this later and remove.
1956 if not oTest.afFlags:
1957 oTest.afFlags = [ vboxcon.DirectoryCopyFlag_Recursive, ];
1958 elif vboxcon.DirectoryCopyFlag_Recursive not in oTest.afFlags:
1959 oTest.afFlags.append(vboxcon.DirectoryCopyFlag_Recursive);
1960 ## @todo Ditto.
1961 if not oTest.afFlags:
1962 oTest.afFlags = [ vboxcon.DirectoryCopyFlag_FollowLinks, ];
1963 elif vboxcon.DirectoryCopyFlag_FollowLinks not in oTest.afFlags:
1964 oTest.afFlags.append(vboxcon.DirectoryCopyFlag_FollowLinks);
1965 oCurProgress = oGuestSession.directoryCopyFromGuest(oTest.sSrc, oTest.sDst, oTest.afFlags);
1966 except:
1967 reporter.maybeErrXcpt(fExpected, 'Copy dir from exception for sSrc="%s", sDst="%s":' % (oTest.sSrc, oTest.sDst,));
1968 return False;
1969 if oCurProgress is None:
1970 return reporter.error('No progress object returned');
1971
1972 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlDirCopyFrom");
1973 oProgress.wait();
1974 if not oProgress.isSuccess():
1975 oProgress.logResult(fIgnoreErrors = not fExpected);
1976 return False;
1977
1978 #
1979 # Check the result if we can.
1980 #
1981 if oTest.oSrc:
1982 assert isinstance(oTest.oSrc, testfileset.TestDir);
1983 sDst = oTest.sDst;
1984 if oTest.fIntoDst:
1985 return self.__compareTestDir(oTest.oSrc, os.path.join(sDst, oTest.oSrc.sName));
1986 oDummy = testfileset.TestDir(None, 'dummy');
1987 oDummy.aoChildren = [oTest.oSrc,]
1988 oDummy.dChildrenUpper = { oTest.oSrc.sName.upper(): oTest.oSrc, };
1989 return self.__compareTestDir(oDummy, sDst);
1990 return True;
1991
1992 def gctrlCopyFileTo(self, oGuestSession, sSrc, sDst, afFlags, fIsError):
1993 """
1994 Helper function to copy a single file from the host to the guest.
1995
1996 afFlags is either None or an array of vboxcon.DirectoryCopyFlag_Xxxx values.
1997 """
1998 reporter.log2('Copying host file "%s" to guest "%s" (flags %s)' % (limitString(sSrc), limitString(sDst), afFlags));
1999 try:
2000 if self.oTstDrv.fpApiVer >= 5.0:
2001 oCurProgress = oGuestSession.fileCopyToGuest(sSrc, sDst, afFlags);
2002 else:
2003 oCurProgress = oGuestSession.copyTo(sSrc, sDst, afFlags);
2004 except:
2005 reporter.maybeErrXcpt(fIsError, 'sSrc=%s sDst=%s' % (sSrc, sDst,));
2006 return False;
2007
2008 if oCurProgress is None:
2009 return reporter.error('No progress object returned');
2010 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlCopyFileTo");
2011
2012 try:
2013 oProgress.wait();
2014 if not oProgress.isSuccess():
2015 oProgress.logResult(fIgnoreErrors = not fIsError);
2016 return False;
2017 except:
2018 reporter.maybeErrXcpt(fIsError, 'Wait exception for sSrc="%s", sDst="%s":' % (sSrc, sDst));
2019 return False;
2020 return True;
2021
2022 def gctrlCopyDirTo(self, oGuestSession, sSrc, sDst, afFlags, fIsError):
2023 """
2024 Helper function to copy a directory (tree) from the host to the guest.
2025
2026 afFlags is either None or an array of vboxcon.DirectoryCopyFlag_Xxxx values.
2027 """
2028 reporter.log2('Copying host directory "%s" to guest "%s" (flags %s)' % (limitString(sSrc), limitString(sDst), afFlags));
2029 try:
2030 if self.oTstDrv.fpApiVer >= 7.0:
2031 ## @todo Make the following new flags implicit for 7.0 for now. Develop dedicated tests for this later and remove.
2032 if not afFlags:
2033 afFlags = [ vboxcon.DirectoryCopyFlag_Recursive, ];
2034 elif vboxcon.DirectoryCopyFlag_Recursive not in afFlags:
2035 afFlags.append(vboxcon.DirectoryCopyFlag_Recursive);
2036 ## @todo Ditto.
2037 if not afFlags:
2038 afFlags = [vboxcon.DirectoryCopyFlag_FollowLinks,];
2039 elif vboxcon.DirectoryCopyFlag_FollowLinks not in afFlags:
2040 afFlags.append(vboxcon.DirectoryCopyFlag_FollowLinks);
2041 oCurProgress = oGuestSession.directoryCopyToGuest(sSrc, sDst, afFlags);
2042 except:
2043 reporter.maybeErrXcpt(fIsError, 'sSrc=%s sDst=%s' % (sSrc, sDst,));
2044 return False;
2045
2046 if oCurProgress is None:
2047 return reporter.error('No progress object returned');
2048 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlCopyFileTo");
2049
2050 try:
2051 oProgress.wait();
2052 if not oProgress.isSuccess():
2053 oProgress.logResult(fIgnoreErrors = not fIsError);
2054 return False;
2055 except:
2056 reporter.maybeErrXcpt(fIsError, 'Wait exception for sSrc="%s", sDst="%s":' % (sSrc, sDst));
2057 return False;
2058 return True;
2059
2060 def gctrlCreateDir(self, oTest, oRes, oGuestSession):
2061 """
2062 Helper function to create a guest directory specified in the current test.
2063 """
2064 reporter.log2('Creating directory "%s"' % (limitString(oTest.sDirectory),));
2065 try:
2066 oGuestSession.directoryCreate(oTest.sDirectory, oTest.fMode, oTest.afFlags);
2067 except:
2068 reporter.maybeErrXcpt(oRes.fRc, 'Failed to create "%s" fMode=%o afFlags=%s'
2069 % (oTest.sDirectory, oTest.fMode, oTest.afFlags,));
2070 return not oRes.fRc;
2071 if oRes.fRc is not True:
2072 return reporter.error('Did not expect to create directory "%s"!' % (oTest.sDirectory,));
2073
2074 # Check if the directory now exists.
2075 try:
2076 if self.oTstDrv.fpApiVer >= 5.0:
2077 fDirExists = oGuestSession.directoryExists(oTest.sDirectory, False);
2078 else:
2079 fDirExists = oGuestSession.directoryExists(oTest.sDirectory);
2080 except:
2081 return reporter.errorXcpt('directoryExists failed on "%s"!' % (oTest.sDirectory,));
2082 if not fDirExists:
2083 return reporter.errorXcpt('directoryExists returned False on "%s" after directoryCreate succeeded!'
2084 % (oTest.sDirectory,));
2085 return True;
2086
2087 def gctrlReadDirTree(self, oTest, oGuestSession, fIsError, fUseDirList = False, cEntriesPerRead = 0, sSubDir = None):
2088 """
2089 Helper function to recursively read a guest directory tree specified in the current test.
2090 """
2091 sDir = oTest.sDirectory;
2092 sFilter = oTest.sFilter;
2093 afFlags = oTest.afFlags;
2094 oTestVm = oTest.oCreds.oTestVm;
2095 sCurDir = oTestVm.pathJoin(sDir, sSubDir) if sSubDir else sDir;
2096
2097 fRc = True; # Be optimistic.
2098 cDirs = 0; # Number of directories read.
2099 cFiles = 0; # Number of files read.
2100 cOthers = 0; # Other files.
2101
2102 cEntriesToRead = cEntriesPerRead; # Only used when listing directories.
2103 aFsObjInfo = [];
2104
2105 # Open the directory:
2106 reporter.log2('Directory="%s", filter="%s", afFlags="%s", fUseDirList=%s, cEntriesPerRead=%d'
2107 % (limitString(sCurDir), sFilter, afFlags, fUseDirList, cEntriesPerRead));
2108 try:
2109 oCurDir = oGuestSession.directoryOpen(sCurDir, sFilter, afFlags);
2110 except:
2111 reporter.maybeErrXcpt(fIsError, 'sCurDir=%s sFilter=%s afFlags=%s' % (sCurDir, sFilter, afFlags,))
2112 return (False, 0, 0, 0);
2113
2114 # Read the directory.
2115 fDone = False;
2116 while fRc is True:
2117 reporter.log3('Reading next batch ...');
2118 aFsObjInfo = [];
2119 try:
2120 if not fUseDirList:
2121 aFsObjInfo.append(oCurDir.read());
2122 else:
2123 if not cEntriesToRead:
2124 cEntriesToRead = random.randrange(1, 32768);
2125 aFsObjInfo = oCurDir.list(cEntriesToRead);
2126 except Exception as oXcpt:
2127 if vbox.ComError.notEqual(oXcpt, vbox.ComError.VBOX_E_OBJECT_NOT_FOUND):
2128 if fUseDirList:
2129 fRc = reporter.errorXcpt('Error listing directory "%s" (cEntriesToRead=%d):' % (sCurDir, cEntriesToRead));
2130 else:
2131 if self.oTstDrv.fpApiVer > 5.2:
2132 reporter.errorXcpt('Error reading directory "%s":' % (sCurDir,));
2133 else:
2134 # Unlike fileOpen, directoryOpen will not fail if the directory does not exist.
2135 reporter.maybeErrXcpt(fIsError, 'Error reading directory "%s":' % (sCurDir,));
2136 fRc = False;
2137 else:
2138 reporter.log2('\tNo more directory entries for "%s"' % (limitString(sCurDir),));
2139 fDone = True;
2140 break;
2141
2142 if fDone or not fRc: # Abort reading?
2143 break;
2144
2145 reporter.log3('Processing next batch (%d items)...' % (len(aFsObjInfo)));
2146 for oFsObjInfo in aFsObjInfo:
2147 try:
2148 sName = oFsObjInfo.name;
2149 eType = oFsObjInfo.type;
2150 except:
2151 fRc = reporter.errorXcpt();
2152 break;
2153
2154 if sName in ('.', '..', ):
2155 if eType != vboxcon.FsObjType_Directory:
2156 fRc = reporter.error('Wrong type for "%s": %d, expected %d (Directory)'
2157 % (sName, eType, vboxcon.FsObjType_Directory));
2158 elif eType == vboxcon.FsObjType_Directory:
2159 reporter.log2(' Directory "%s"' % limitString(oFsObjInfo.name));
2160 aSubResult = self.gctrlReadDirTree(oTest, oGuestSession, fIsError,
2161 fUseDirList, cEntriesPerRead,
2162 oTestVm.pathJoin(sSubDir, sName) if sSubDir else sName);
2163 fRc = aSubResult[0];
2164 cDirs += aSubResult[1] + 1;
2165 cFiles += aSubResult[2];
2166 cOthers += aSubResult[3];
2167 elif eType is vboxcon.FsObjType_File:
2168 reporter.log4(' File "%s"' % oFsObjInfo.name);
2169 cFiles += 1;
2170 elif eType is vboxcon.FsObjType_Symlink:
2171 reporter.log4(' Symlink "%s" -- not tested yet' % oFsObjInfo.name);
2172 cOthers += 1;
2173 elif oTestVm.isWindows() \
2174 or oTestVm.isOS2() \
2175 or eType not in (vboxcon.FsObjType_Fifo, vboxcon.FsObjType_DevChar, vboxcon.FsObjType_DevBlock,
2176 vboxcon.FsObjType_Socket, vboxcon.FsObjType_WhiteOut):
2177 fRc = reporter.error('Directory "%s" contains invalid directory entry "%s" (type %d)' %
2178 (sCurDir, oFsObjInfo.name, oFsObjInfo.type,));
2179 else:
2180 cOthers += 1;
2181
2182 # Close the directory
2183 try:
2184 oCurDir.close();
2185 except:
2186 fRc = reporter.errorXcpt('sCurDir=%s' % (sCurDir));
2187
2188 return (fRc, cDirs, cFiles, cOthers);
2189
2190 def gctrlReadDirTree2(self, oGuestSession, oDir, fUseDirList = False, cEntriesPerRead = 0):
2191 # type: (testfileset.TestDir) -> bool
2192 """
2193 Helper function to recursively read a guest directory tree specified in the current test.
2194 """
2195
2196 #
2197 # Process the directory.
2198 #
2199
2200 # Open the directory:
2201 try:
2202 oCurDir = oGuestSession.directoryOpen(oDir.sPath, '', None);
2203 except:
2204 return reporter.errorXcpt('sPath=%s' % (oDir.sPath,));
2205
2206 # Read the directory.
2207 dLeftUpper = dict(oDir.dChildrenUpper);
2208 cDot = 0;
2209 cDotDot = 0;
2210 fRc = True;
2211 cEntriesToRead = cEntriesPerRead; # Only used when listing directories.
2212 aFsObjInfo = [];
2213 while True:
2214 reporter.log3('Reading next batch ...');
2215 aFsObjInfo = [];
2216 try:
2217 if not fUseDirList:
2218 aFsObjInfo.append(oCurDir.read());
2219 else:
2220 if not cEntriesToRead:
2221 cEntriesToRead = random.randrange(1, 32768);
2222 aFsObjInfo = oCurDir.list(cEntriesToRead);
2223 except Exception as oXcpt:
2224 if vbox.ComError.notEqual(oXcpt, vbox.ComError.VBOX_E_OBJECT_NOT_FOUND):
2225 if fUseDirList:
2226 fRc = reporter.errorXcpt('Error listing directory "%s" (cEntriesToRead=%d):' % \
2227 (oDir.sPath, cEntriesToRead));
2228 else:
2229 fRc = reporter.errorXcpt('Error reading directory "%s":' % (oDir.sPath));
2230 else:
2231 reporter.log2('\tNo more directory entries for "%s"' % (limitString(oDir.sPath),));
2232 break;
2233
2234 reporter.log3('Processing next batch (%d items)...' % (len(aFsObjInfo)));
2235 for oFsObjInfo in aFsObjInfo:
2236 try:
2237 sName = oFsObjInfo.name;
2238 eType = oFsObjInfo.type;
2239 cbFile = oFsObjInfo.objectSize;
2240 ## @todo check further attributes.
2241 except:
2242 fRc = reporter.errorXcpt();
2243 break;
2244
2245 # '.' and '..' entries are not present in oDir.aoChildren, so special treatment:
2246 if sName in ('.', '..', ):
2247 if eType != vboxcon.FsObjType_Directory:
2248 fRc = reporter.error('Wrong type for "%s": %d, expected %d (Directory)'
2249 % (sName, eType, vboxcon.FsObjType_Directory));
2250 if sName == '.': cDot += 1;
2251 else: cDotDot += 1;
2252 else:
2253 # Find the child and remove it from the dictionary.
2254 sNameUpper = sName.upper();
2255 oFsObj = dLeftUpper.get(sNameUpper);
2256 if oFsObj is None:
2257 fRc = reporter.error('Unknown object "%s" found in "%s" (type %s, size %s)!'
2258 % (sName, oDir.sPath, eType, cbFile,));
2259 else:
2260 del dLeftUpper[sNameUpper];
2261
2262 # Check type
2263 if isinstance(oFsObj, testfileset.TestDir):
2264 if eType != vboxcon.FsObjType_Directory:
2265 fRc = reporter.error('%s: expected directory (%d), got eType=%d!'
2266 % (oFsObj.sPath, vboxcon.FsObjType_Directory, eType,));
2267 elif isinstance(oFsObj, testfileset.TestFile):
2268 if eType != vboxcon.FsObjType_File:
2269 fRc = reporter.error('%s: expected file (%d), got eType=%d!'
2270 % (oFsObj.sPath, vboxcon.FsObjType_File, eType,));
2271 else:
2272 fRc = reporter.error('%s: WTF? type=%s' % (oFsObj.sPath, type(oFsObj),));
2273
2274 # Check the name.
2275 if oFsObj.sName != sName:
2276 fRc = reporter.error('%s: expected name "%s", got "%s" instead!' % \
2277 (oFsObj.sPath, oFsObj.sName, sName,));
2278
2279 # Check the size if a file.
2280 if isinstance(oFsObj, testfileset.TestFile) and cbFile != oFsObj.cbContent:
2281 fRc = reporter.error('%s: expected size %s, got %s instead!' % \
2282 (oFsObj.sPath, oFsObj.cbContent, cbFile,));
2283
2284 ## @todo check timestamps and attributes.
2285
2286 # Close the directory
2287 try:
2288 oCurDir.close();
2289 except:
2290 fRc = reporter.errorXcpt('oDir.sPath=%s' % (oDir.sPath,));
2291
2292 # Any files left over?
2293 for sKey in dLeftUpper:
2294 oFsObj = dLeftUpper[sKey];
2295 fRc = reporter.error('%s: Was not returned! (%s)' % (oFsObj.sPath, type(oFsObj),));
2296
2297 # Check the dot and dot-dot counts.
2298 if cDot != 1:
2299 fRc = reporter.error('%s: Found %s "." entries, expected exactly 1!' % (oDir.sPath, cDot,));
2300 if cDotDot != 1:
2301 fRc = reporter.error('%s: Found %s ".." entries, expected exactly 1!' % (oDir.sPath, cDotDot,));
2302
2303 #
2304 # Recurse into subdirectories using info from oDir.
2305 #
2306 for oFsObj in oDir.aoChildren:
2307 if isinstance(oFsObj, testfileset.TestDir):
2308 fRc = self.gctrlReadDirTree2(oGuestSession, oFsObj, fUseDirList, cEntriesPerRead) and fRc;
2309
2310 return fRc;
2311
2312 def gctrlExecDoTest(self, i, oTest, oRes, oGuestSession):
2313 """
2314 Wrapper function around gctrlExecute to provide more sanity checking
2315 when needed in actual execution tests.
2316 """
2317 reporter.log('Testing #%d, cmd="%s" ...' % (i, oTest.sCmd));
2318 fRcExec = self.gctrlExecute(oTest, oGuestSession, oRes.fRc);
2319 if fRcExec == oRes.fRc:
2320 fRc = True;
2321 if fRcExec is True:
2322 # Compare exit status / code on successful process execution.
2323 if oTest.uExitStatus != oRes.uExitStatus \
2324 or oTest.iExitCode != oRes.iExitCode:
2325 fRc = reporter.error('Test #%d (%s) failed: Got exit status + code %d,%d, expected %d,%d'
2326 % (i, oTest.asArgs, oTest.uExitStatus, oTest.iExitCode,
2327 oRes.uExitStatus, oRes.iExitCode));
2328
2329 # Compare test / result buffers on successful process execution.
2330 if oTest.sBuf is not None and oRes.sBuf is not None:
2331 if not utils.areBytesEqual(oTest.sBuf, oRes.sBuf):
2332 fRc = reporter.error('Test #%d (%s) failed: Got buffer\n%s (%d bytes), expected\n%s (%d bytes)'
2333 % (i, oTest.asArgs,
2334 map(hex, map(ord, oTest.sBuf)), len(oTest.sBuf),
2335 map(hex, map(ord, oRes.sBuf)), len(oRes.sBuf)));
2336 reporter.log2('Test #%d passed: Buffers match (%d bytes)' % (i, len(oRes.sBuf)));
2337 elif oRes.sBuf and not oTest.sBuf:
2338 fRc = reporter.error('Test #%d (%s) failed: Got no buffer data, expected\n%s (%dbytes)' %
2339 (i, oTest.asArgs, map(hex, map(ord, oRes.sBuf)), len(oRes.sBuf),));
2340
2341 if oRes.cbStdOut is not None and oRes.cbStdOut != oTest.cbStdOut:
2342 fRc = reporter.error('Test #%d (%s) failed: Got %d bytes of stdout data, expected %d'
2343 % (i, oTest.asArgs, oTest.cbStdOut, oRes.cbStdOut));
2344 if oRes.cbStdErr is not None and oRes.cbStdErr != oTest.cbStdErr:
2345 fRc = reporter.error('Test #%d (%s) failed: Got %d bytes of stderr data, expected %d'
2346 % (i, oTest.asArgs, oTest.cbStdErr, oRes.cbStdErr));
2347 else:
2348 fRc = reporter.error('Test #%d (%s) failed: Got %s, expected %s' % (i, oTest.asArgs, fRcExec, oRes.fRc));
2349 return fRc;
2350
2351 def processCreateWrapper(self, oGuestSession, sCmd, asArgs, sCwd, aEnv, afFlags, timeoutMS):
2352 """
2353 Wrapepr function to deal with different flavors of the IGuestProcess::processCreate call,
2354 depending on the API version.
2355
2356 Returns oProcess object on success, None on failure.
2357 """
2358 oProcess = None;
2359
2360 reporter.log2('Executing sCmd=%s, cCwd=%s, afFlags=%s, timeoutMS=%d, asArgs=%s, asEnv=%s'
2361 % (sCmd, sCwd, afFlags, timeoutMS, limitString(asArgs), limitString(aEnv),));
2362
2363 if self.oTstDrv.fpApiVer >= 7.1 and self.oTstDrv.uRevision >= 156485:
2364 # 7.1 adds a current working directory parameter.
2365 oProcess = oGuestSession.processCreate(sCmd, asArgs, sCwd, aEnv, afFlags, timeoutMS);
2366 else:
2367 oProcess = oGuestSession.processCreate(sCmd,
2368 asArgs if self.oTstDrv.fpApiVer >= 5.0 else asArgs[1:],
2369 aEnv, afFlags, timeoutMS);
2370 return oProcess;
2371
2372 def processExecute(self, oGuestSession, sCmd, asArgs, sCwd, aEnv, afFlags, timeoutMS, fIsError = True):
2373 """
2374 Executes a process on the guest and deals with input/output + waiting flags.
2375
2376 Returns tuple (success, exit status, exit code, stdout len, stderr len, stdout / stderr output).
2377 """
2378
2379 #
2380 # Start the process:
2381 #
2382 try:
2383 oProcess = self.processCreateWrapper(oGuestSession, sCmd, asArgs, sCwd, aEnv, afFlags, timeoutMS);
2384 except:
2385 reporter.maybeErrXcpt(fIsError, 'type=%s, asArgs=%s' % (type(asArgs), asArgs,));
2386 return False;
2387 if oProcess is None:
2388 return reporter.error('oProcess is None! (%s)' % (asArgs,));
2389
2390 fRc = True;
2391 uExitStatus = vboxcon.ProcessStatus_Undefined;
2392 iExitCode = -1;
2393 cbStdOut = 0;
2394 cbStdErr = 0;
2395 sBufOut = '';
2396
2397 #time.sleep(5); # try this if you want to see races here.
2398
2399 # Wait for the process to start properly:
2400 reporter.log2('Process start requested, waiting for start (%dms) ...' % (timeoutMS,));
2401 iPid = -1;
2402 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Start, ];
2403 try:
2404 eWaitResult = oProcess.waitForArray(aeWaitFor, timeoutMS);
2405 except:
2406 reporter.maybeErrXcpt(fIsError, 'waitforArray failed for asArgs=%s' % (asArgs,));
2407 fRc = False;
2408 else:
2409 try:
2410 eStatus = oProcess.status;
2411 iPid = oProcess.PID;
2412 except:
2413 fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
2414 else:
2415 reporter.log2('Wait result returned: %d, current process status is: %d' % (eWaitResult, eStatus,));
2416
2417 #
2418 # Wait for the process to run to completion if necessary.
2419 #
2420 # Note! The above eWaitResult return value can be ignored as it will
2421 # (mostly) reflect the process status anyway.
2422 #
2423 if eStatus == vboxcon.ProcessStatus_Started:
2424
2425 # What to wait for:
2426 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate, ];
2427 if vboxcon.ProcessCreateFlag_WaitForStdOut in afFlags:
2428 aeWaitFor.append(vboxcon.ProcessWaitForFlag_StdOut);
2429 if vboxcon.ProcessCreateFlag_WaitForStdErr in afFlags:
2430 aeWaitFor.append(vboxcon.ProcessWaitForFlag_StdErr);
2431 ## @todo Add vboxcon.ProcessWaitForFlag_StdIn.
2432
2433 reporter.log2('Process (PID %d) started, waiting for termination (%dms), aeWaitFor=%s ...'
2434 % (iPid, timeoutMS, aeWaitFor));
2435 acbFdOut = [0,0,0];
2436 while True:
2437 try:
2438 eWaitResult = oProcess.waitForArray(aeWaitFor, timeoutMS);
2439 except KeyboardInterrupt: # Not sure how helpful this is, but whatever.
2440 reporter.error('Process (PID %d) execution interrupted' % (iPid,));
2441 try: oProcess.close();
2442 except: pass;
2443 break;
2444 except:
2445 fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
2446 break;
2447 #reporter.log2('Wait returned: %d' % (eWaitResult,));
2448
2449 # Process output:
2450 for eFdResult, iFd, sFdNm in [ (vboxcon.ProcessWaitResult_StdOut, 1, 'stdout'),
2451 (vboxcon.ProcessWaitResult_StdErr, 2, 'stderr'), ]:
2452 if eWaitResult in (eFdResult, vboxcon.ProcessWaitResult_WaitFlagNotSupported):
2453 try:
2454 abBuf = oProcess.read(iFd, 64 * 1024, timeoutMS);
2455 except KeyboardInterrupt: # Not sure how helpful this is, but whatever.
2456 reporter.error('Process (PID %d) execution interrupted' % (iPid,));
2457 try: oProcess.close();
2458 except: pass;
2459 except:
2460 reporter.maybeErrXcpt(fIsError, 'asArgs=%s' % (asArgs,));
2461 else:
2462 if abBuf:
2463 reporter.log2('Process (PID %d) got %d bytes of %s data (type: %s)'
2464 % (iPid, len(abBuf), sFdNm, type(abBuf)));
2465 if reporter.getVerbosity() >= 4:
2466 sBufOut = '';
2467 if sys.version_info >= (2, 7):
2468 if isinstance(abBuf, memoryview): ## @todo Why is this happening?
2469 abBuf = abBuf.tobytes();
2470 sBufOut = abBuf.decode("utf-8");
2471 if sys.version_info <= (2, 7):
2472 if isinstance(abBuf, buffer): # (for 3.0+) pylint: disable=undefined-variable
2473 sBufOut = str(abBuf);
2474 for sLine in sBufOut.splitlines():
2475 reporter.log4('%s: %s' % (sFdNm, sLine));
2476 acbFdOut[iFd] += len(abBuf);
2477 sBufOut = abBuf; ## @todo Figure out how to uniform + append!
2478
2479 ## Process input (todo):
2480 #if eWaitResult in (vboxcon.ProcessWaitResult_StdIn, vboxcon.ProcessWaitResult_WaitFlagNotSupported):
2481 # reporter.log2('Process (PID %d) needs stdin data' % (iPid,));
2482
2483 # Termination or error?
2484 if eWaitResult in (vboxcon.ProcessWaitResult_Terminate,
2485 vboxcon.ProcessWaitResult_Error,
2486 vboxcon.ProcessWaitResult_Timeout,):
2487 try: eStatus = oProcess.status;
2488 except: fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
2489 reporter.log2('Process (PID %d) reported terminate/error/timeout: %d, status: %d'
2490 % (iPid, eWaitResult, eStatus,));
2491 break;
2492
2493 # End of the wait loop.
2494 _, cbStdOut, cbStdErr = acbFdOut;
2495
2496 try: eStatus = oProcess.status;
2497 except: fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
2498 reporter.log2('Final process status (PID %d) is: %d' % (iPid, eStatus));
2499 reporter.log2('Process (PID %d) %d stdout, %d stderr' % (iPid, cbStdOut, cbStdErr));
2500
2501 #
2502 # Get the final status and exit code of the process.
2503 #
2504 try:
2505 uExitStatus = oProcess.status;
2506 iExitCode = oProcess.exitCode;
2507 except:
2508 fRc = reporter.errorXcpt('asArgs=%s' % (asArgs,));
2509 reporter.log2('Process (PID %d) has exit code: %d; status: %d ' % (iPid, iExitCode, uExitStatus));
2510 return fRc, uExitStatus, iExitCode, cbStdOut, cbStdErr, sBufOut;
2511
2512 def gctrlExecute(self, oTest, oGuestSession, fIsError): # pylint: disable=too-many-statements
2513 """
2514 Helper function to execute a program on a guest, specified in the current test.
2515
2516 Note! This weirdo returns results (process exitcode and status) in oTest.
2517 """
2518 fRc = True; # Be optimistic.
2519
2520 # Reset the weird result stuff:
2521 oTest.cbStdOut = 0;
2522 oTest.cbStdErr = 0;
2523 oTest.sBuf = '';
2524 oTest.uExitStatus = 0;
2525 oTest.iExitCode = 0;
2526
2527 ## @todo Compare execution timeouts!
2528 #tsStart = base.timestampMilli();
2529
2530 try:
2531 reporter.log2('Using session user=%s, sDomain=%s, name=%s, timeout=%d'
2532 % (oGuestSession.user, oGuestSession.domain, oGuestSession.name, oGuestSession.timeout,));
2533 except:
2534 return reporter.errorXcpt();
2535
2536 fRc, oTest.uExitStatus, oTest.iExitCode, oTest.cbStdOut, oTest.cbStdErr, oTest.sBuf = \
2537 self.processExecute(oGuestSession, oTest.sCmd, oTest.asArgs, oTest.sCwd,
2538 oTest.aEnv, oTest.afFlags, oTest.timeoutMS, fIsError);
2539
2540 return fRc;
2541
2542 def executeGstCtlHelper(self, oTxsSession, oGuestSession, asArgs, asEnv = None, sCwd = '', timeoutMS = 30 * 1000):
2543 """
2544 Wrapper to invoke the Guest Control Helper on the guest.
2545
2546 Returns tuple (success, exit status, exit code, stdout len, stderr len, stdout / stderr output).
2547 """
2548 fRc = True;
2549 eExitStatus = vboxcon.ProcessStatus_Undefined;
2550 iExitCode = -1;
2551 cbStdOut = 0;
2552 cbStdErr = 0;
2553 sBuf = '';
2554
2555 if not self.sGstCtlHelperExe:
2556 fRc, self.sGstCtlHelperExe = self.locateGstBinary(oTxsSession, self.asGstCtlHelperPaths);
2557 if fRc:
2558 reporter.log('Using VBoxGuestControlHelper on guest at \"%s\"' % (self.sGstCtlHelperExe));
2559
2560 if fRc \
2561 and self.sGstCtlHelperExe:
2562 try:
2563 asArgs2 = [ self.sGstCtlHelperExe ];
2564 asArgs2.append(asArgs); # Always set argv0.
2565 if not asEnv:
2566 asEnv = [];
2567 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate, \
2568 vboxcon.ProcessWaitForFlag_StdOut, \
2569 vboxcon.ProcessWaitForFlag_StdErr ];
2570
2571 fRc, eExitStatus, iExitCode, cbStdOut, cbStdErr, sBuf = \
2572 self.processExecute(oGuestSession, self.sGstCtlHelperExe, asArgs2, sCwd,
2573 asEnv, aeWaitFor, timeoutMS);
2574 if eExitStatus != vboxcon.TerminatedNormally:
2575 reporter.log('VBoxGuestControlHelper failed to run; got exit status %d' % (eExitStatus,));
2576 fRc = False;
2577 except:
2578 reporter.errorXcpt();
2579
2580 return fRc, eExitStatus, iExitCode, cbStdOut, cbStdErr, sBuf;
2581
2582 def testGuestCtrlSessionEnvironment(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
2583 """
2584 Tests the guest session environment changes.
2585 """
2586 aoTests = [
2587 # Check basic operations.
2588 tdTestSessionEx([ # Initial environment is empty.
2589 tdStepSessionCheckEnv(),
2590 # Check clearing empty env.
2591 tdStepSessionClearEnv(),
2592 tdStepSessionCheckEnv(),
2593 # Check set.
2594 tdStepSessionSetEnv('FOO', 'BAR'),
2595 tdStepSessionCheckEnv(['FOO=BAR',]),
2596 tdStepRequireMinimumApiVer(5.0), # 4.3 can't cope with the remainder.
2597 tdStepSessionClearEnv(),
2598 tdStepSessionCheckEnv(),
2599 # Check unset.
2600 tdStepSessionUnsetEnv('BAR'),
2601 tdStepSessionCheckEnv(['BAR']),
2602 tdStepSessionClearEnv(),
2603 tdStepSessionCheckEnv(),
2604 # Set + unset.
2605 tdStepSessionSetEnv('FOO', 'BAR'),
2606 tdStepSessionCheckEnv(['FOO=BAR',]),
2607 tdStepSessionUnsetEnv('FOO'),
2608 tdStepSessionCheckEnv(['FOO']),
2609 # Bulk environment changes (via attrib) (shall replace existing 'FOO').
2610 tdStepSessionBulkEnv( ['PATH=/bin:/usr/bin', 'TMPDIR=/var/tmp', 'USER=root']),
2611 tdStepSessionCheckEnv(['PATH=/bin:/usr/bin', 'TMPDIR=/var/tmp', 'USER=root']),
2612 ]),
2613 tdTestSessionEx([ # Check that setting the same value several times works.
2614 tdStepSessionSetEnv('FOO','BAR'),
2615 tdStepSessionCheckEnv([ 'FOO=BAR',]),
2616 tdStepSessionSetEnv('FOO','BAR2'),
2617 tdStepSessionCheckEnv([ 'FOO=BAR2',]),
2618 tdStepSessionSetEnv('FOO','BAR3'),
2619 tdStepSessionCheckEnv([ 'FOO=BAR3',]),
2620 tdStepRequireMinimumApiVer(5.0), # 4.3 can't cope with the remainder.
2621 # Add a little unsetting to the mix.
2622 tdStepSessionSetEnv('BAR', 'BEAR'),
2623 tdStepSessionCheckEnv([ 'FOO=BAR3', 'BAR=BEAR',]),
2624 tdStepSessionUnsetEnv('FOO'),
2625 tdStepSessionCheckEnv([ 'FOO', 'BAR=BEAR',]),
2626 tdStepSessionSetEnv('FOO','BAR4'),
2627 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR',]),
2628 # The environment is case sensitive.
2629 tdStepSessionSetEnv('foo','BAR5'),
2630 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR', 'foo=BAR5']),
2631 tdStepSessionUnsetEnv('foo'),
2632 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR', 'foo']),
2633 ]),
2634 tdTestSessionEx([ # Bulk settings merges stuff, last entry standing.
2635 tdStepSessionBulkEnv(['FOO=bar', 'foo=bar', 'FOO=doofus', 'TMPDIR=/tmp', 'foo=bar2']),
2636 tdStepSessionCheckEnv(['FOO=doofus', 'TMPDIR=/tmp', 'foo=bar2']),
2637 tdStepRequireMinimumApiVer(5.0), # 4.3 is buggy!
2638 tdStepSessionBulkEnv(['2=1+1', 'FOO=doofus2', ]),
2639 tdStepSessionCheckEnv(['2=1+1', 'FOO=doofus2' ]),
2640 ]),
2641 # Invalid variable names.
2642 tdTestSessionEx([
2643 tdStepSessionSetEnv('', 'FOO', vbox.ComError.E_INVALIDARG),
2644 tdStepSessionCheckEnv(),
2645 tdStepRequireMinimumApiVer(5.0), # 4.3 is too relaxed checking input!
2646 tdStepSessionBulkEnv(['', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2647 tdStepSessionCheckEnv(),
2648 tdStepSessionSetEnv('FOO=', 'BAR', vbox.ComError.E_INVALIDARG),
2649 tdStepSessionCheckEnv(),
2650 ]),
2651 # A bit more weird keys/values.
2652 tdTestSessionEx([ tdStepSessionSetEnv('$$$', ''),
2653 tdStepSessionCheckEnv([ '$$$=',]), ]),
2654 tdTestSessionEx([ tdStepSessionSetEnv('$$$', '%%%'),
2655 tdStepSessionCheckEnv([ '$$$=%%%',]),
2656 ]),
2657 tdTestSessionEx([ tdStepRequireMinimumApiVer(5.0), # 4.3 is buggy!
2658 tdStepSessionSetEnv(u'ß$%ß&', ''),
2659 tdStepSessionCheckEnv([ u'ß$%ß&=',]),
2660 ]),
2661 # Misc stuff.
2662 tdTestSessionEx([ tdStepSessionSetEnv('FOO', ''),
2663 tdStepSessionCheckEnv(['FOO=',]),
2664 ]),
2665 tdTestSessionEx([ tdStepSessionSetEnv('FOO', 'BAR'),
2666 tdStepSessionCheckEnv(['FOO=BAR',])
2667 ],),
2668 tdTestSessionEx([ tdStepSessionSetEnv('FOO', 'BAR'),
2669 tdStepSessionSetEnv('BAR', 'BAZ'),
2670 tdStepSessionCheckEnv([ 'FOO=BAR', 'BAR=BAZ',]),
2671 ]),
2672 ];
2673 # Leading '=' in the name is okay for windows guests in 6.1 and later (for driver letter CWDs).
2674 if (self.oTstDrv.fpApiVer < 6.1 and self.oTstDrv.fpApiVer >= 5.0) or not oTestVm.isWindows():
2675 aoTests.append(tdTestSessionEx([tdStepSessionSetEnv('=', '===', vbox.ComError.E_INVALIDARG),
2676 tdStepSessionCheckEnv(),
2677 tdStepSessionSetEnv('=FOO', 'BAR', vbox.ComError.E_INVALIDARG),
2678 tdStepSessionCheckEnv(),
2679 tdStepSessionBulkEnv(['=', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2680 tdStepSessionCheckEnv(),
2681 tdStepSessionBulkEnv(['=FOO', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2682 tdStepSessionCheckEnv(),
2683 tdStepSessionBulkEnv(['=D:=D:/tmp', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2684 tdStepSessionCheckEnv(),
2685 tdStepSessionSetEnv('=D:', 'D:/temp', vbox.ComError.E_INVALIDARG),
2686 tdStepSessionCheckEnv(),
2687 ]));
2688 elif self.oTstDrv.fpApiVer >= 6.1 and oTestVm.isWindows():
2689 aoTests.append(tdTestSessionEx([tdStepSessionSetEnv('=D:', 'D:/tmp'),
2690 tdStepSessionCheckEnv(['=D:=D:/tmp',]),
2691 tdStepSessionBulkEnv(['=D:=D:/temp', '=FOO', 'foo=bar']),
2692 tdStepSessionCheckEnv(['=D:=D:/temp', '=FOO', 'foo=bar']),
2693 tdStepSessionUnsetEnv('=D:'),
2694 tdStepSessionCheckEnv(['=D:', '=FOO', 'foo=bar']),
2695 ]));
2696
2697 return tdTestSessionEx.executeListTestSessions(aoTests, self.oTstDrv, oSession, oTxsSession, oTestVm, 'SessionEnv');
2698
2699 def testGuestCtrlSessionSimple(self, oSession, oTxsSession, oTestVm):
2700 """
2701 Tests simple session-based API calls.
2702 """
2703
2704 reporter.log('Testing simple session-based API calls ...');
2705
2706 # Start a valid session.
2707 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
2708 try:
2709 oCreds = tdCtxCreds();
2710 oCreds.applyDefaultsIfNotSet(oTestVm);
2711 oGuest = oSession.o.console.guest;
2712 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionSimple");
2713 oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
2714 except:
2715 reporter.logXcpt('Starting session for session-based API calls failed');
2716 return False;
2717
2718 if self.oTstDrv.fpApiVer >= 7.1 \
2719 and oTestVm.isWindows():
2720 reporter.testStart('Windows guest processes in session >= 1');
2721 # Test in which Windows session Guest Control processes are being started.
2722 # We don't want them to be started in session 0, as this would prevent desktop interaction and other stuff.
2723 fRc, eExitStatus, iExitCode, _, _, _ = \
2724 self.executeGstCtlHelper(oSession, oTxsSession, oGuestSession, [ "show", "win-session-id" ]);
2725 if fRc \
2726 and eExitStatus == vboxcon.TerminatedNormally:
2727 if iExitCode >= 1000: # We report 1000 + <session ID> as exit code.
2728 uSessionId = iExitCode - 1000;
2729 if uSessionId == 0:
2730 reporter.log('Guest processes start in session %d, good' % (uSessionId));
2731 else:
2732 reporter.error('Guest processes start in session %d, expected session 0' % (uSessionId));
2733 else:
2734 reporter.error('Guest Control Helper returned error %d (exit code)' % (iExitCode));
2735 reporter.testDone();
2736
2737 # User home.
2738 if self.oTstDrv.fpApiVer >= 7.0:
2739 reporter.log('Getting user\'s home directory ...');
2740 try:
2741 reporter.log('User home directory: %s' % (oGuestSession.userHome));
2742 except:
2743 fRc = reporter.logXcpt('Getting user home directory failed');
2744
2745 # User documents.
2746 if self.oTstDrv.fpApiVer >= 7.0:
2747 reporter.log('Getting user\'s documents directory ...');
2748 try:
2749 reporter.log('User documents directory: %s' % (oGuestSession.userDocuments));
2750 except:
2751 fRc = reporter.logXcpt('Getting user documents directory failed');
2752
2753 # Mount points. Only available for Guest Additions >= 7.1.
2754 if self.oTstDrv.fpApiVer >= 7.1:
2755 reporter.log('Getting mount points ...');
2756 try:
2757 aMountpoints = oGuestSession.getMountPoints();
2758 reporter.log('Got %ld mount points' % len(aMountpoints))
2759 for mountPoint in aMountpoints:
2760 reporter.log('Mountpoint: %s' % (mountPoint));
2761 except:
2762 fRc = reporter.logXcpt('Getting mount points failed');
2763
2764 # Close the session.
2765 try:
2766 oGuestSession.close();
2767 except:
2768 fRc = reporter.errorXcpt('Closing guest session failed');
2769
2770 return fRc;
2771
2772 def testGuestCtrlSession(self, oSession, oTxsSession, oTestVm):
2773 """
2774 Tests the guest session handling.
2775 """
2776
2777 #
2778 # Tests:
2779 #
2780 atTests = [
2781 # Invalid parameters.
2782 [ tdTestSession(sUser = ''), tdTestResultSession() ],
2783 # User account without a passwort - forbidden.
2784 [ tdTestSession(sPassword = "" ), tdTestResultSession() ],
2785 # Various wrong credentials.
2786 # Note! Only windows cares about sDomain, the other guests ignores it.
2787 # Note! On Guest Additions < 4.3 this always succeeds because these don't
2788 # support creating dedicated sessions. Instead, guest process creation
2789 # then will fail. See note below.
2790 [ tdTestSession(sPassword = 'bar'), tdTestResultSession() ],
2791 [ tdTestSession(sUser = 'foo', sPassword = 'bar'), tdTestResultSession() ],
2792 [ tdTestSession(sPassword = 'bar', sDomain = 'boo'), tdTestResultSession() ],
2793 [ tdTestSession(sUser = 'foo', sPassword = 'bar', sDomain = 'boo'), tdTestResultSession() ],
2794 ];
2795 if oTestVm.isWindows(): # domain is ignored elsewhere.
2796 atTests.append([ tdTestSession(sDomain = 'boo'), tdTestResultSession() ]);
2797
2798 # Finally, correct credentials.
2799 atTests.append([ tdTestSession(), tdTestResultSession(fRc = True, cNumSessions = 1) ]);
2800
2801 #
2802 # Run the tests.
2803 #
2804 fRc = True;
2805 for (i, tTest) in enumerate(atTests):
2806 oCurTest = tTest[0] # type: tdTestSession
2807 oCurRes = tTest[1] # type: tdTestResult
2808
2809 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
2810 if not fRc:
2811 break;
2812 reporter.log('Testing #%d, user="%s", sPassword="%s", sDomain="%s" ...'
2813 % (i, oCurTest.oCreds.sUser, oCurTest.oCreds.sPassword, oCurTest.oCreds.sDomain));
2814 sCurGuestSessionName = 'testGuestCtrlSession: Test #%d' % (i,);
2815 fRc2, oCurGuestSession = oCurTest.createSession(sCurGuestSessionName, fIsError = oCurRes.fRc);
2816
2817 # See note about < 4.3 Guest Additions above.
2818 uProtocolVersion = 2;
2819 if oCurGuestSession is not None:
2820 try:
2821 uProtocolVersion = oCurGuestSession.protocolVersion;
2822 except:
2823 fRc = reporter.errorXcpt('Test #%d' % (i,));
2824
2825 if uProtocolVersion >= 2 and fRc2 is not oCurRes.fRc:
2826 fRc = reporter.error('Test #%d failed: Session creation failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc,));
2827
2828 if fRc2 and oCurGuestSession is None:
2829 fRc = reporter.error('Test #%d failed: no session object' % (i,));
2830 fRc2 = False;
2831
2832 if fRc2:
2833 if uProtocolVersion >= 2: # For Guest Additions < 4.3 getSessionCount() always will return 1.
2834 cCurSessions = oCurTest.getSessionCount(self.oTstDrv.oVBoxMgr);
2835 if cCurSessions != oCurRes.cNumSessions:
2836 fRc = reporter.error('Test #%d failed: Session count does not match: Got %d, expected %d'
2837 % (i, cCurSessions, oCurRes.cNumSessions));
2838 try:
2839 sObjName = oCurGuestSession.name;
2840 except:
2841 fRc = reporter.errorXcpt('Test #%d' % (i,));
2842 else:
2843 if sObjName != sCurGuestSessionName:
2844 fRc = reporter.error('Test #%d failed: Session name does not match: Got "%s", expected "%s"'
2845 % (i, sObjName, sCurGuestSessionName));
2846 fRc2 = oCurTest.closeSession();
2847 if fRc2 is False:
2848 fRc = reporter.error('Test #%d failed: Session could not be closed' % (i,));
2849
2850 if fRc is False:
2851 return (False, oTxsSession);
2852
2853 #
2854 # Multiple sessions.
2855 #
2856 cMaxGuestSessions = 31; # Maximum number of concurrent guest session allowed.
2857 # Actually, this is 32, but we don't test session 0.
2858 aoMultiSessions = {};
2859 reporter.log2('Opening multiple guest tsessions at once ...');
2860 for i in xrange(cMaxGuestSessions + 1):
2861 aoMultiSessions[i] = tdTestSession(sSessionName = 'MultiSession #%d' % (i,));
2862 fRc = aoMultiSessions[i].setEnvironment(oSession, oTxsSession, oTestVm);
2863 if not fRc:
2864 break;
2865
2866 cCurSessions = aoMultiSessions[i].getSessionCount(self.oTstDrv.oVBoxMgr);
2867 reporter.log2('MultiSession test #%d count is %d' % (i, cCurSessions));
2868 if cCurSessions != i:
2869 return (reporter.error('MultiSession count is %d, expected %d' % (cCurSessions, i)), oTxsSession);
2870 fRc2, _ = aoMultiSessions[i].createSession('MultiSession #%d' % (i,), i < cMaxGuestSessions);
2871 if fRc2 is not True:
2872 if i < cMaxGuestSessions:
2873 return (reporter.error('MultiSession #%d test failed' % (i,)), oTxsSession);
2874 reporter.log('MultiSession #%d exceeded concurrent guest session count, good' % (i,));
2875 break;
2876
2877 cCurSessions = aoMultiSessions[i].getSessionCount(self.oTstDrv.oVBoxMgr);
2878 if cCurSessions is not cMaxGuestSessions:
2879 return (reporter.error('Final session count %d, expected %d ' % (cCurSessions, cMaxGuestSessions,)), oTxsSession);
2880
2881 reporter.log2('Closing MultiSessions ...');
2882 for i in xrange(cMaxGuestSessions):
2883 # Close this session:
2884 oClosedGuestSession = aoMultiSessions[i].oGuestSession;
2885 fRc2 = aoMultiSessions[i].closeSession();
2886 cCurSessions = aoMultiSessions[i].getSessionCount(self.oTstDrv.oVBoxMgr)
2887 reporter.log2('MultiSession #%d count is %d' % (i, cCurSessions,));
2888 if fRc2 is False:
2889 fRc = reporter.error('Closing MultiSession #%d failed' % (i,));
2890 elif cCurSessions != cMaxGuestSessions - (i + 1):
2891 fRc = reporter.error('Expected %d session after closing #%d, got %d instead'
2892 % (cMaxGuestSessions - (i + 1), cCurSessions, i,));
2893 assert aoMultiSessions[i].oGuestSession is None or not fRc2;
2894 ## @todo any way to check that the session is closed other than the 'sessions' attribute?
2895
2896 # Try check that none of the remaining sessions got closed.
2897 try:
2898 aoGuestSessions = self.oTstDrv.oVBoxMgr.getArray(atTests[0][0].oGuest, 'sessions');
2899 except:
2900 return (reporter.errorXcpt('i=%d/%d' % (i, cMaxGuestSessions,)), oTxsSession);
2901 if oClosedGuestSession in aoGuestSessions:
2902 fRc = reporter.error('i=%d/%d: %s should not be in %s'
2903 % (i, cMaxGuestSessions, oClosedGuestSession, aoGuestSessions));
2904 if i + 1 < cMaxGuestSessions: # Not sure what xrange(2,2) does...
2905 for j in xrange(i + 1, cMaxGuestSessions):
2906 if aoMultiSessions[j].oGuestSession not in aoGuestSessions:
2907 fRc = reporter.error('i=%d/j=%d/%d: %s should be in %s'
2908 % (i, j, cMaxGuestSessions, aoMultiSessions[j].oGuestSession, aoGuestSessions));
2909 ## @todo any way to check that they work?
2910
2911 ## @todo Test session timeouts.
2912
2913 fRc2 = self.testGuestCtrlSessionSimple(oSession, oTxsSession, oTestVm);
2914 if fRc:
2915 fRc = fRc2;
2916
2917 return (fRc, oTxsSession);
2918
2919 def testGuestCtrlSessionFileRefs(self, oSession, oTxsSession, oTestVm):
2920 """
2921 Tests the guest session file reference handling.
2922 """
2923
2924 # Find a file to play around with:
2925 sFile = self.oTstDrv.getGuestSystemFileForReading(oTestVm);
2926
2927 # Use credential defaults.
2928 oCreds = tdCtxCreds();
2929 oCreds.applyDefaultsIfNotSet(oTestVm);
2930
2931 # Number of stale guest files to create.
2932 cStaleFiles = 10;
2933
2934 #
2935 # Start a session.
2936 #
2937 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
2938 try:
2939 oGuest = oSession.o.console.guest;
2940 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionFileRefs");
2941 eWaitResult = oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
2942 except:
2943 return (reporter.errorXcpt(), oTxsSession);
2944
2945 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
2946 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
2947 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
2948 reporter.log('Session successfully started');
2949
2950 #
2951 # Open guest files and "forget" them (stale entries).
2952 # For them we don't have any references anymore intentionally.
2953 #
2954 reporter.log2('Opening stale files');
2955 fRc = True;
2956 for i in xrange(0, cStaleFiles):
2957 try:
2958 if self.oTstDrv.fpApiVer >= 5.0:
2959 oGuestSession.fileOpen(sFile, vboxcon.FileAccessMode_ReadOnly, vboxcon.FileOpenAction_OpenExisting, 0);
2960 else:
2961 oGuestSession.fileOpen(sFile, "r", "oe", 0);
2962 # Note: Use a timeout in the call above for not letting the stale processes
2963 # hanging around forever. This can happen if the installed Guest Additions
2964 # do not support terminating guest processes.
2965 except:
2966 fRc = reporter.errorXcpt('Opening stale file #%d failed:' % (i,));
2967 break;
2968
2969 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
2970 except: fRc = reporter.errorXcpt();
2971 else:
2972 if cFiles != cStaleFiles:
2973 fRc = reporter.error('Got %d stale files, expected %d' % (cFiles, cStaleFiles));
2974
2975 if fRc is True:
2976 #
2977 # Open non-stale files and close them again.
2978 #
2979 reporter.log2('Opening non-stale files');
2980 aoFiles = [];
2981 for i in xrange(0, cStaleFiles):
2982 try:
2983 if self.oTstDrv.fpApiVer >= 5.0:
2984 oCurFile = oGuestSession.fileOpen(sFile, vboxcon.FileAccessMode_ReadOnly,
2985 vboxcon.FileOpenAction_OpenExisting, 0);
2986 else:
2987 oCurFile = oGuestSession.fileOpen(sFile, "r", "oe", 0);
2988 aoFiles.append(oCurFile);
2989 except:
2990 fRc = reporter.errorXcpt('Opening non-stale file #%d failed:' % (i,));
2991 break;
2992
2993 # Check the count.
2994 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
2995 except: fRc = reporter.errorXcpt();
2996 else:
2997 if cFiles != cStaleFiles * 2:
2998 fRc = reporter.error('Got %d total files, expected %d' % (cFiles, cStaleFiles * 2));
2999
3000 # Close them.
3001 reporter.log2('Closing all non-stale files again ...');
3002 for i, oFile in enumerate(aoFiles):
3003 try:
3004 oFile.close();
3005 except:
3006 fRc = reporter.errorXcpt('Closing non-stale file #%d failed:' % (i,));
3007
3008 # Check the count again.
3009 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
3010 except: fRc = reporter.errorXcpt();
3011 # Here we count the stale files (that is, files we don't have a reference
3012 # anymore for) and the opened and then closed non-stale files (that we still keep
3013 # a reference in aoFiles[] for).
3014 if cFiles != cStaleFiles:
3015 fRc = reporter.error('Got %d total files, expected %d' % (cFiles, cStaleFiles));
3016
3017 #
3018 # Check that all (referenced) non-stale files are now in the "closed" state.
3019 #
3020 reporter.log2('Checking statuses of all non-stale files ...');
3021 for i, oFile in enumerate(aoFiles):
3022 try:
3023 eFileStatus = aoFiles[i].status;
3024 except:
3025 fRc = reporter.errorXcpt('Checking status of file #%d failed:' % (i,));
3026 else:
3027 if eFileStatus != vboxcon.FileStatus_Closed:
3028 fRc = reporter.error('Non-stale file #%d has status %d, expected %d'
3029 % (i, eFileStatus, vboxcon.FileStatus_Closed));
3030
3031 if fRc is True:
3032 reporter.log2('All non-stale files closed');
3033
3034 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
3035 except: fRc = reporter.errorXcpt();
3036 else: reporter.log2('Final guest session file count: %d' % (cFiles,));
3037
3038 #
3039 # Now try to close the session and see what happens.
3040 # Note! Session closing is why we've been doing all the 'if fRc is True' stuff above rather than returning.
3041 #
3042 reporter.log2('Closing guest session ...');
3043 try:
3044 oGuestSession.close();
3045 except:
3046 fRc = reporter.errorXcpt('Testing for stale processes failed:');
3047
3048 return (fRc, oTxsSession);
3049
3050 #def testGuestCtrlSessionDirRefs(self, oSession, oTxsSession, oTestVm):
3051 # """
3052 # Tests the guest session directory reference handling.
3053 # """
3054
3055 # fRc = True;
3056 # return (fRc, oTxsSession);
3057
3058 def testGuestCtrlSessionProcRefs(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals,too-many-statements
3059 """
3060 Tests the guest session process reference handling.
3061 """
3062
3063 sShell = self.oTstDrv.getGuestSystemShell(oTestVm);
3064 asArgs = [sShell,];
3065
3066 # Use credential defaults.
3067 oCreds = tdCtxCreds();
3068 oCreds.applyDefaultsIfNotSet(oTestVm);
3069
3070 # Number of guest processes per group to create.
3071 cProcsPerGroup = 10;
3072
3073 #
3074 # Start a session.
3075 #
3076 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
3077 try:
3078 oGuest = oSession.o.console.guest;
3079 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionProcRefs");
3080 eWaitResult = oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
3081 except:
3082 return (reporter.errorXcpt(), oTxsSession);
3083
3084 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
3085 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
3086 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
3087 reporter.log('Session successfully started');
3088
3089 #
3090 # Fire off forever-running processes and "forget" them (stale entries).
3091 # For them we don't have any references anymore intentionally.
3092 #
3093 reporter.log('Starting stale processes...');
3094 fRc = True;
3095 for i in xrange(0, cProcsPerGroup):
3096 try:
3097 reporter.log2('Starting stale process #%d...' % (i));
3098 self.processCreateWrapper(oGuestSession, sShell, asArgs, "", # Working directory.
3099 [], # Environment changes.
3100 [ vboxcon.ProcessCreateFlag_WaitForStdOut ], 30 * 1000);
3101 # Note: Not keeping a process reference from the created process above is intentional and part of the test!
3102
3103 # Note: Use a timeout in the call above for not letting the stale processes
3104 # hanging around forever. This can happen if the installed Guest Additions
3105 # do not support terminating guest processes.
3106 except:
3107 fRc = reporter.errorXcpt('Creating stale process #%d failed:' % (i,));
3108 break;
3109
3110 if fRc:
3111 reporter.log2('Starting stale processes successful');
3112 try: cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
3113 except: fRc = reporter.errorXcpt();
3114 else:
3115 reporter.log2('Proccess count is: %d' % (cProcs));
3116 if cProcs != cProcsPerGroup:
3117 fRc = reporter.error('Got %d stale processes, expected %d (stale)' % (cProcs, cProcsPerGroup));
3118
3119 if fRc:
3120 #
3121 # Fire off non-stale processes and wait for termination.
3122 #
3123 if oTestVm.isWindows() or oTestVm.isOS2():
3124 asArgs = [ sShell, '/C', 'dir', '/S', self.oTstDrv.getGuestSystemDir(oTestVm), ];
3125 else:
3126 asArgs = [ sShell, '-c', 'ls -la ' + self.oTstDrv.getGuestSystemDir(oTestVm), ];
3127 reporter.log('Starting non-stale processes...');
3128 aoProcs = [];
3129 for i in xrange(0, cProcsPerGroup):
3130 try:
3131 reporter.log2('Starting non-stale process #%d...' % (i));
3132 oCurProc = self.processCreateWrapper(oGuestSession, sShell, asArgs,
3133 "", # Working directory.
3134 [], [], 0); # Infinite timeout.
3135 aoProcs.append(oCurProc);
3136 except:
3137 fRc = reporter.errorXcpt('Creating non-stale process #%d failed:' % (i,));
3138 break;
3139
3140 try: cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
3141 except: fRc = reporter.errorXcpt();
3142 else:
3143 reporter.log2('Proccess count is: %d' % (cProcs));
3144
3145 reporter.log('Waiting for non-stale processes to terminate...');
3146 for i, oProcess in enumerate(aoProcs):
3147 try:
3148 reporter.log('Waiting for non-stale process #%d...' % (i));
3149 eWaitResult = oProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate, ], 30 * 1000);
3150 eProcessStatus = oProcess.status;
3151 except:
3152 fRc = reporter.errorXcpt('Waiting for non-stale process #%d failed:' % (i,));
3153 else:
3154 if eProcessStatus != vboxcon.ProcessStatus_TerminatedNormally:
3155 fRc = reporter.error('Waiting for non-stale processes #%d resulted in status %d, expected %d (wr=%d)'
3156 % (i, eProcessStatus, vboxcon.ProcessStatus_TerminatedNormally, eWaitResult));
3157 if fRc:
3158 reporter.log('All non-stale processes ended successfully');
3159
3160 try: cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
3161 except: fRc = reporter.errorXcpt();
3162 else:
3163 reporter.log2('Proccess count is: %d' % (cProcs));
3164
3165 # Here we count the stale processes (that is, processes we don't have a reference
3166 # anymore for) and the started + ended non-stale processes (that we still keep
3167 # a reference in aoProcesses[] for).
3168 cProcsExpected = cProcsPerGroup * 2;
3169 if cProcs != cProcsExpected:
3170 fRc = reporter.error('Got %d total processes, expected %d (stale vs. non-stale)' \
3171 % (cProcs, cProcsExpected));
3172 #
3173 # Fire off non-stale blocking processes which are terminated via terminate().
3174 #
3175 if oTestVm.isWindows() or oTestVm.isOS2():
3176 sCmd = sShell;
3177 asArgs = [ sCmd, '/C', 'pause'];
3178 else:
3179 sCmd = '/usr/bin/yes';
3180 asArgs = [ sCmd ];
3181 reporter.log('Starting blocking processes...');
3182 aoProcs = [];
3183 for i in xrange(0, cProcsPerGroup):
3184 try:
3185 reporter.log2('Starting blocking process #%d...' % (i));
3186 oCurProc = self.processCreateWrapper(oGuestSession, sCmd, asArgs,
3187 "", # Working directory.
3188 [], [], 30 * 1000);
3189
3190 # Note: Use a timeout in the call above for not letting the stale processes
3191 # hanging around forever. This can happen if the installed Guest Additions
3192 # do not support terminating guest processes.
3193 try:
3194 reporter.log('Waiting for blocking process #%d getting started...' % (i));
3195 eWaitResult = oCurProc.waitForArray([ vboxcon.ProcessWaitForFlag_Start, ], 30 * 1000);
3196 eProcessStatus = oCurProc.status;
3197 except:
3198 fRc = reporter.errorXcpt('Waiting for blocking process #%d failed:' % (i,));
3199 else:
3200 if eProcessStatus != vboxcon.ProcessStatus_Started:
3201 fRc = reporter.error('Waiting for blocking processes #%d resulted in status %d, expected %d (wr=%d)'
3202 % (i, eProcessStatus, vboxcon.ProcessStatus_Started, eWaitResult));
3203 aoProcs.append(oCurProc);
3204 except:
3205 fRc = reporter.errorXcpt('Creating blocking process #%d failed:' % (i,));
3206 break;
3207
3208 if fRc:
3209 reporter.log2('Starting blocking processes successful');
3210
3211 reporter.log2('Terminating blocking processes...');
3212 for i, oProcess in enumerate(aoProcs):
3213 try:
3214 reporter.log('Terminating blocking process #%d...' % (i));
3215 oProcess.terminate();
3216 except: # Termination might not be supported, just skip and log it.
3217 reporter.logXcpt('Termination of blocking process #%d failed, skipped:' % (i,));
3218 if self.oTstDrv.fpApiVer >= 6.1: # Termination is supported since 5.2 or so.
3219 fRc = False;
3220 if fRc:
3221 reporter.log('All blocking processes were terminated successfully');
3222
3223 try: cProcs = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
3224 except: fRc = reporter.errorXcpt();
3225 else:
3226 # There still should be 20 processes because we just terminated the 10 blocking ones above.
3227 cProcsExpected = cProcsPerGroup * 2;
3228 if cProcs != cProcsExpected:
3229 fRc = reporter.error('Got %d total processes, expected %d (final)' % (cProcs, cProcsExpected));
3230 reporter.log2('Final guest session processes count: %d' % (cProcs,));
3231
3232 if not fRc:
3233 aoProcs = self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes');
3234 for i, oProc in enumerate(aoProcs):
3235 try:
3236 aoArgs = self.oTstDrv.oVBoxMgr.getArray(oProc, 'arguments');
3237 reporter.log('Process %d (\'%s\') still around, status is %d' \
3238 % (i, ' '.join([str(x) for x in aoArgs]), oProc.status));
3239 except:
3240 reporter.errorXcpt('Process lookup failed:');
3241 #
3242 # Now try to close the session and see what happens.
3243 #
3244 reporter.log('Closing guest session ...');
3245 try:
3246 oGuestSession.close();
3247 except:
3248 fRc = reporter.errorXcpt('Closing session for testing process references failed:');
3249
3250 return (fRc, oTxsSession);
3251
3252 def testGuestCtrlExec(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals,too-many-statements
3253 """
3254 Tests the basic execution feature.
3255 """
3256
3257 # Paths:
3258 sVBoxControl = None; # Only available on supported Windows guests.
3259 sShell = self.oTstDrv.getGuestSystemShell(oTestVm);
3260 sShellOpt = '/C' if oTestVm.isWindows() or oTestVm.isOS2() else '-c';
3261 sSystemDir = self.oTstDrv.getGuestSystemDir(oTestVm);
3262 sTempDir = self.oTstDrv.getGuestTempDir(oTestVm);
3263 sFileForReading = self.oTstDrv.getGuestSystemFileForReading(oTestVm);
3264 if oTestVm.isWindows() or oTestVm.isOS2():
3265 sImageOut = self.oTstDrv.getGuestSystemShell(oTestVm);
3266 if oTestVm.isWindows():
3267 sVBoxControl = oTestVm.pathJoin(self.oTstDrv.getGuestSystemAdminDir(oTestVm), 'VBoxControl.exe');
3268 else:
3269 # Really old guests (like OL 6) have their coreutils in /bin instead of /usr/bin.
3270 if self.oTstDrv.txsIsFile(oSession, oTxsSession, "/bin/ls", fIgnoreErrors = True):
3271 sImageOut = "/bin/ls";
3272 else:
3273 sImageOut = oTestVm.pathJoin(self.oTstDrv.getGuestSystemDir(oTestVm), 'ls');
3274 if oTestVm.isLinux(): ## @todo check solaris and darwin.
3275 sVBoxControl = "/usr/bin/VBoxControl"; # Symlink
3276
3277 # Use credential defaults.
3278 oCreds = tdCtxCreds();
3279 oCreds.applyDefaultsIfNotSet(oTestVm);
3280
3281 atInvalid = [
3282 # Invalid parameters.
3283 [ tdTestExec(), tdTestResultExec() ],
3284 # Non-existent / invalid image.
3285 [ tdTestExec(sCmd = "non-existent"), tdTestResultExec() ],
3286 [ tdTestExec(sCmd = "non-existent2"), tdTestResultExec() ],
3287 # Use an invalid format string.
3288 [ tdTestExec(sCmd = "%$%%%&"), tdTestResultExec() ],
3289 # More stuff.
3290 [ tdTestExec(sCmd = u"ƒ‰‹ˆ÷‹¸"), tdTestResultExec() ],
3291 [ tdTestExec(sCmd = "???://!!!"), tdTestResultExec() ],
3292 [ tdTestExec(sCmd = "<>!\\"), tdTestResultExec() ],
3293 # Enable as soon as ERROR_BAD_DEVICE is implemented.
3294 #[ tdTestExec(sCmd = "CON", tdTestResultExec() ],
3295 ];
3296
3297 atExec = [];
3298 if oTestVm.isWindows() or oTestVm.isOS2():
3299 if oTestVm.sKind == 'WindowsNT4':
3300 # For whatever reason NT4 SP6 (tst-nt4sp6) returns exit code 2 for existing *and* non-existing files.
3301 # I've manually checked that on the VM itself, so this is *not* a bug in the Guest Control code.
3302 # So we have to tweak the expected exit codes here in order to make the following tests pass.
3303 iExitCodeForExistingFiles = 2
3304 iExitCodeForNonExistingFiles = 2
3305 else:
3306 iExitCodeForExistingFiles = 0
3307 iExitCodeForNonExistingFiles = 1
3308 atExec += [
3309 # Basic execution.
3310 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
3311 tdTestResultExec(fRc = True) ],
3312 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sFileForReading ]),
3313 tdTestResultExec(fRc = True, iExitCode = iExitCodeForExistingFiles) ],
3314 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir + '\\nonexist.dll' ]),
3315 tdTestResultExec(fRc = True, iExitCode = iExitCodeForNonExistingFiles) ],
3316 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', '/wrongparam' ]),
3317 tdTestResultExec(fRc = True, iExitCode = 1) ],
3318 [ tdTestExec(sCmd = sShell, asArgs = [ sShell, sShellOpt, 'wrongcommand' ]),
3319 tdTestResultExec(fRc = True, iExitCode = 1) ],
3320 # StdOut.
3321 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
3322 tdTestResultExec(fRc = True) ],
3323 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', 'stdout-non-existing' ]),
3324 tdTestResultExec(fRc = True, iExitCode = iExitCodeForNonExistingFiles) ],
3325 # StdErr.
3326 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
3327 tdTestResultExec(fRc = True) ],
3328 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', 'stderr-non-existing' ]),
3329 tdTestResultExec(fRc = True, iExitCode = iExitCodeForNonExistingFiles) ],
3330 # StdOut + StdErr.
3331 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
3332 tdTestResultExec(fRc = True) ],
3333 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', 'stdouterr-non-existing' ]),
3334 tdTestResultExec(fRc = True, iExitCode = iExitCodeForNonExistingFiles) ],
3335 ];
3336
3337 if self.oTstDrv.isVersionEqualOrBigger(self.tpAdditionsVer, "7.1.0"):
3338 atExec.extend([
3339 # Current working directory set (VBox >= 7.1).
3340 [ tdTestExec(sCmd = sImageOut, sCwd = sTempDir, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
3341 tdTestResultExec(fRc = True) ]
3342 ]);
3343
3344 # atExec.extend([
3345 # FIXME: Failing tests.
3346 # Environment variables.
3347 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_NONEXIST' ],
3348 # tdTestResultExec(fRc = True, iExitCode = 1) ]
3349 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'windir' ],
3350 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3351 # tdTestResultExec(fRc = True, sBuf = 'windir=C:\\WINDOWS\r\n') ],
3352 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
3353 # aEnv = [ 'TEST_FOO=BAR' ],
3354 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3355 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ],
3356 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
3357 # aEnv = [ 'TEST_FOO=BAR', 'TEST_BAZ=BAR' ],
3358 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3359 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ]
3360
3361 ## @todo Create some files (or get files) we know the output size of to validate output length!
3362 ## @todo Add task which gets killed at some random time while letting the guest output something.
3363 #];
3364 else:
3365 atExec += [
3366 # Basic execution.
3367 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '-R', sSystemDir ]),
3368 tdTestResultExec(fRc = True) ],
3369 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sFileForReading ]),
3370 tdTestResultExec(fRc = True) ],
3371 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '--wrong-parameter' ]),
3372 tdTestResultExec(fRc = True, iExitCode = 2) ],
3373 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/non/existent' ]),
3374 tdTestResultExec(fRc = True, iExitCode = 2) ],
3375 [ tdTestExec(sCmd = sShell, asArgs = [ sShell, sShellOpt, 'wrongcommand' ]),
3376 tdTestResultExec(fRc = True, iExitCode = 127) ],
3377 # StdOut.
3378 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sSystemDir ]),
3379 tdTestResultExec(fRc = True) ],
3380 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, 'stdout-non-existing' ]),
3381 tdTestResultExec(fRc = True, iExitCode = 2) ],
3382 # StdErr.
3383 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sSystemDir ]),
3384 tdTestResultExec(fRc = True) ],
3385 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, 'stderr-non-existing' ]),
3386 tdTestResultExec(fRc = True, iExitCode = 2) ],
3387 # StdOut + StdErr.
3388 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sSystemDir ]),
3389 tdTestResultExec(fRc = True) ],
3390 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, 'stdouterr-non-existing' ]),
3391 tdTestResultExec(fRc = True, iExitCode = 2) ],
3392 ];
3393
3394 if self.oTstDrv.isVersionEqualOrBigger(self.tpAdditionsVer, "7.1.0"):
3395 atExec.extend([
3396 # Current working directory set (VBox >= 7.1).
3397 [ tdTestExec(sCmd = sImageOut, sCwd = sTempDir, asArgs = [ sImageOut, '-R', sSystemDir ]),
3398 tdTestResultExec(fRc = True) ]
3399 ]);
3400
3401 # atExec.extend([
3402 # FIXME: Failing tests.
3403 # Environment variables.
3404 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_NONEXIST' ],
3405 # tdTestResultExec(fRc = True, iExitCode = 1) ]
3406 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'windir' ],
3407 #
3408 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3409 # tdTestResultExec(fRc = True, sBuf = 'windir=C:\\WINDOWS\r\n') ],
3410 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
3411 # aEnv = [ 'TEST_FOO=BAR' ],
3412 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3413 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ],
3414 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
3415 # aEnv = [ 'TEST_FOO=BAR', 'TEST_BAZ=BAR' ],
3416 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3417 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ]
3418
3419 ## @todo Create some files (or get files) we know the output size of to validate output length!
3420 ## @todo Add task which gets killed at some random time while letting the guest output something.
3421 #];
3422
3423 #
3424 #for iExitCode in xrange(0, 127):
3425 # atExec.append([ tdTestExec(sCmd = sShell, asArgs = [ sShell, sShellOpt, 'exit %s' % iExitCode ]),
3426 # tdTestResultExec(fRc = True, iExitCode = iExitCode) ]);
3427
3428 if sVBoxControl \
3429 and self.oTstDrv.fpApiVer >= 6.0: # Investigate with this doesn't work on (<) 5.2.
3430 # Paths with spaces on windows.
3431 atExec.append([ tdTestExec(sCmd = sVBoxControl, asArgs = [ sVBoxControl, 'version' ],
3432 afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut,
3433 vboxcon.ProcessCreateFlag_WaitForStdErr ]),
3434 tdTestResultExec(fRc = True) ]);
3435
3436 # Test very long arguments. Be careful when tweaking this to not break the tests.
3437 # Regarding paths:
3438 # - We have RTPATH_BIG_MAX (64K)
3439 # - MSDN says 32K for CreateFileW()
3440 # - On Windows, each path component must not be longer than MAX_PATH (260), see
3441 # https://docs.microsoft.com/en-us/windows/win32/fileio/filesystem-functionality-comparison#limits
3442 #
3443 # Old(er) Windows OSes tend to crash in cmd.exe, so skip this on these OSes.
3444 if self.oTstDrv.fpApiVer >= 6.1 \
3445 and oTestVm.sKind not in ('WindowsNT4', 'Windows2000', 'WindowsXP', 'Windows2003'):
3446 sEndMarker = '--end-marker';
3447 if oTestVm.isWindows() \
3448 or oTestVm.isOS2():
3449 sCmd = sShell;
3450 else:
3451 # Really old guests (like OL 6) have their coreutils in /bin instead of /usr/bin.
3452 if self.oTstDrv.txsIsFile(oSession, oTxsSession, "/bin/echo", fIgnoreErrors = True):
3453 sCmd = "/bin/echo";
3454 else:
3455 sCmd = oTestVm.pathJoin(self.oTstDrv.getGuestSystemDir(oTestVm), 'echo');
3456
3457 for _ in xrange(0, 16):
3458 if oTestVm.isWindows() \
3459 or oTestVm.isOS2():
3460 asArgs = [ sShell, sShellOpt, "echo" ];
3461 else:
3462 asArgs = [ sCmd ];
3463
3464 # Append a random number of arguments with random length.
3465 for _ in xrange(0, self.oTestFiles.oRandom.randrange(1, 64)):
3466 asArgs.append(''.join(random.choice(string.ascii_lowercase)
3467 for _ in range(self.oTestFiles.oRandom.randrange(1, 196))));
3468
3469 asArgs.append(sEndMarker);
3470
3471 reporter.log2('asArgs=%s (%d args), type=%s' % (limitString(asArgs), len(asArgs), type(asArgs)));
3472
3473 ## @todo Check limits; on Ubuntu with 256KB IPRT returns VERR_NOT_IMPLEMENTED.
3474 # Use a higher timeout (15 min) than usual for these long checks.
3475 atExec.append([ tdTestExec(sCmd = sCmd, asArgs = asArgs,
3476 afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut,
3477 vboxcon.ProcessCreateFlag_WaitForStdErr ],
3478 timeoutMS = 15 * 60 * 1000),
3479 tdTestResultExec(fRc = True) ]);
3480
3481 # Build up the final test array for the first batch.
3482 atTests = atInvalid + atExec;
3483
3484 #
3485 # First batch: One session per guest process.
3486 #
3487 reporter.log('One session per guest process ...');
3488 fRc = True;
3489 for (i, tTest) in enumerate(atTests):
3490 oCurTest = tTest[0] # type: tdTestExec
3491 oCurRes = tTest[1] # type: tdTestResultExec
3492 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3493 if not fRc:
3494 break;
3495 fRc2, oCurGuestSession = oCurTest.createSession('testGuestCtrlExec: Test #%d' % (i,));
3496 if fRc2 is not True:
3497 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
3498 break;
3499 fRc = self.gctrlExecDoTest(i, oCurTest, oCurRes, oCurGuestSession) and fRc;
3500 fRc = oCurTest.closeSession() and fRc;
3501
3502 reporter.log('Execution of all tests done, checking for stale sessions');
3503
3504 # No sessions left?
3505 try:
3506 aSessions = self.oTstDrv.oVBoxMgr.getArray(oSession.o.console.guest, 'sessions');
3507 except:
3508 fRc = reporter.errorXcpt();
3509 else:
3510 cSessions = len(aSessions);
3511 if cSessions != 0:
3512 fRc = reporter.error('Found %d stale session(s), expected 0:' % (cSessions,));
3513 for (i, aSession) in enumerate(aSessions):
3514 try: reporter.log(' Stale session #%d ("%s")' % (aSession.id, aSession.name));
3515 except: reporter.errorXcpt();
3516
3517 if fRc is not True:
3518 return (fRc, oTxsSession);
3519
3520 reporter.log('Now using one guest session for all tests ...');
3521
3522 #
3523 # Second batch: One session for *all* guest processes.
3524 #
3525
3526 # Create session.
3527 reporter.log('Creating session for all tests ...');
3528 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start, ];
3529 try:
3530 oGuest = oSession.o.console.guest;
3531 oCurGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain,
3532 'testGuestCtrlExec: One session for all tests');
3533 except:
3534 return (reporter.errorXcpt(), oTxsSession);
3535
3536 try:
3537 eWaitResult = oCurGuestSession.waitForArray(aeWaitFor, 30 * 1000);
3538 except:
3539 fRc = reporter.errorXcpt('Waiting for guest session to start failed:');
3540 else:
3541 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
3542 fRc = reporter.error('Session did not start successfully, returned wait result: %d' % (eWaitResult,));
3543 else:
3544 reporter.log('Session successfully started');
3545
3546 # Do the tests within this session.
3547 for (i, tTest) in enumerate(atTests):
3548 oCurTest = tTest[0] # type: tdTestExec
3549 oCurRes = tTest[1] # type: tdTestResultExec
3550
3551 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3552 if not fRc:
3553 break;
3554 fRc = self.gctrlExecDoTest(i, oCurTest, oCurRes, oCurGuestSession);
3555 if fRc is False:
3556 break;
3557
3558 # Close the session.
3559 reporter.log2('Closing guest session ...');
3560 try:
3561 oCurGuestSession.close();
3562 oCurGuestSession = None;
3563 except:
3564 fRc = reporter.errorXcpt('Closing guest session failed:');
3565
3566 # No sessions left?
3567 reporter.log('Execution of all tests done, checking for stale sessions again');
3568 try: cSessions = len(self.oTstDrv.oVBoxMgr.getArray(oSession.o.console.guest, 'sessions'));
3569 except: fRc = reporter.errorXcpt();
3570 else:
3571 if cSessions != 0:
3572 fRc = reporter.error('Found %d stale session(s), expected 0' % (cSessions,));
3573 return (fRc, oTxsSession);
3574
3575 def threadForTestGuestCtrlSessionReboot(self, oGuestProcess):
3576 """
3577 Thread routine which waits for the stale guest process getting terminated (or some error)
3578 while the main test routine reboots the guest. It then compares the expected guest process result
3579 and logs an error if appropriate.
3580 """
3581 reporter.log('Waiting for process to get terminated at reboot ...');
3582 try:
3583 eWaitResult = oGuestProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate ], 5 * 60 * 1000);
3584 except:
3585 return reporter.errorXcpt('waitForArray failed');
3586 try:
3587 eStatus = oGuestProcess.status
3588 except:
3589 return reporter.errorXcpt('failed to get status (wait result %d)' % (eWaitResult,));
3590
3591 if eWaitResult == vboxcon.ProcessWaitResult_Terminate and eStatus == vboxcon.ProcessStatus_Down:
3592 reporter.log('Stale process was correctly terminated (status: down)');
3593 return True;
3594
3595 return reporter.error('Process wait across reboot failed: eWaitResult=%d, expected %d; eStatus=%d, expected %d'
3596 % (eWaitResult, vboxcon.ProcessWaitResult_Terminate, eStatus, vboxcon.ProcessStatus_Down,));
3597
3598 def testGuestCtrlSessionReboot(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
3599 """
3600 Tests guest object notifications when a guest gets rebooted / shutdown.
3601
3602 These notifications gets sent from the guest sessions in order to make API clients
3603 aware of guest session changes.
3604
3605 To test that we create a stale guest process and trigger a reboot of the guest.
3606 """
3607
3608 ## @todo backport fixes to 6.0 and maybe 5.2
3609 if self.oTstDrv.fpApiVer <= 6.0:
3610 reporter.log('Skipping: Required fixes not yet backported!');
3611 return None;
3612
3613 # Use credential defaults.
3614 oCreds = tdCtxCreds();
3615 oCreds.applyDefaultsIfNotSet(oTestVm);
3616
3617 fRebooted = False;
3618 fRc = True;
3619
3620 #
3621 # Start a session.
3622 #
3623 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
3624 try:
3625 oGuest = oSession.o.console.guest;
3626 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionReboot");
3627 eWaitResult = oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
3628 except:
3629 return (reporter.errorXcpt(), oTxsSession);
3630
3631 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
3632 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
3633 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
3634 reporter.log('Session successfully started');
3635
3636 #
3637 # Create a process.
3638 #
3639 # That process will also be used later to see if the session cleanup worked upon reboot.
3640 #
3641 sImage = self.oTstDrv.getGuestSystemShell(oTestVm);
3642 asArgs = [ sImage, ];
3643 aEnv = [];
3644 afFlags = [];
3645 try:
3646 oGuestProcess = self.processCreateWrapper(oGuestSession, sImage, asArgs,
3647 "", # Working directory.
3648 aEnv, afFlags, 30 * 1000);
3649 except:
3650 fRc = reporter.error('Failed to start shell process (%s)' % (sImage,));
3651 else:
3652 try:
3653 eWaitResult = oGuestProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
3654 except:
3655 fRc = reporter.errorXcpt('Waiting for shell process (%s) to start failed' % (sImage,));
3656 else:
3657 # Check the result and state:
3658 try: eStatus = oGuestProcess.status;
3659 except: fRc = reporter.errorXcpt('Waiting for shell process (%s) to start failed' % (sImage,));
3660 else:
3661 reporter.log2('Starting process wait result returned: %d; Process status is: %d' % (eWaitResult, eStatus,));
3662 if eWaitResult != vboxcon.ProcessWaitResult_Start:
3663 fRc = reporter.error('wait for ProcessWaitForFlag_Start failed: %d, expected %d (Start)'
3664 % (eWaitResult, vboxcon.ProcessWaitResult_Start,));
3665 elif eStatus != vboxcon.ProcessStatus_Started:
3666 fRc = reporter.error('Unexpected process status after startup: %d, wanted %d (Started)'
3667 % (eStatus, vboxcon.ProcessStatus_Started,));
3668 else:
3669 # Create a thread that waits on the process to terminate
3670 reporter.log('Creating reboot thread ...');
3671 oThreadReboot = threading.Thread(target = self.threadForTestGuestCtrlSessionReboot,
3672 args = (oGuestProcess,),
3673 name = 'threadForTestGuestCtrlSessionReboot');
3674 oThreadReboot.setDaemon(True); # pylint: disable=deprecated-method
3675 oThreadReboot.start();
3676
3677 # Do the reboot.
3678 reporter.log('Rebooting guest and reconnecting TXS ...');
3679 (oSession, oTxsSession) = self.oTstDrv.txsRebootAndReconnectViaTcp(oSession, oTxsSession,
3680 cMsTimeout = 3 * 60000);
3681 if oSession \
3682 and oTxsSession:
3683 # Set reboot flag (needed later for session closing).
3684 fRebooted = True;
3685 else:
3686 reporter.error('Rebooting via TXS failed');
3687 try: oGuestProcess.terminate();
3688 except: reporter.logXcpt();
3689 fRc = False;
3690
3691 reporter.log('Waiting for thread to finish ...');
3692 oThreadReboot.join();
3693
3694 # Check that the guest session now still has the formerly guest process object created above,
3695 # but with the "down" status now (because of guest reboot).
3696 try:
3697 aoGuestProcs = self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes');
3698 if len(aoGuestProcs) == 1:
3699 enmProcSts = aoGuestProcs[0].status;
3700 if enmProcSts != vboxcon.ProcessStatus_Down:
3701 fRc = reporter.error('Old guest process (before reboot) has status %d, expected %s' \
3702 % (enmProcSts, vboxcon.ProcessStatus_Down));
3703 else:
3704 fRc = reporter.error('Old guest session (before reboot) has %d processes registered, expected 1' \
3705 % (len(aoGuestProcs)));
3706 except:
3707 fRc = reporter.errorXcpt();
3708 #
3709 # Try make sure we don't leave with a stale process on failure.
3710 #
3711 try: oGuestProcess.terminate();
3712 except: reporter.logXcpt();
3713
3714 #
3715 # Close the session.
3716 #
3717 reporter.log2('Closing guest session ...');
3718 try:
3719 oGuestSession.close();
3720 except:
3721 # Closing the guest session will fail when the guest reboot has been triggered,
3722 # as the session object will be cleared on a guest reboot.
3723 if fRebooted:
3724 reporter.logXcpt('Closing guest session failed, good (guest rebooted)');
3725 else: # ... otherwise this (still) should succeed. Report so if it doesn't.
3726 reporter.errorXcpt('Closing guest session failed');
3727
3728 return (fRc, oTxsSession);
3729
3730 def testGuestCtrlExecTimeout(self, oSession, oTxsSession, oTestVm):
3731 """
3732 Tests handling of timeouts of started guest processes.
3733 """
3734
3735 sShell = self.oTstDrv.getGuestSystemShell(oTestVm);
3736
3737 # Use credential defaults.
3738 oCreds = tdCtxCreds();
3739 oCreds.applyDefaultsIfNotSet(oTestVm);
3740
3741 #
3742 # Create a session.
3743 #
3744 try:
3745 oGuest = oSession.o.console.guest;
3746 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlExecTimeout");
3747 eWaitResult = oGuestSession.waitForArray([ vboxcon.GuestSessionWaitForFlag_Start, ], 30 * 1000);
3748 except:
3749 return (reporter.errorXcpt(), oTxsSession);
3750
3751 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
3752 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
3753 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
3754 reporter.log('Session successfully started');
3755
3756 #
3757 # Create a process which never terminates and should timeout when
3758 # waiting for termination.
3759 #
3760 fRc = True;
3761 try:
3762 oCurProcess = self.processCreateWrapper(oGuestSession, sShell, [ sShell,] if self.oTstDrv.fpApiVer >= 5.0 else [],
3763 "", # Working directory.
3764 [], [], 30 * 1000);
3765 except:
3766 fRc = reporter.errorXcpt();
3767 else:
3768 reporter.log('Waiting for process 1 being started ...');
3769 try:
3770 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
3771 except:
3772 fRc = reporter.errorXcpt();
3773 else:
3774 if eWaitResult != vboxcon.ProcessWaitResult_Start:
3775 fRc = reporter.error('Waiting for process 1 to start failed, got status %d' % (eWaitResult,));
3776 else:
3777 for msWait in (1, 32, 2000,):
3778 reporter.log('Waiting for process 1 to time out within %sms ...' % (msWait,));
3779 try:
3780 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate, ], msWait);
3781 except:
3782 fRc = reporter.errorXcpt();
3783 break;
3784 if eWaitResult != vboxcon.ProcessWaitResult_Timeout:
3785 fRc = reporter.error('Waiting for process 1 did not time out in %sms as expected: %d'
3786 % (msWait, eWaitResult,));
3787 break;
3788 reporter.log('Waiting for process 1 timed out in %u ms, good' % (msWait,));
3789
3790 try:
3791 oCurProcess.terminate();
3792 except:
3793 reporter.errorXcpt();
3794 oCurProcess = None;
3795
3796 #
3797 # Create another process that doesn't terminate, but which will be killed by VBoxService
3798 # because it ran out of execution time (3 seconds).
3799 #
3800 try:
3801 oCurProcess = self.processCreateWrapper(oGuestSession, sShell, [sShell,] if self.oTstDrv.fpApiVer >= 5.0 else [],
3802 "", # Working directory.
3803 [], [], 3 * 1000);
3804 except:
3805 fRc = reporter.errorXcpt();
3806 else:
3807 reporter.log('Waiting for process 2 being started ...');
3808 try:
3809 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
3810 except:
3811 fRc = reporter.errorXcpt();
3812 else:
3813 if eWaitResult != vboxcon.ProcessWaitResult_Start:
3814 fRc = reporter.error('Waiting for process 2 to start failed, got status %d' % (eWaitResult,));
3815 else:
3816 reporter.log('Waiting for process 2 to get killed for running out of execution time ...');
3817 try:
3818 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate, ], 15 * 1000);
3819 except:
3820 fRc = reporter.errorXcpt();
3821 else:
3822 if eWaitResult != vboxcon.ProcessWaitResult_Timeout:
3823 fRc = reporter.error('Waiting for process 2 did not time out when it should, got wait result %d'
3824 % (eWaitResult,));
3825 else:
3826 reporter.log('Waiting for process 2 did not time out, good: %s' % (eWaitResult,));
3827 try:
3828 eStatus = oCurProcess.status;
3829 except:
3830 fRc = reporter.errorXcpt();
3831 else:
3832 if eStatus != vboxcon.ProcessStatus_TimedOutKilled:
3833 fRc = reporter.error('Status of process 2 wrong; excepted %d, got %d'
3834 % (vboxcon.ProcessStatus_TimedOutKilled, eStatus));
3835 else:
3836 reporter.log('Status of process 2 is TimedOutKilled (%d) is it should be.'
3837 % (vboxcon.ProcessStatus_TimedOutKilled,));
3838 try:
3839 oCurProcess.terminate();
3840 except:
3841 reporter.logXcpt();
3842 oCurProcess = None;
3843
3844 #
3845 # Clean up the session.
3846 #
3847 try:
3848 oGuestSession.close();
3849 except:
3850 fRc = reporter.errorXcpt();
3851
3852 return (fRc, oTxsSession);
3853
3854 def testGuestCtrlDirCreate(self, oSession, oTxsSession, oTestVm):
3855 """
3856 Tests creation of guest directories.
3857 """
3858
3859 sScratch = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), 'testGuestCtrlDirCreate');
3860
3861 atTests = [
3862 # Invalid stuff.
3863 [ tdTestDirCreate(sDirectory = '' ), tdTestResultFailure() ],
3864 # More unusual stuff.
3865 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin('..', '.') ), tdTestResultFailure() ],
3866 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin('..', '..') ), tdTestResultFailure() ],
3867 [ tdTestDirCreate(sDirectory = '..' ), tdTestResultFailure() ],
3868 [ tdTestDirCreate(sDirectory = '../' ), tdTestResultFailure() ],
3869 [ tdTestDirCreate(sDirectory = '../../' ), tdTestResultFailure() ],
3870 [ tdTestDirCreate(sDirectory = '/' ), tdTestResultFailure() ],
3871 [ tdTestDirCreate(sDirectory = '/..' ), tdTestResultFailure() ],
3872 [ tdTestDirCreate(sDirectory = '/../' ), tdTestResultFailure() ],
3873 ];
3874 if oTestVm.isWindows() or oTestVm.isOS2():
3875 atTests.extend([
3876 [ tdTestDirCreate(sDirectory = 'C:\\' ), tdTestResultFailure() ],
3877 [ tdTestDirCreate(sDirectory = 'C:\\..' ), tdTestResultFailure() ],
3878 [ tdTestDirCreate(sDirectory = 'C:\\..\\' ), tdTestResultFailure() ],
3879 [ tdTestDirCreate(sDirectory = 'C:/' ), tdTestResultFailure() ],
3880 [ tdTestDirCreate(sDirectory = 'C:/.' ), tdTestResultFailure() ],
3881 [ tdTestDirCreate(sDirectory = 'C:/./' ), tdTestResultFailure() ],
3882 [ tdTestDirCreate(sDirectory = 'C:/..' ), tdTestResultFailure() ],
3883 [ tdTestDirCreate(sDirectory = 'C:/../' ), tdTestResultFailure() ],
3884 [ tdTestDirCreate(sDirectory = '\\\\uncrulez\\foo' ), tdTestResultFailure() ],
3885 ]);
3886 atTests.extend([
3887 # Existing directories and files.
3888 [ tdTestDirCreate(sDirectory = self.oTstDrv.getGuestSystemDir(oTestVm) ), tdTestResultFailure() ],
3889 [ tdTestDirCreate(sDirectory = self.oTstDrv.getGuestSystemShell(oTestVm) ), tdTestResultFailure() ],
3890 [ tdTestDirCreate(sDirectory = self.oTstDrv.getGuestSystemFileForReading(oTestVm) ), tdTestResultFailure() ],
3891 # Creating directories.
3892 [ tdTestDirCreate(sDirectory = sScratch ), tdTestResultSuccess() ],
3893 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo', 'bar', 'baz'),
3894 afFlags = (vboxcon.DirectoryCreateFlag_Parents,) ), tdTestResultSuccess() ],
3895 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo', 'bar', 'baz'),
3896 afFlags = (vboxcon.DirectoryCreateFlag_Parents,) ), tdTestResultSuccess() ],
3897 # Try format strings as directories.
3898 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo%sbar%sbaz%d' )), tdTestResultSuccess() ],
3899 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, '%f%%boo%%bar%RI32' )), tdTestResultSuccess() ],
3900 # Long random names.
3901 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(36, 28))),
3902 tdTestResultSuccess() ],
3903 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(140, 116))),
3904 tdTestResultSuccess() ],
3905 # Too long names. ASSUMES a guests has a 255 filename length limitation.
3906 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(2048, 256))),
3907 tdTestResultFailure() ],
3908 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(2048, 256))),
3909 tdTestResultFailure() ],
3910 # Missing directory in path.
3911 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo1', 'bar') ), tdTestResultFailure() ],
3912 ]);
3913
3914 fRc = True;
3915 for (i, tTest) in enumerate(atTests):
3916 oCurTest = tTest[0] # type: tdTestDirCreate
3917 oCurRes = tTest[1] # type: tdTestResult
3918 reporter.log('Testing #%d, sDirectory="%s" ...' % (i, limitString(oCurTest.sDirectory),));
3919
3920 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3921 if not fRc:
3922 break;
3923 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirCreate: Test #%d' % (i,));
3924 if fRc is False:
3925 return reporter.error('Test #%d failed: Could not create session' % (i,));
3926
3927 fRc = self.gctrlCreateDir(oCurTest, oCurRes, oCurGuestSession);
3928
3929 fRc = oCurTest.closeSession() and fRc;
3930 if fRc is False:
3931 fRc = reporter.error('Test #%d failed' % (i,));
3932
3933 return (fRc, oTxsSession);
3934
3935 def testGuestCtrlDirCreateTemp(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
3936 """
3937 Tests creation of temporary directories.
3938 """
3939
3940 sSystemDir = self.oTstDrv.getGuestSystemDir(oTestVm);
3941 atTests = [
3942 # Invalid stuff (template must have one or more trailin 'X'es (upper case only), or a cluster of three or more).
3943 [ tdTestDirCreateTemp(sDirectory = ''), tdTestResultFailure() ],
3944 [ tdTestDirCreateTemp(sDirectory = sSystemDir, fMode = 1234), tdTestResultFailure() ],
3945 [ tdTestDirCreateTemp(sTemplate = 'xXx', sDirectory = sSystemDir, fMode = 0o700), tdTestResultFailure() ],
3946 [ tdTestDirCreateTemp(sTemplate = 'xxx', sDirectory = sSystemDir, fMode = 0o700), tdTestResultFailure() ],
3947 [ tdTestDirCreateTemp(sTemplate = 'XXx', sDirectory = sSystemDir, fMode = 0o700), tdTestResultFailure() ],
3948 [ tdTestDirCreateTemp(sTemplate = 'bar', sDirectory = 'whatever', fMode = 0o700), tdTestResultFailure() ],
3949 [ tdTestDirCreateTemp(sTemplate = 'foo', sDirectory = 'it is not used', fMode = 0o700), tdTestResultFailure() ],
3950 [ tdTestDirCreateTemp(sTemplate = 'X,so', sDirectory = 'pointless test', fMode = 0o700), tdTestResultFailure() ],
3951 # Non-existing stuff.
3952 [ tdTestDirCreateTemp(sTemplate = 'XXXXXXX',
3953 sDirectory = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), 'non', 'existing')),
3954 tdTestResultFailure() ],
3955 # Working stuff:
3956 [ tdTestDirCreateTemp(sTemplate = 'X', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3957 [ tdTestDirCreateTemp(sTemplate = 'XX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3958 [ tdTestDirCreateTemp(sTemplate = 'XXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3959 [ tdTestDirCreateTemp(sTemplate = 'XXXXXXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)),
3960 tdTestResultFailure() ],
3961 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)),
3962 tdTestResultFailure() ],
3963 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)),
3964 tdTestResultFailure() ],
3965 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm)),
3966 tdTestResultFailure() ],
3967 ];
3968
3969 if self.oTstDrv.fpApiVer >= 7.0:
3970 # Weird mode set.
3971 atTests.extend([
3972 [ tdTestDirCreateTemp(sTemplate = 'XXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o42333),
3973 tdTestResultFailure() ]
3974 ]);
3975 # Same as working stuff above, but with a different mode set.
3976 atTests.extend([
3977 [ tdTestDirCreateTemp(sTemplate = 'X', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3978 tdTestResultFailure() ],
3979 [ tdTestDirCreateTemp(sTemplate = 'XX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3980 tdTestResultFailure() ],
3981 [ tdTestDirCreateTemp(sTemplate = 'XXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3982 tdTestResultFailure() ],
3983 [ tdTestDirCreateTemp(sTemplate = 'XXXXXXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3984 tdTestResultFailure() ],
3985 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3986 tdTestResultFailure() ],
3987 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3988 tdTestResultFailure() ],
3989 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fMode = 0o777),
3990 tdTestResultFailure() ]
3991 ]);
3992 # Same as working stuff above, but with secure mode set.
3993 atTests.extend([
3994 [ tdTestDirCreateTemp(sTemplate = 'X', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fSecure = True),
3995 tdTestResultFailure() ],
3996 [ tdTestDirCreateTemp(sTemplate = 'XX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fSecure = True),
3997 tdTestResultFailure() ],
3998 [ tdTestDirCreateTemp(sTemplate = 'XXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fSecure = True),
3999 tdTestResultFailure() ],
4000 [ tdTestDirCreateTemp(sTemplate = 'XXXXXXX', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm), fSecure = True),
4001 tdTestResultFailure() ],
4002 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm),
4003 fSecure = True),
4004 tdTestResultFailure() ],
4005 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm),
4006 fSecure = True),
4007 tdTestResultFailure() ],
4008 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.oTstDrv.getGuestTempDir(oTestVm),
4009 fSecure = True),
4010 tdTestResultFailure() ]
4011 ]);
4012
4013 fRc = True;
4014 for (i, tTest) in enumerate(atTests):
4015 oCurTest = tTest[0] # type: tdTestDirCreateTemp
4016 oCurRes = tTest[1] # type: tdTestResult
4017 reporter.log('Testing #%d, sTemplate="%s", fMode=%#o, path="%s", secure="%s" ...' %
4018 (i, oCurTest.sTemplate, oCurTest.fMode, oCurTest.sDirectory, oCurTest.fSecure));
4019
4020 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4021 if not fRc:
4022 break;
4023 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirCreateTemp: Test #%d' % (i,));
4024 if fRc is False:
4025 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4026 break;
4027
4028 sDirTemp = '';
4029 try:
4030 sDirTemp = oCurGuestSession.directoryCreateTemp(oCurTest.sTemplate, oCurTest.fMode,
4031 oCurTest.sDirectory, oCurTest.fSecure);
4032 except:
4033 if oCurRes.fRc is True:
4034 fRc = reporter.errorXcpt('Creating temp directory "%s" failed:' % (oCurTest.sDirectory,));
4035 else:
4036 reporter.logXcpt('Creating temp directory "%s" failed expectedly, skipping:' % (oCurTest.sDirectory,));
4037 else:
4038 reporter.log2('Temporary directory is: "%s"' % (limitString(sDirTemp),));
4039 if not sDirTemp:
4040 fRc = reporter.error('Resulting directory is empty!');
4041 else:
4042 ## @todo This does not work for some unknown reason.
4043 #try:
4044 # if self.oTstDrv.fpApiVer >= 5.0:
4045 # fExists = oCurGuestSession.directoryExists(sDirTemp, False);
4046 # else:
4047 # fExists = oCurGuestSession.directoryExists(sDirTemp);
4048 #except:
4049 # fRc = reporter.errorXcpt('sDirTemp=%s' % (sDirTemp,));
4050 #else:
4051 # if fExists is not True:
4052 # fRc = reporter.error('Test #%d failed: Temporary directory "%s" does not exists (%s)'
4053 # % (i, sDirTemp, fExists));
4054 try:
4055 oFsObjInfo = oCurGuestSession.fsObjQueryInfo(sDirTemp, False);
4056 eType = oFsObjInfo.type;
4057 except:
4058 fRc = reporter.errorXcpt('sDirTemp="%s"' % (sDirTemp,));
4059 else:
4060 reporter.log2('%s: eType=%s (dir=%d)' % (limitString(sDirTemp), eType, vboxcon.FsObjType_Directory,));
4061 if eType != vboxcon.FsObjType_Directory:
4062 fRc = reporter.error('Temporary directory "%s" not created as a directory: eType=%d'
4063 % (sDirTemp, eType));
4064 fRc = oCurTest.closeSession() and fRc;
4065 return (fRc, oTxsSession);
4066
4067 def testGuestCtrlDirRead(self, oSession, oTxsSession, oTestVm):
4068 """
4069 Tests opening and reading (enumerating) guest directories.
4070 """
4071
4072 sSystemDir = self.oTstDrv.getGuestSystemDir(oTestVm);
4073 atTests = [
4074 # Invalid stuff.
4075 [ tdTestDirRead(sDirectory = ''), tdTestResultDirRead() ],
4076 [ tdTestDirRead(sDirectory = sSystemDir, afFlags = [ 1234 ]), tdTestResultDirRead() ],
4077 [ tdTestDirRead(sDirectory = sSystemDir, sFilter = '*.foo'), tdTestResultDirRead() ],
4078 # Non-existing stuff.
4079 [ tdTestDirRead(sDirectory = oTestVm.pathJoin(sSystemDir, 'really-no-such-subdir')), tdTestResultDirRead() ],
4080 [ tdTestDirRead(sDirectory = oTestVm.pathJoin(sSystemDir, 'non', 'existing')), tdTestResultDirRead() ],
4081 ];
4082
4083 if oTestVm.isWindows() or oTestVm.isOS2():
4084 atTests.extend([
4085 # More unusual stuff.
4086 [ tdTestDirRead(sDirectory = 'z:\\'), tdTestResultDirRead() ],
4087 [ tdTestDirRead(sDirectory = '\\\\uncrulez\\foo'), tdTestResultDirRead() ],
4088 ]);
4089
4090 # Read the system directory (ASSUMES at least 5 files in it):
4091 # Windows 7+ has inaccessible system32/com/dmp directory that screws up this test, so skip it on windows:
4092 if not oTestVm.isWindows():
4093 atTests.append([ tdTestDirRead(sDirectory = sSystemDir),
4094 tdTestResultDirRead(fRc = True, cFiles = -5, cDirs = None) ]);
4095 ## @todo trailing slash
4096
4097 # Read from the test file set.
4098 atTests.extend([
4099 [ tdTestDirRead(sDirectory = self.oTestFiles.oEmptyDir.sPath),
4100 tdTestResultDirRead(fRc = True, cFiles = 0, cDirs = 0, cOthers = 0) ],
4101 [ tdTestDirRead(sDirectory = self.oTestFiles.oManyDir.sPath),
4102 tdTestResultDirRead(fRc = True, cFiles = len(self.oTestFiles.oManyDir.aoChildren), cDirs = 0, cOthers = 0) ],
4103 [ tdTestDirRead(sDirectory = self.oTestFiles.oTreeDir.sPath),
4104 tdTestResultDirRead(fRc = True, cFiles = self.oTestFiles.cTreeFiles, cDirs = self.oTestFiles.cTreeDirs,
4105 cOthers = self.oTestFiles.cTreeOthers) ],
4106 ]);
4107
4108
4109 fRc = True;
4110 for (i, tTest) in enumerate(atTests):
4111 oCurTest = tTest[0] # type: tdTestExec
4112 oCurRes = tTest[1] # type: tdTestResultDirRead
4113
4114 reporter.log('Testing #%d, dir="%s" ...' % (i, oCurTest.sDirectory));
4115 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4116 if not fRc:
4117 break;
4118 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirRead: Test #%d' % (i,));
4119 if fRc is not True:
4120 break;
4121 fUseDirList = False;
4122 cEntriesPerRead = random.randrange(1, 32768);
4123 if self.oTstDrv.fpApiVer >= 7.1 and self.oTstDrv.uRevision >= 156485 \
4124 and self.oTstDrv.isVersionEqualOrBigger(self.tpAdditionsVer, "7.1.0"):
4125 # Listing directories only is available for >= VBox 7.1.
4126 fUseDirList = random.choice( [True, False] );
4127 (fRc2, cDirs, cFiles, cOthers) = self.gctrlReadDirTree(oCurTest, oCurGuestSession, oCurRes.fRc,
4128 fUseDirList, cEntriesPerRead);
4129 fRc = oCurTest.closeSession() and fRc;
4130
4131 reporter.log2('Test #%d: Returned %d directories, %d files total' % (i, cDirs, cFiles));
4132 if fRc2 is oCurRes.fRc:
4133 if fRc2 is True:
4134 if oCurRes.cFiles is None:
4135 pass; # ignore
4136 elif oCurRes.cFiles >= 0 and cFiles != oCurRes.cFiles:
4137 fRc = reporter.error('Test #%d failed: Got %d files, expected %d' % (i, cFiles, oCurRes.cFiles));
4138 elif oCurRes.cFiles < 0 and cFiles < -oCurRes.cFiles:
4139 fRc = reporter.error('Test #%d failed: Got %d files, expected at least %d'
4140 % (i, cFiles, -oCurRes.cFiles));
4141 if oCurRes.cDirs is None:
4142 pass; # ignore
4143 elif oCurRes.cDirs >= 0 and cDirs != oCurRes.cDirs:
4144 fRc = reporter.error('Test #%d failed: Got %d directories, expected %d' % (i, cDirs, oCurRes.cDirs));
4145 elif oCurRes.cDirs < 0 and cDirs < -oCurRes.cDirs:
4146 fRc = reporter.error('Test #%d failed: Got %d directories, expected at least %d'
4147 % (i, cDirs, -oCurRes.cDirs));
4148 if oCurRes.cOthers is None:
4149 pass; # ignore
4150 elif oCurRes.cOthers >= 0 and cOthers != oCurRes.cOthers:
4151 fRc = reporter.error('Test #%d failed: Got %d other types, expected %d' % (i, cOthers, oCurRes.cOthers));
4152 elif oCurRes.cOthers < 0 and cOthers < -oCurRes.cOthers:
4153 fRc = reporter.error('Test #%d failed: Got %d other types, expected at least %d'
4154 % (i, cOthers, -oCurRes.cOthers));
4155
4156 else:
4157 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc));
4158
4159
4160 #
4161 # Go over a few directories in the test file set and compare names,
4162 # types and sizes rather than just the counts like we did above.
4163 #
4164 if fRc is True:
4165 oCurTest = tdTestDirRead();
4166 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4167 if fRc:
4168 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirRead: gctrlReadDirTree2');
4169 if fRc is True:
4170 for oDir in (self.oTestFiles.oEmptyDir, self.oTestFiles.oManyDir, self.oTestFiles.oTreeDir):
4171 reporter.log('Checking "%s" ...' % (oDir.sPath,));
4172 fUseDirList = False;
4173 cEntriesPerRead = random.randrange(1, 32768);
4174 if self.oTstDrv.fpApiVer >= 7.1 and self.oTstDrv.uRevision >= 156485 \
4175 and self.oTstDrv.isVersionEqualOrBigger(self.tpAdditionsVer, "7.1.0"):
4176 # Listing directories only is available for >= VBox 7.1.
4177 fUseDirList = random.choice( [True, False] );
4178 fRc = self.gctrlReadDirTree2(oCurGuestSession, oDir, fUseDirList, cEntriesPerRead) and fRc;
4179 fRc = oCurTest.closeSession() and fRc;
4180
4181 return (fRc, oTxsSession);
4182
4183
4184 def testGuestCtrlFileRemove(self, oSession, oTxsSession, oTestVm):
4185 """
4186 Tests removing guest files.
4187 """
4188
4189 #
4190 # Create a directory with a few files in it using TXS that we'll use for the initial tests.
4191 #
4192 asTestDirs = [
4193 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-1'), # [0]
4194 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-1', 'subdir-1'), # [1]
4195 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-1', 'subdir-1', 'subsubdir-1'), # [2]
4196 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-2'), # [3]
4197 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-2', 'subdir-2'), # [4]
4198 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-2', 'subdir-2', 'subsbudir-2'), # [5]
4199 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-3'), # [6]
4200 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-4'), # [7]
4201 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-5'), # [8]
4202 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-5', 'subdir-5'), # [9]
4203 ]
4204 asTestFiles = [
4205 oTestVm.pathJoin(asTestDirs[0], 'file-0'), # [0]
4206 oTestVm.pathJoin(asTestDirs[0], 'file-1'), # [1]
4207 oTestVm.pathJoin(asTestDirs[0], 'file-2'), # [2]
4208 oTestVm.pathJoin(asTestDirs[1], 'file-3'), # [3] - subdir-1
4209 oTestVm.pathJoin(asTestDirs[1], 'file-4'), # [4] - subdir-1
4210 oTestVm.pathJoin(asTestDirs[2], 'file-5'), # [5] - subsubdir-1
4211 oTestVm.pathJoin(asTestDirs[3], 'file-6'), # [6] - rmtestdir-2
4212 oTestVm.pathJoin(asTestDirs[4], 'file-7'), # [7] - subdir-2
4213 oTestVm.pathJoin(asTestDirs[5], 'file-8'), # [8] - subsubdir-2
4214 ];
4215 for sDir in asTestDirs:
4216 if oTxsSession.syncMkDir(sDir, 0o777) is not True:
4217 return reporter.error('Failed to create test dir "%s"!' % (sDir,));
4218 for sFile in asTestFiles:
4219 if oTxsSession.syncUploadString(sFile, sFile, 0o666) is not True:
4220 return reporter.error('Failed to create test file "%s"!' % (sFile,));
4221
4222 #
4223 # Tear down the directories and files.
4224 #
4225 aoTests = [
4226 # Negative tests first:
4227 tdTestRemoveFile(asTestDirs[0], fRcExpect = False),
4228 tdTestRemoveDir(asTestDirs[0], fRcExpect = False),
4229 tdTestRemoveDir(asTestFiles[0], fRcExpect = False),
4230 tdTestRemoveFile(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-file'), fRcExpect = False),
4231 tdTestRemoveDir(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-dir'), fRcExpect = False),
4232 tdTestRemoveFile(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-dir', 'no-file'), fRcExpect = False),
4233 tdTestRemoveDir(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-dir', 'no-subdir'), fRcExpect = False),
4234 tdTestRemoveTree(asTestDirs[0], afFlags = [], fRcExpect = False), # Only removes empty dirs, this isn't empty.
4235 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_None,], fRcExpect = False), # ditto
4236 # Empty paths:
4237 tdTestRemoveFile('', fRcExpect = False),
4238 tdTestRemoveDir('', fRcExpect = False),
4239 tdTestRemoveTree('', fRcExpect = False),
4240 # Now actually remove stuff:
4241 tdTestRemoveDir(asTestDirs[7], fRcExpect = True),
4242 tdTestRemoveFile(asTestDirs[6], fRcExpect = False),
4243 tdTestRemoveDir(asTestDirs[6], fRcExpect = True),
4244 tdTestRemoveFile(asTestFiles[0], fRcExpect = True),
4245 tdTestRemoveFile(asTestFiles[0], fRcExpect = False),
4246 # 17:
4247 tdTestRemoveTree(asTestDirs[8], fRcExpect = True), # Removes empty subdirs and leaves the dir itself.
4248 tdTestRemoveDir(asTestDirs[8], fRcExpect = True),
4249 tdTestRemoveTree(asTestDirs[3], fRcExpect = False), # Have subdirs & files,
4250 tdTestRemoveTree(asTestDirs[3], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentOnly,], fRcExpect = True),
4251 tdTestRemoveDir(asTestDirs[3], fRcExpect = True),
4252 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentAndDir,], fRcExpect = True),
4253 # No error if already delete (RTDirRemoveRecursive artifact).
4254 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentAndDir,], fRcExpect = True),
4255 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentOnly,],
4256 fNotExist = True, fRcExpect = True),
4257 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_None,], fNotExist = True, fRcExpect = True),
4258 ];
4259
4260 #
4261 # Execution loop
4262 #
4263 fRc = True;
4264 for (i, oTest) in enumerate(aoTests): # int, tdTestRemoveBase
4265 reporter.log('Testing #%d, path="%s" %s ...' % (i, oTest.sPath, oTest.__class__.__name__));
4266 fRc = oTest.setEnvironment(oSession, oTxsSession, oTestVm);
4267 if not fRc:
4268 break;
4269 fRc, _ = oTest.createSession('testGuestCtrlFileRemove: Test #%d' % (i,));
4270 if fRc is False:
4271 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4272 break;
4273 fRc = oTest.execute(self) and fRc;
4274 fRc = oTest.closeSession() and fRc;
4275
4276 if fRc is True:
4277 oCurTest = tdTestDirRead();
4278 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4279 if fRc:
4280 fRc, oCurGuestSession = oCurTest.createSession('remove final');
4281 if fRc is True:
4282
4283 #
4284 # Delete all the files in the many subdir of the test set.
4285 #
4286 reporter.log('Deleting the file in "%s" ...' % (self.oTestFiles.oManyDir.sPath,));
4287 for oFile in self.oTestFiles.oManyDir.aoChildren:
4288 reporter.log2('"%s"' % (limitString(oFile.sPath),));
4289 try:
4290 if self.oTstDrv.fpApiVer >= 5.0:
4291 oCurGuestSession.fsObjRemove(oFile.sPath);
4292 else:
4293 oCurGuestSession.fileRemove(oFile.sPath);
4294 except:
4295 fRc = reporter.errorXcpt('Removing "%s" failed' % (oFile.sPath,));
4296
4297 # Remove the directory itself to verify that we've removed all the files in it:
4298 reporter.log('Removing the directory "%s" ...' % (self.oTestFiles.oManyDir.sPath,));
4299 try:
4300 oCurGuestSession.directoryRemove(self.oTestFiles.oManyDir.sPath);
4301 except:
4302 fRc = reporter.errorXcpt('Removing directory "%s" failed' % (self.oTestFiles.oManyDir.sPath,));
4303
4304 #
4305 # Recursively delete the entire test file tree from the root up.
4306 #
4307 # Note! On unix we cannot delete the root dir itself since it is residing
4308 # in /var/tmp where only the owner may delete it. Root is the owner.
4309 #
4310 if oTestVm.isWindows() or oTestVm.isOS2():
4311 afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentAndDir,];
4312 else:
4313 afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentOnly,];
4314 try:
4315 oProgress = oCurGuestSession.directoryRemoveRecursive(self.oTestFiles.oRoot.sPath, afFlags);
4316 except:
4317 fRc = reporter.errorXcpt('Removing tree "%s" failed' % (self.oTestFiles.oRoot.sPath,));
4318 else:
4319 oWrappedProgress = vboxwrappers.ProgressWrapper(oProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv,
4320 "remove-tree-root: %s" % (self.oTestFiles.oRoot.sPath,));
4321 reporter.log2('waiting ...')
4322 oWrappedProgress.wait();
4323 reporter.log2('isSuccess=%s' % (oWrappedProgress.isSuccess(),));
4324 if not oWrappedProgress.isSuccess():
4325 fRc = oWrappedProgress.logResult();
4326
4327 fRc = oCurTest.closeSession() and fRc;
4328
4329 return (fRc, oTxsSession);
4330
4331
4332 def testGuestCtrlFileStat(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4333 """
4334 Tests querying file information through stat.
4335 """
4336
4337 # Basic stuff, existing stuff.
4338 aoTests = [
4339 tdTestSessionEx([
4340 tdStepStatDir('.'),
4341 tdStepStatDir('..'),
4342 tdStepStatDir(self.oTstDrv.getGuestTempDir(oTestVm)),
4343 tdStepStatDir(self.oTstDrv.getGuestSystemDir(oTestVm)),
4344 tdStepStatDirEx(self.oTestFiles.oRoot),
4345 tdStepStatDirEx(self.oTestFiles.oEmptyDir),
4346 tdStepStatDirEx(self.oTestFiles.oTreeDir),
4347 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
4348 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
4349 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
4350 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
4351 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
4352 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
4353 tdStepStatFile(self.oTstDrv.getGuestSystemFileForReading(oTestVm)),
4354 tdStepStatFile(self.oTstDrv.getGuestSystemShell(oTestVm)),
4355 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
4356 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
4357 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
4358 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
4359 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
4360 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
4361 ]),
4362 ];
4363
4364 # None existing stuff.
4365 sSysDir = self.oTstDrv.getGuestSystemDir(oTestVm);
4366 sSep = oTestVm.pathSep();
4367 aoTests += [
4368 tdTestSessionEx([
4369 tdStepStatFileNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory')),
4370 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory') + sSep),
4371 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', '.')),
4372 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', 'NoSuchFileOrSubDirectory')),
4373 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', 'NoSuchFileOrSubDirectory') + sSep),
4374 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', 'NoSuchFileOrSubDirectory', '.')),
4375 #tdStepStatPathNotFound('N:\\'), # ASSUMES nothing mounted on N:!
4376 #tdStepStatPathNotFound('\\\\NoSuchUncServerName\\NoSuchShare'),
4377 ]),
4378 ];
4379 # Invalid parameter check.
4380 aoTests += [ tdTestSessionEx([ tdStepStat('', vbox.ComError.E_INVALIDARG), ]), ];
4381
4382 #
4383 # Execute the tests.
4384 #
4385 fRc, oTxsSession = tdTestSessionEx.executeListTestSessions(aoTests, self.oTstDrv, oSession, oTxsSession,
4386 oTestVm, 'FsStat');
4387 #
4388 # Test the full test file set.
4389 #
4390 if self.oTstDrv.fpApiVer < 5.0:
4391 return (fRc, oTxsSession);
4392
4393 oTest = tdTestGuestCtrlBase();
4394 fRc = oTest.setEnvironment(oSession, oTxsSession, oTestVm);
4395 if not fRc:
4396 return (False, oTxsSession);
4397 fRc2, oGuestSession = oTest.createSession('FsStat on TestFileSet');
4398 if fRc2 is not True:
4399 return (False, oTxsSession);
4400
4401 for oFsObj in self.oTestFiles.dPaths.values():
4402 reporter.log2('testGuestCtrlFileStat: %s sPath=%s'
4403 % ('file' if isinstance(oFsObj, testfileset.TestFile) else 'dir ', limitString(oFsObj.sPath),));
4404
4405 # Query the information:
4406 try:
4407 oFsInfo = oGuestSession.fsObjQueryInfo(oFsObj.sPath, False);
4408 except:
4409 fRc = reporter.errorXcpt('sPath=%s type=%s: fsObjQueryInfo trouble!' % (oFsObj.sPath, type(oFsObj),));
4410 continue;
4411 if oFsInfo is None:
4412 fRc = reporter.error('sPath=%s type=%s: No info object returned!' % (oFsObj.sPath, type(oFsObj),));
4413 continue;
4414
4415 # Check attributes:
4416 try:
4417 eType = oFsInfo.type;
4418 cbObject = oFsInfo.objectSize;
4419 except:
4420 fRc = reporter.errorXcpt('sPath=%s type=%s: attribute access trouble!' % (oFsObj.sPath, type(oFsObj),));
4421 continue;
4422
4423 if isinstance(oFsObj, testfileset.TestFile):
4424 if eType != vboxcon.FsObjType_File:
4425 fRc = reporter.error('sPath=%s type=file: eType=%s, expected %s!'
4426 % (oFsObj.sPath, eType, vboxcon.FsObjType_File));
4427 if cbObject != oFsObj.cbContent:
4428 fRc = reporter.error('sPath=%s type=file: cbObject=%s, expected %s!'
4429 % (oFsObj.sPath, cbObject, oFsObj.cbContent));
4430 fFileExists = True;
4431 fDirExists = False;
4432 elif isinstance(oFsObj, testfileset.TestDir):
4433 if eType != vboxcon.FsObjType_Directory:
4434 fRc = reporter.error('sPath=%s type=dir: eType=%s, expected %s!'
4435 % (oFsObj.sPath, eType, vboxcon.FsObjType_Directory));
4436 fFileExists = False;
4437 fDirExists = True;
4438 else:
4439 fRc = reporter.error('sPath=%s type=%s: Unexpected oFsObj type!' % (oFsObj.sPath, type(oFsObj),));
4440 continue;
4441
4442 # Check the directoryExists and fileExists results too.
4443 try:
4444 fExistsResult = oGuestSession.fileExists(oFsObj.sPath, False);
4445 except:
4446 fRc = reporter.errorXcpt('sPath=%s type=%s: fileExists trouble!' % (oFsObj.sPath, type(oFsObj),));
4447 else:
4448 if fExistsResult != fFileExists:
4449 fRc = reporter.error('sPath=%s type=%s: fileExists returned %s, expected %s!'
4450 % (oFsObj.sPath, type(oFsObj), fExistsResult, fFileExists));
4451 try:
4452 fExistsResult = oGuestSession.directoryExists(oFsObj.sPath, False);
4453 except:
4454 fRc = reporter.errorXcpt('sPath=%s type=%s: directoryExists trouble!' % (oFsObj.sPath, type(oFsObj),));
4455 else:
4456 if fExistsResult != fDirExists:
4457 fRc = reporter.error('sPath=%s type=%s: directoryExists returned %s, expected %s!'
4458 % (oFsObj.sPath, type(oFsObj), fExistsResult, fDirExists));
4459
4460 fRc = oTest.closeSession() and fRc;
4461 return (fRc, oTxsSession);
4462
4463 def testGuestCtrlFileOpen(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4464 """
4465 Tests opening guest files.
4466 """
4467 if self.oTstDrv.fpApiVer < 5.0:
4468 reporter.log('Skipping because of pre 5.0 API');
4469 return None;
4470
4471 #
4472 # Paths.
4473 #
4474 sTempDir = self.oTstDrv.getGuestTempDir(oTestVm);
4475 sFileForReading = self.oTstDrv.getGuestSystemFileForReading(oTestVm);
4476 asFiles = [
4477 oTestVm.pathJoin(sTempDir, 'file-open-0'),
4478 oTestVm.pathJoin(sTempDir, 'file-open-1'),
4479 oTestVm.pathJoin(sTempDir, 'file-open-2'),
4480 oTestVm.pathJoin(sTempDir, 'file-open-3'),
4481 oTestVm.pathJoin(sTempDir, 'file-open-4'),
4482 ];
4483 asNonEmptyFiles = [
4484 oTestVm.pathJoin(sTempDir, 'file-open-10'),
4485 oTestVm.pathJoin(sTempDir, 'file-open-11'),
4486 oTestVm.pathJoin(sTempDir, 'file-open-12'),
4487 oTestVm.pathJoin(sTempDir, 'file-open-13'),
4488 ];
4489 sContent = 'abcdefghijklmnopqrstuvwxyz0123456789';
4490 for sFile in asNonEmptyFiles:
4491 if oTxsSession.syncUploadString(sContent, sFile, 0o666) is not True:
4492 return reporter.error('Failed to create "%s" via TXS' % (sFile,));
4493
4494 #
4495 # The tests.
4496 #
4497 atTests = [
4498 # Invalid stuff.
4499 [ tdTestFileOpen(sFile = ''), tdTestResultFailure() ],
4500 # Wrong open mode.
4501 [ tdTestFileOpen(sFile = sFileForReading, eAccessMode = -1), tdTestResultFailure() ],
4502 # Wrong disposition.
4503 [ tdTestFileOpen(sFile = sFileForReading, eAction = -1), tdTestResultFailure() ],
4504 # Non-existing file or path.
4505 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir')), tdTestResultFailure() ],
4506 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir'),
4507 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultFailure() ],
4508 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir'),
4509 eAccessMode = vboxcon.FileAccessMode_WriteOnly,
4510 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultFailure() ],
4511 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir'),
4512 eAccessMode = vboxcon.FileAccessMode_ReadWrite,
4513 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultFailure() ],
4514 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-dir', 'no-such-file')), tdTestResultFailure() ],
4515 ];
4516 if self.oTstDrv.fpApiVer > 5.2: # Fixed since 6.0.
4517 atTests.extend([
4518 # Wrong type:
4519 [ tdTestFileOpen(sFile = self.oTstDrv.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
4520 [ tdTestFileOpen(sFile = self.oTstDrv.getGuestSystemDir(oTestVm)), tdTestResultFailure() ],
4521 ]);
4522 atTests.extend([
4523 # O_EXCL and such:
4524 [ tdTestFileOpen(sFile = sFileForReading, eAction = vboxcon.FileOpenAction_CreateNew,
4525 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultFailure() ],
4526 [ tdTestFileOpen(sFile = sFileForReading, eAction = vboxcon.FileOpenAction_CreateNew), tdTestResultFailure() ],
4527 # Open a file.
4528 [ tdTestFileOpen(sFile = sFileForReading), tdTestResultSuccess() ],
4529 [ tdTestFileOpen(sFile = sFileForReading,
4530 eAction = vboxcon.FileOpenAction_OpenOrCreate), tdTestResultSuccess() ],
4531 # Create a new file.
4532 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_CreateNew,
4533 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4534 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_CreateNew,
4535 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultFailure() ],
4536 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_OpenExisting,
4537 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4538 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_CreateOrReplace,
4539 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4540 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_OpenOrCreate,
4541 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4542 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_OpenExistingTruncated,
4543 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4544 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_AppendOrCreate,
4545 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4546 # Open or create a new file.
4547 [ tdTestFileOpenCheckSize(sFile = asFiles[1], eAction = vboxcon.FileOpenAction_OpenOrCreate,
4548 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4549 # Create or replace a new file.
4550 [ tdTestFileOpenCheckSize(sFile = asFiles[2], eAction = vboxcon.FileOpenAction_CreateOrReplace,
4551 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4552 # Create and append to file (weird stuff).
4553 [ tdTestFileOpenCheckSize(sFile = asFiles[3], eAction = vboxcon.FileOpenAction_AppendOrCreate,
4554 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4555 [ tdTestFileOpenCheckSize(sFile = asFiles[4], eAction = vboxcon.FileOpenAction_AppendOrCreate,
4556 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4557 # Open the non-empty files in non-destructive modes.
4558 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], cbOpenExpected = len(sContent)), tdTestResultSuccess() ],
4559 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], cbOpenExpected = len(sContent),
4560 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4561 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], cbOpenExpected = len(sContent),
4562 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4563
4564 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], cbOpenExpected = len(sContent),
4565 eAction = vboxcon.FileOpenAction_OpenOrCreate,
4566 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4567 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], cbOpenExpected = len(sContent),
4568 eAction = vboxcon.FileOpenAction_OpenOrCreate,
4569 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4570 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], cbOpenExpected = len(sContent),
4571 eAction = vboxcon.FileOpenAction_OpenOrCreate,
4572 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4573
4574 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], cbOpenExpected = len(sContent),
4575 eAction = vboxcon.FileOpenAction_AppendOrCreate,
4576 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
4577 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], cbOpenExpected = len(sContent),
4578 eAction = vboxcon.FileOpenAction_AppendOrCreate,
4579 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4580 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], cbOpenExpected = len(sContent),
4581 eAction = vboxcon.FileOpenAction_AppendOrCreate,
4582 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4583
4584 # Now the destructive stuff:
4585 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], eAccessMode = vboxcon.FileAccessMode_WriteOnly,
4586 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultSuccess() ],
4587 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], eAccessMode = vboxcon.FileAccessMode_WriteOnly,
4588 eAction = vboxcon.FileOpenAction_CreateOrReplace), tdTestResultSuccess() ],
4589 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], eAction = vboxcon.FileOpenAction_CreateOrReplace,
4590 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
4591 ]);
4592
4593 #
4594 # Do the testing.
4595 #
4596 fRc = True;
4597 for (i, tTest) in enumerate(atTests):
4598 oCurTest = tTest[0] # type: tdTestFileOpen
4599 oCurRes = tTest[1] # type: tdTestResult
4600
4601 reporter.log('Testing #%d: %s - sFile="%s", eAccessMode=%d, eAction=%d, (%s, %s, %s) ...'
4602 % (i, oCurTest.__class__.__name__, oCurTest.sFile, oCurTest.eAccessMode, oCurTest.eAction,
4603 oCurTest.eSharing, oCurTest.fCreationMode, oCurTest.afOpenFlags,));
4604
4605 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4606 if not fRc:
4607 break;
4608 fRc, _ = oCurTest.createSession('testGuestCtrlFileOpen: Test #%d' % (i,));
4609 if fRc is not True:
4610 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4611 break;
4612
4613 fRc2 = oCurTest.doSteps(oCurRes.fRc, self);
4614 if fRc2 != oCurRes.fRc:
4615 fRc = reporter.error('Test #%d result mismatch: Got %s, expected %s' % (i, fRc2, oCurRes.fRc,));
4616
4617 fRc = oCurTest.closeSession() and fRc;
4618
4619 return (fRc, oTxsSession);
4620
4621
4622 def testGuestCtrlFileRead(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-branches,too-many-statements
4623 """
4624 Tests reading from guest files.
4625 """
4626 if self.oTstDrv.fpApiVer < 5.0:
4627 reporter.log('Skipping because of pre 5.0 API');
4628 return None;
4629
4630 #
4631 # Do everything in one session.
4632 #
4633 oTest = tdTestGuestCtrlBase();
4634 fRc = oTest.setEnvironment(oSession, oTxsSession, oTestVm);
4635 if not fRc:
4636 return (False, oTxsSession);
4637 fRc2, oGuestSession = oTest.createSession('FsStat on TestFileSet');
4638 if fRc2 is not True:
4639 return (False, oTxsSession);
4640
4641 #
4642 # Create a really big zero filled, up to 1 GiB, adding it to the list of
4643 # files from the set.
4644 #
4645 # Note! This code sucks a bit because we don't have a working setSize nor
4646 # any way to figure out how much free space there is in the guest.
4647 #
4648 aoExtraFiles = [];
4649 sBigName = self.oTestFiles.generateFilenameEx();
4650 sBigPath = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, sBigName);
4651 fRc = True;
4652 try:
4653 oFile = oGuestSession.fileOpenEx(sBigPath, vboxcon.FileAccessMode_ReadWrite, vboxcon.FileOpenAction_CreateOrReplace,
4654 vboxcon.FileSharingMode_All, 0, []);
4655 except:
4656 fRc = reporter.errorXcpt('sBigName=%s' % (sBigPath,));
4657 else:
4658 # Does setSize work now?
4659 fUseFallback = True;
4660 try:
4661 oFile.setSize(0);
4662 oFile.setSize(64);
4663 fUseFallback = False;
4664 except:
4665 reporter.logXcpt();
4666
4667 # Grow the file till we hit trouble, typical VERR_DISK_FULL, then
4668 # reduce the file size if we have a working setSize.
4669 cbBigFile = 0;
4670 while cbBigFile < (1024 + 32)*1024*1024:
4671 if not fUseFallback:
4672 cbBigFile += 16*1024*1024;
4673 try:
4674 oFile.setSize(cbBigFile);
4675 except Exception:
4676 reporter.logXcpt('cbBigFile=%s' % (sBigPath,));
4677 try:
4678 cbBigFile -= 16*1024*1024;
4679 oFile.setSize(cbBigFile);
4680 except:
4681 reporter.logXcpt('cbBigFile=%s' % (sBigPath,));
4682 break;
4683 else:
4684 cbBigFile += 32*1024*1024;
4685 try:
4686 oFile.seek(cbBigFile, vboxcon.FileSeekOrigin_Begin);
4687 oFile.write(bytearray(1), 60*1000);
4688 except:
4689 reporter.logXcpt('cbBigFile=%s' % (sBigPath,));
4690 break;
4691 try:
4692 cbBigFile = oFile.seek(0, vboxcon.FileSeekOrigin_End);
4693 except:
4694 fRc = reporter.errorXcpt('sBigName=%s' % (sBigPath,));
4695 try:
4696 oFile.close();
4697 except:
4698 fRc = reporter.errorXcpt('sBigName=%s' % (sBigPath,));
4699 if fRc is True:
4700 reporter.log('Big file: %s bytes: %s' % (cbBigFile, sBigPath,));
4701 aoExtraFiles.append(testfileset.TestFileZeroFilled(None, sBigPath, cbBigFile));
4702 else:
4703 try:
4704 oGuestSession.fsObjRemove(sBigPath);
4705 except:
4706 reporter.errorXcpt('fsObjRemove(sBigName=%s)' % (sBigPath,));
4707
4708 #
4709 # Open and read all the files in the test file set.
4710 #
4711 for oTestFile in aoExtraFiles + self.oTestFiles.aoFiles: # type: testfileset.TestFile
4712 reporter.log2('Test file: %s bytes, "%s" ...' % (oTestFile.cbContent, limitString(oTestFile.sPath),));
4713
4714 #
4715 # Open it:
4716 #
4717 try:
4718 oFile = oGuestSession.fileOpenEx(oTestFile.sPath, vboxcon.FileAccessMode_ReadOnly,
4719 vboxcon.FileOpenAction_OpenExisting, vboxcon.FileSharingMode_All, 0, []);
4720 except:
4721 fRc = reporter.errorXcpt('sPath=%s' % (oTestFile.sPath, ));
4722 continue;
4723
4724 #
4725 # Read the file in different sized chunks:
4726 #
4727 if oTestFile.cbContent < 128:
4728 acbChunks = xrange(1,128);
4729 elif oTestFile.cbContent < 1024:
4730 acbChunks = (2048, 127, 63, 32, 29, 17, 16, 15, 9);
4731 elif oTestFile.cbContent < 8*1024*1024:
4732 acbChunks = (128*1024, 32*1024, 8191, 255);
4733 else:
4734 acbChunks = (768*1024, 128*1024);
4735
4736 reporter.log2('Chunked reads');
4737
4738 for cbChunk in acbChunks:
4739 # Read the whole file straight thru:
4740 #if oTestFile.cbContent >= 1024*1024: reporter.log2('... cbChunk=%s' % (cbChunk,));
4741 offFile = 0;
4742 cReads = 0;
4743 while offFile <= oTestFile.cbContent:
4744 try:
4745 abRead = oFile.read(cbChunk, 30*1000);
4746 except:
4747 fRc = reporter.errorXcpt('%s: offFile=%s cbChunk=%s cbContent=%s'
4748 % (oTestFile.sPath, offFile, cbChunk, oTestFile.cbContent));
4749 break;
4750 cbRead = len(abRead);
4751 if cbRead == 0 and offFile == oTestFile.cbContent:
4752 break;
4753 if cbRead <= 0:
4754 fRc = reporter.error('%s @%s: cbRead=%s, cbContent=%s'
4755 % (oTestFile.sPath, offFile, cbRead, oTestFile.cbContent));
4756 break;
4757 if not oTestFile.equalMemory(abRead, offFile):
4758 fRc = reporter.error('%s: read mismatch @ %s LB %s' % (oTestFile.sPath, offFile, cbRead));
4759 break;
4760 offFile += cbRead;
4761 cReads += 1;
4762 if cReads > 8192:
4763 break;
4764
4765 # Seek to start of file.
4766 try:
4767 offFile = oFile.seek(0, vboxcon.FileSeekOrigin_Begin);
4768 except:
4769 fRc = reporter.errorXcpt('%s: error seeking to start of file' % (oTestFile.sPath,));
4770 break;
4771 if offFile != 0:
4772 fRc = reporter.error('%s: seek to start of file returned %u, expected 0' % (oTestFile.sPath, offFile));
4773 break;
4774
4775 #
4776 # Random reads.
4777 #
4778 reporter.log2('Random reads (seek)');
4779 for _ in xrange(8):
4780 offFile = self.oTestFiles.oRandom.randrange(0, oTestFile.cbContent + 1024);
4781 cbToRead = self.oTestFiles.oRandom.randrange(1, min(oTestFile.cbContent + 256, 768*1024));
4782 #if oTestFile.cbContent >= 1024*1024: reporter.log2('... %s LB %s' % (offFile, cbToRead,));
4783
4784 try:
4785 offActual = oFile.seek(offFile, vboxcon.FileSeekOrigin_Begin);
4786 except:
4787 fRc = reporter.errorXcpt('%s: error seeking to %s' % (oTestFile.sPath, offFile));
4788 break;
4789 if offActual != offFile:
4790 fRc = reporter.error('%s: seek(%s,Begin) -> %s, expected %s'
4791 % (oTestFile.sPath, offFile, offActual, offFile));
4792 break;
4793
4794 try:
4795 abRead = oFile.read(cbToRead, 30*1000);
4796 except:
4797 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s'
4798 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4799 cbRead = 0;
4800 else:
4801 cbRead = len(abRead);
4802 if not oTestFile.equalMemory(abRead, offFile):
4803 fRc = reporter.error('%s: random read mismatch @ %s LB %s' % (oTestFile.sPath, offFile, cbRead,));
4804
4805 try:
4806 offActual = oFile.offset;
4807 except:
4808 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#1)'
4809 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4810 else:
4811 if offActual != offFile + cbRead:
4812 fRc = reporter.error('%s: IFile.offset is %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#1)'
4813 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4814 try:
4815 offActual = oFile.seek(0, vboxcon.FileSeekOrigin_Current);
4816 except:
4817 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#1)'
4818 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4819 else:
4820 if offActual != offFile + cbRead:
4821 fRc = reporter.error('%s: seek(0,cur) -> %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#1)'
4822 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4823
4824 #
4825 # Random reads using readAt.
4826 #
4827 reporter.log2('Random reads (readAt)');
4828 for _ in xrange(12):
4829 offFile = self.oTestFiles.oRandom.randrange(0, oTestFile.cbContent + 1024);
4830 cbToRead = self.oTestFiles.oRandom.randrange(1, min(oTestFile.cbContent + 256, 768*1024));
4831 #if oTestFile.cbContent >= 1024*1024: reporter.log2('... %s LB %s (readAt)' % (offFile, cbToRead,));
4832
4833 try:
4834 abRead = oFile.readAt(offFile, cbToRead, 30*1000);
4835 except:
4836 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s'
4837 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4838 cbRead = 0;
4839 else:
4840 cbRead = len(abRead);
4841 if not oTestFile.equalMemory(abRead, offFile):
4842 fRc = reporter.error('%s: random readAt mismatch @ %s LB %s' % (oTestFile.sPath, offFile, cbRead,));
4843
4844 try:
4845 offActual = oFile.offset;
4846 except:
4847 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#2)'
4848 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4849 else:
4850 if offActual != offFile + cbRead:
4851 fRc = reporter.error('%s: IFile.offset is %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#2)'
4852 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4853
4854 try:
4855 offActual = oFile.seek(0, vboxcon.FileSeekOrigin_Current);
4856 except:
4857 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#2)'
4858 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4859 else:
4860 if offActual != offFile + cbRead:
4861 fRc = reporter.error('%s: seek(0,cur) -> %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#2)'
4862 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4863
4864 #
4865 # A few negative things.
4866 #
4867
4868 # Zero byte reads -> E_INVALIDARG.
4869 reporter.log2('Zero byte reads');
4870 try:
4871 abRead = oFile.read(0, 30*1000);
4872 except Exception as oXcpt:
4873 if vbox.ComError.notEqual(oXcpt, vbox.ComError.E_INVALIDARG):
4874 fRc = reporter.errorXcpt('read(0,30s) did not raise E_INVALIDARG as expected!');
4875 else:
4876 fRc = reporter.error('read(0,30s) did not fail!');
4877
4878 try:
4879 abRead = oFile.readAt(0, 0, 30*1000);
4880 except Exception as oXcpt:
4881 if vbox.ComError.notEqual(oXcpt, vbox.ComError.E_INVALIDARG):
4882 fRc = reporter.errorXcpt('readAt(0,0,30s) did not raise E_INVALIDARG as expected!');
4883 else:
4884 fRc = reporter.error('readAt(0,0,30s) did not fail!');
4885
4886 # See what happens when we read 1GiB. We should get a max of 1MiB back.
4887 ## @todo Document this behaviour in VirtualBox.xidl.
4888 reporter.log2('1GB reads');
4889 try:
4890 oFile.seek(0, vboxcon.FileSeekOrigin_Begin);
4891 except:
4892 fRc = reporter.error('seek(0)');
4893 try:
4894 abRead = oFile.read(1024*1024*1024, 30*1000);
4895 except:
4896 fRc = reporter.errorXcpt('read(1GiB,30s)');
4897 else:
4898 if len(abRead) != min(oTestFile.cbContent, 1024*1024):
4899 fRc = reporter.error('Expected read(1GiB,30s) to return %s bytes, got %s bytes instead'
4900 % (min(oTestFile.cbContent, 1024*1024), len(abRead),));
4901
4902 try:
4903 abRead = oFile.readAt(0, 1024*1024*1024, 30*1000);
4904 except:
4905 fRc = reporter.errorXcpt('readAt(0,1GiB,30s)');
4906 else:
4907 if len(abRead) != min(oTestFile.cbContent, 1024*1024):
4908 reporter.error('Expected readAt(0, 1GiB,30s) to return %s bytes, got %s bytes instead'
4909 % (min(oTestFile.cbContent, 1024*1024), len(abRead),));
4910
4911 #
4912 # Check stat info on the file as well as querySize.
4913 #
4914 if self.oTstDrv.fpApiVer > 5.2:
4915 try:
4916 oFsObjInfo = oFile.queryInfo();
4917 except:
4918 fRc = reporter.errorXcpt('%s: queryInfo()' % (oTestFile.sPath,));
4919 else:
4920 if oFsObjInfo is None:
4921 fRc = reporter.error('IGuestFile::queryInfo returned None');
4922 else:
4923 try:
4924 cbFile = oFsObjInfo.objectSize;
4925 except:
4926 fRc = reporter.errorXcpt();
4927 else:
4928 if cbFile != oTestFile.cbContent:
4929 fRc = reporter.error('%s: queryInfo returned incorrect file size: %s, expected %s'
4930 % (oTestFile.sPath, cbFile, oTestFile.cbContent));
4931
4932 try:
4933 cbFile = oFile.querySize();
4934 except:
4935 fRc = reporter.errorXcpt('%s: querySize()' % (oTestFile.sPath,));
4936 else:
4937 if cbFile != oTestFile.cbContent:
4938 fRc = reporter.error('%s: querySize returned incorrect file size: %s, expected %s'
4939 % (oTestFile.sPath, cbFile, oTestFile.cbContent));
4940
4941 #
4942 # Use seek to test the file size and do a few other end-relative seeks.
4943 #
4944 try:
4945 cbFile = oFile.seek(0, vboxcon.FileSeekOrigin_End);
4946 except:
4947 fRc = reporter.errorXcpt('%s: seek(0,End)' % (oTestFile.sPath,));
4948 else:
4949 if cbFile != oTestFile.cbContent:
4950 fRc = reporter.error('%s: seek(0,End) returned incorrect file size: %s, expected %s'
4951 % (oTestFile.sPath, cbFile, oTestFile.cbContent));
4952 if oTestFile.cbContent > 0:
4953 for _ in xrange(5):
4954 offSeek = self.oTestFiles.oRandom.randrange(oTestFile.cbContent + 1);
4955 try:
4956 offFile = oFile.seek(-offSeek, vboxcon.FileSeekOrigin_End);
4957 except:
4958 fRc = reporter.errorXcpt('%s: seek(%s,End)' % (oTestFile.sPath, -offSeek,));
4959 else:
4960 if offFile != oTestFile.cbContent - offSeek:
4961 fRc = reporter.error('%s: seek(%s,End) returned incorrect offset: %s, expected %s (cbContent=%s)'
4962 % (oTestFile.sPath, -offSeek, offSeek, oTestFile.cbContent - offSeek,
4963 oTestFile.cbContent,));
4964
4965 #
4966 # Close it and we're done with this file.
4967 #
4968 try:
4969 oFile.close();
4970 except:
4971 fRc = reporter.errorXcpt('%s: error closing the file' % (oTestFile.sPath,));
4972
4973 #
4974 # Clean up.
4975 #
4976 for oTestFile in aoExtraFiles:
4977 try:
4978 oGuestSession.fsObjRemove(sBigPath);
4979 except:
4980 fRc = reporter.errorXcpt('fsObjRemove(%s)' % (sBigPath,));
4981
4982 fRc = oTest.closeSession() and fRc;
4983
4984 return (fRc, oTxsSession);
4985
4986
4987 def testGuestCtrlFileWrite(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4988 """
4989 Tests writing to guest files.
4990 """
4991 if self.oTstDrv.fpApiVer < 5.0:
4992 reporter.log('Skipping because of pre 5.0 API');
4993 return None;
4994
4995 #
4996 # The test file and its content.
4997 #
4998 sFile = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), 'gctrl-write-1');
4999 abContent = bytearray(0);
5000
5001 #
5002 # The tests.
5003 #
5004 def randBytes(cbHowMany):
5005 """ Returns an bytearray of random bytes. """
5006 return bytearray(self.oTestFiles.oRandom.getrandbits(8) for _ in xrange(cbHowMany));
5007
5008 aoTests = [
5009 # Write at end:
5010 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_CreateNew, abContent = abContent,
5011 atChunks = [(None, randBytes(1)), (None, randBytes(77)), (None, randBytes(98)),]),
5012 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 1+77+98), # 176
5013 # Appending:
5014 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_AppendOrCreate, abContent = abContent,
5015 atChunks = [(None, randBytes(255)), (None, randBytes(33)),]),
5016 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 176 + 255+33), # 464
5017 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_AppendOrCreate, abContent = abContent,
5018 atChunks = [(10, randBytes(44)),]),
5019 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 464 + 44), # 508
5020 # Write within existing:
5021 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_OpenExisting, abContent = abContent,
5022 atChunks = [(0, randBytes(1)), (50, randBytes(77)), (255, randBytes(199)),]),
5023 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 508),
5024 # Writing around and over the end:
5025 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent,
5026 atChunks = [(500, randBytes(9)), (508, randBytes(15)), (512, randBytes(12)),]),
5027 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 512+12),
5028
5029 # writeAt appending:
5030 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True,
5031 atChunks = [(0, randBytes(23)), (6, randBytes(1018)),]),
5032 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 6+1018), # 1024
5033 # writeAt within existing:
5034 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True,
5035 atChunks = [(1000, randBytes(23)), (1, randBytes(990)),]),
5036 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 1024),
5037 # writeAt around and over the end:
5038 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True,
5039 atChunks = [(1024, randBytes(63)), (1080, randBytes(968)),]),
5040 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 1080+968), # 2048
5041
5042 # writeAt beyond the end (gap is filled with zeros):
5043 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True, atChunks = [(3070, randBytes(2)),]),
5044 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 3072),
5045 # write beyond the end (gap is filled with zeros):
5046 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, atChunks = [(4090, randBytes(6)),]),
5047 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 4096),
5048 ];
5049
5050 for (i, oCurTest) in enumerate(aoTests):
5051 reporter.log('Testing #%d: %s ...' % (i, oCurTest.toString(),));
5052 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
5053 if not fRc:
5054 break;
5055 fRc, _ = oCurTest.createSession('testGuestCtrlFileWrite: Test #%d' % (i,));
5056 if fRc is not True:
5057 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
5058 break;
5059
5060 fRc2 = oCurTest.doSteps(True, self);
5061 if fRc2 is not True:
5062 fRc = reporter.error('Test #%d failed!' % (i,));
5063
5064 fRc = oCurTest.closeSession() and fRc;
5065
5066 #
5067 # Cleanup
5068 #
5069 if oTxsSession.syncRmFile(sFile) is not True:
5070 fRc = reporter.error('Failed to remove write-test file: %s' % (sFile, ));
5071
5072 return (fRc, oTxsSession);
5073
5074 @staticmethod
5075 def __generateFile(sName, cbFile):
5076 """ Helper for generating a file with a given size. """
5077 with open(sName, 'wb') as oFile:
5078 while cbFile > 0:
5079 cb = cbFile if cbFile < 256*1024 else 256*1024;
5080 oFile.write(bytearray(random.getrandbits(8) for _ in xrange(cb)));
5081 cbFile -= cb;
5082 return True;
5083
5084 def testGuestCtrlCopyTo(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
5085 """
5086 Tests copying files from host to the guest.
5087 """
5088
5089 #
5090 # Paths and test files.
5091 #
5092 sScratchHst = os.path.join(self.oTstDrv.sScratchPath, 'copyto');
5093 sScratchTestFilesHst = os.path.join(sScratchHst, self.oTestFiles.sSubDir);
5094 sScratchEmptyDirHst = os.path.join(sScratchTestFilesHst, self.oTestFiles.oEmptyDir.sName);
5095 sScratchNonEmptyDirHst = self.oTestFiles.chooseRandomDirFromTree().buildPath(sScratchHst, os.path.sep);
5096 sScratchTreeDirHst = os.path.join(sScratchTestFilesHst, self.oTestFiles.oTreeDir.sName);
5097
5098 sScratchGst = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), 'copyto');
5099 sScratchDstDir1Gst = oTestVm.pathJoin(sScratchGst, 'dstdir1');
5100 sScratchDstDir2Gst = oTestVm.pathJoin(sScratchGst, 'dstdir2');
5101 sScratchDstDir3Gst = oTestVm.pathJoin(sScratchGst, 'dstdir3');
5102 sScratchDstDir4Gst = oTestVm.pathJoin(sScratchGst, 'dstdir4');
5103 sScratchDotDotDirGst = oTestVm.pathJoin(sScratchGst, '..');
5104 #sScratchGstNotExist = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), 'no-such-file-or-directory');
5105 sScratchHstNotExist = os.path.join(self.oTstDrv.sScratchPath, 'no-such-file-or-directory');
5106 sScratchGstPathNotFound = oTestVm.pathJoin(self.oTstDrv.getGuestTempDir(oTestVm), 'no-such-directory', 'or-file');
5107 #sScratchHstPathNotFound = os.path.join(self.oTstDrv.sScratchPath, 'no-such-directory', 'or-file');
5108
5109 if oTestVm.isWindows() or oTestVm.isOS2():
5110 sScratchGstInvalid = "?*|<invalid-name>";
5111 else:
5112 sScratchGstInvalid = None;
5113 if utils.getHostOs() in ('win', 'os2'):
5114 sScratchHstInvalid = "?*|<invalid-name>";
5115 else:
5116 sScratchHstInvalid = None;
5117
5118 for sDir in (sScratchGst, sScratchDstDir1Gst, sScratchDstDir2Gst, sScratchDstDir3Gst, sScratchDstDir4Gst):
5119 if oTxsSession.syncMkDir(sDir, 0o777) is not True:
5120 return reporter.error('TXS failed to create directory "%s"!' % (sDir,));
5121
5122 # Put the test file set under sScratchHst.
5123 if os.path.exists(sScratchHst):
5124 if base.wipeDirectory(sScratchHst) != 0:
5125 return reporter.error('Failed to wipe "%s"' % (sScratchHst,));
5126 else:
5127 try:
5128 os.mkdir(sScratchHst);
5129 except:
5130 return reporter.errorXcpt('os.mkdir(%s)' % (sScratchHst, ));
5131 if self.oTestFiles.writeToDisk(sScratchHst) is not True:
5132 return reporter.error('Filed to write test files to "%s" on the host!' % (sScratchHst,));
5133
5134 # If for whatever reason the directory tree does not exist on the host, let us know.
5135 # Copying an non-existing tree *will* fail the tests which otherwise should succeed!
5136 assert os.path.exists(sScratchTreeDirHst);
5137
5138 # Generate a test file in 32MB to 64 MB range.
5139 sBigFileHst = os.path.join(self.oTstDrv.sScratchPath, 'gctrl-random.data');
5140 cbBigFileHst = random.randrange(32*1024*1024, 64*1024*1024);
5141 reporter.log('cbBigFileHst=%s' % (cbBigFileHst,));
5142 cbLeft = cbBigFileHst;
5143 try:
5144 self.__generateFile(sBigFileHst, cbBigFileHst);
5145 except:
5146 return reporter.errorXcpt('sBigFileHst=%s cbBigFileHst=%s cbLeft=%s' % (sBigFileHst, cbBigFileHst, cbLeft,));
5147 reporter.log('cbBigFileHst=%s' % (cbBigFileHst,));
5148
5149 # Generate an empty file on the host that we can use to save space in the guest.
5150 sEmptyFileHst = os.path.join(self.oTstDrv.sScratchPath, 'gctrl-empty.data');
5151 try:
5152 open(sEmptyFileHst, "wb").close(); # pylint: disable=consider-using-with
5153 except:
5154 return reporter.errorXcpt('sEmptyFileHst=%s' % (sEmptyFileHst,));
5155
5156 # os.path.join() is too clever for "..", so we just build up the path here ourselves.
5157 sScratchDotDotFileHst = sScratchHst + os.path.sep + '..' + os.path.sep + 'gctrl-empty.data';
5158
5159 #
5160 # Tests.
5161 #
5162 atTests = [
5163 # Nothing given:
5164 [ tdTestCopyToFile(), tdTestResultFailure() ],
5165 [ tdTestCopyToDir(), tdTestResultFailure() ],
5166 # Only source given:
5167 [ tdTestCopyToFile(sSrc = sBigFileHst), tdTestResultFailure() ],
5168 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst), tdTestResultFailure() ],
5169 # Only destination given:
5170 [ tdTestCopyToFile(sDst = oTestVm.pathJoin(sScratchGst, 'dstfile')), tdTestResultFailure() ],
5171 [ tdTestCopyToDir( sDst = sScratchGst), tdTestResultFailure() ],
5172 # Both given, but invalid flags.
5173 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGst, afFlags = [ 0x40000000, ] ), tdTestResultFailure() ],
5174 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst, sDst = sScratchGst, afFlags = [ 0x40000000, ] ),
5175 tdTestResultFailure() ],
5176 ];
5177 atTests.extend([
5178 # Non-existing source, but no destination:
5179 [ tdTestCopyToFile(sSrc = sScratchHstNotExist), tdTestResultFailure() ],
5180 [ tdTestCopyToDir( sSrc = sScratchHstNotExist), tdTestResultFailure() ],
5181 # Valid sources, but destination path not found:
5182 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGstPathNotFound), tdTestResultFailure() ],
5183 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst, sDst = sScratchGstPathNotFound), tdTestResultFailure() ],
5184 # Valid destination, but source file/dir not found:
5185 [ tdTestCopyToFile(sSrc = sScratchHstNotExist, sDst = oTestVm.pathJoin(sScratchGst, 'dstfile')),
5186 tdTestResultFailure() ],
5187 [ tdTestCopyToDir( sSrc = sScratchHstNotExist, sDst = sScratchGst), tdTestResultFailure() ],
5188 # Wrong type:
5189 [ tdTestCopyToFile(sSrc = sScratchEmptyDirHst, sDst = oTestVm.pathJoin(sScratchGst, 'dstfile')),
5190 tdTestResultFailure() ],
5191 [ tdTestCopyToDir( sSrc = sBigFileHst, sDst = sScratchGst), tdTestResultFailure() ],
5192 ]);
5193 # Invalid characters in destination or source path:
5194 if sScratchGstInvalid is not None:
5195 atTests.extend([
5196 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, sScratchGstInvalid)),
5197 tdTestResultFailure() ],
5198 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst, sDst = oTestVm.pathJoin(sScratchGst, sScratchGstInvalid)),
5199 tdTestResultFailure() ],
5200 ]);
5201 if sScratchHstInvalid is not None:
5202 atTests.extend([
5203 [ tdTestCopyToFile(sSrc = os.path.join(self.oTstDrv.sScratchPath, sScratchHstInvalid), sDst = sScratchGst),
5204 tdTestResultFailure() ],
5205 [ tdTestCopyToDir( sSrc = os.path.join(self.oTstDrv.sScratchPath, sScratchHstInvalid), sDst = sScratchGst),
5206 tdTestResultFailure() ],
5207 ]);
5208
5209 #
5210 # Single file handling.
5211 #
5212 atTests.extend([
5213 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat')),
5214 tdTestResultSuccess() ],
5215 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat')), # Overwrite
5216 tdTestResultSuccess() ],
5217 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat')), # Overwrite
5218 tdTestResultSuccess() ],
5219 ]);
5220 if self.oTstDrv.fpApiVer > 5.2: # Copying files into directories via Main is supported only 6.0 and later.
5221 atTests.extend([
5222 # Should succeed, as the file isn't there yet on the destination.
5223 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGst + oTestVm.pathSep()), tdTestResultSuccess() ],
5224 # Overwrite the existing file.
5225 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGst + oTestVm.pathSep()), tdTestResultSuccess() ],
5226 # Same file, but with a different name on the destination.
5227 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = oTestVm.pathJoin(sScratchGst, os.path.split(sBigFileHst)[1])),
5228 tdTestResultSuccess() ], # Overwrite
5229 ]);
5230
5231 if oTestVm.isWindows():
5232 # Copy to a Windows alternative data stream (ADS).
5233 atTests.extend([
5234 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat:ADS-Test')),
5235 tdTestResultSuccess() ],
5236 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat:ADS-Test')),
5237 tdTestResultSuccess() ],
5238 ]);
5239
5240 #
5241 # Directory handling.
5242 #
5243 if self.oTstDrv.fpApiVer > 5.2: # Copying directories via Main is supported only in versions > 5.2.
5244 atTests.extend([
5245 # Without a trailing slash added to the destination this should fail,
5246 # as the destination directory already exists.
5247 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir1Gst), tdTestResultFailure() ],
5248 # Same existing host directory, but this time with DirectoryCopyFlag_CopyIntoExisting set.
5249 # This should copy the contents of oEmptyDirGst to sScratchDstDir1Gst (empty, but anyway).
5250 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir1Gst,
5251 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5252 # Try again.
5253 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir1Gst,
5254 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5255 # With a trailing slash added to the destination, copy the empty guest directory
5256 # (should end up as sScratchDstDir2Gst/empty):
5257 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir2Gst + oTestVm.pathSep()),
5258 tdTestResultSuccess() ],
5259 # Repeat -- this time it should fail, as the destination directory already exists (and
5260 # DirectoryCopyFlag_CopyIntoExisting is not specified):
5261 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir2Gst + oTestVm.pathSep()),
5262 tdTestResultFailure() ],
5263 # Add the DirectoryCopyFlag_CopyIntoExisting flag being set and it should work (again).
5264 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir2Gst + oTestVm.pathSep(),
5265 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5266 # Copy with a different destination name just for the heck of it:
5267 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = oTestVm.pathJoin(sScratchDstDir2Gst, 'empty2')),
5268 tdTestResultSuccess() ],
5269 ]);
5270 atTests.extend([
5271 # Now the same using a directory with files in it:
5272 [ tdTestCopyToDir(sSrc = sScratchNonEmptyDirHst, sDst = sScratchDstDir3Gst,
5273 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5274 # Again.
5275 [ tdTestCopyToDir(sSrc = sScratchNonEmptyDirHst, sDst = sScratchDstDir3Gst,
5276 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5277 ]);
5278 atTests.extend([
5279 # Copy the entire test tree:
5280 [ tdTestCopyToDir(sSrc = sScratchTreeDirHst, sDst = sScratchDstDir4Gst + oTestVm.pathSep()),
5281 tdTestResultSuccess() ],
5282 # Again, should fail this time.
5283 [ tdTestCopyToDir(sSrc = sScratchTreeDirHst, sDst = sScratchDstDir4Gst + oTestVm.pathSep()),
5284 tdTestResultFailure() ],
5285 # Works again, as DirectoryCopyFlag_CopyIntoExisting is specified.
5286 [ tdTestCopyToDir(sSrc = sScratchTreeDirHst, sDst = sScratchDstDir4Gst + oTestVm.pathSep(),
5287 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5288 ]);
5289 #
5290 # Dotdot path handling.
5291 #
5292 if self.oTstDrv.fpApiVer >= 6.1:
5293 atTests.extend([
5294 # Test if copying stuff from a host dotdot ".." directory works.
5295 [ tdTestCopyToFile(sSrc = sScratchDotDotFileHst, sDst = sScratchDstDir1Gst + oTestVm.pathSep()),
5296 tdTestResultSuccess() ],
5297 # Test if copying stuff from the host to a guest's dotdot ".." directory works.
5298 # That should fail on destinations.
5299 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = sScratchDotDotDirGst), tdTestResultFailure() ],
5300 ]);
5301
5302 fRc = True;
5303 for (i, tTest) in enumerate(atTests):
5304 oCurTest = tTest[0]; # tdTestCopyTo
5305 oCurRes = tTest[1]; # tdTestResult
5306 reporter.log('Testing #%d, sSrc=%s, sDst=%s, afFlags=%s ...'
5307 % (i, limitString(oCurTest.sSrc), limitString(oCurTest.sDst), oCurTest.afFlags));
5308
5309 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
5310 if not fRc:
5311 break;
5312 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlCopyTo: Test #%d' % (i,));
5313 if fRc is not True:
5314 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
5315 break;
5316
5317 fRc2 = False;
5318 if isinstance(oCurTest, tdTestCopyToFile):
5319 fRc2 = self.gctrlCopyFileTo(oCurGuestSession, oCurTest.sSrc, oCurTest.sDst, oCurTest.afFlags, oCurRes.fRc);
5320 else:
5321 fRc2 = self.gctrlCopyDirTo(oCurGuestSession, oCurTest.sSrc, oCurTest.sDst, oCurTest.afFlags, oCurRes.fRc);
5322 if fRc2 is not oCurRes.fRc:
5323 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc));
5324
5325 fRc = oCurTest.closeSession() and fRc;
5326
5327 return (fRc, oTxsSession);
5328
5329 def testGuestCtrlCopyFrom(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
5330 """
5331 Tests copying files from guest to the host.
5332 """
5333
5334 reporter.log2('Entered');
5335
5336 #
5337 # Paths.
5338 #
5339 sScratchHst = os.path.join(self.oTstDrv.sScratchPath, "testGctrlCopyFrom");
5340 sScratchDstDir1Hst = os.path.join(sScratchHst, "dstdir1");
5341 sScratchDstDir2Hst = os.path.join(sScratchHst, "dstdir2");
5342 sScratchDstDir3Hst = os.path.join(sScratchHst, "dstdir3");
5343 sScratchDstDir4Hst = os.path.join(sScratchHst, "dstdir4");
5344 # os.path.join() is too clever for "..", so we just build up the path here ourselves.
5345 sScratchDotDotDirHst = sScratchHst + os.path.sep + '..' + os.path.sep;
5346 oExistingFileGst = self.oTestFiles.chooseRandomFile();
5347 oNonEmptyDirGst = self.oTestFiles.chooseRandomDirFromTree(fNonEmpty = True);
5348 oTreeDirGst = self.oTestFiles.oTreeDir;
5349 oEmptyDirGst = self.oTestFiles.oEmptyDir;
5350
5351 if oTestVm.isWindows() or oTestVm.isOS2():
5352 sScratchGstInvalid = "?*|<invalid-name>";
5353 else:
5354 sScratchGstInvalid = None;
5355 if utils.getHostOs() in ('win', 'os2'):
5356 sScratchHstInvalid = "?*|<invalid-name>";
5357 else:
5358 sScratchHstInvalid = None;
5359
5360 sScratchDotDotDirGst = oTestVm.pathJoin(oEmptyDirGst.sPath, '..');
5361
5362 if os.path.exists(sScratchHst):
5363 if base.wipeDirectory(sScratchHst) != 0:
5364 return reporter.error('Failed to wipe "%s"' % (sScratchHst,));
5365 else:
5366 try:
5367 os.mkdir(sScratchHst);
5368 except:
5369 return reporter.errorXcpt('os.mkdir(%s)' % (sScratchHst, ));
5370
5371 reporter.log2('Creating host sub dirs ...');
5372
5373 for sSubDir in (sScratchDstDir1Hst, sScratchDstDir2Hst, sScratchDstDir3Hst, sScratchDstDir4Hst):
5374 try:
5375 os.mkdir(sSubDir);
5376 except:
5377 return reporter.errorXcpt('os.mkdir(%s)' % (sSubDir, ));
5378
5379 reporter.log2('Defining tests ...');
5380
5381 #
5382 # Bad parameter tests.
5383 #
5384 atTests = [
5385 # Missing both source and destination:
5386 [ tdTestCopyFromFile(), tdTestResultFailure() ],
5387 [ tdTestCopyFromDir(), tdTestResultFailure() ],
5388 # Missing source.
5389 [ tdTestCopyFromFile(sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
5390 [ tdTestCopyFromDir( sDst = sScratchHst), tdTestResultFailure() ],
5391 # Missing destination.
5392 [ tdTestCopyFromFile(oSrc = oExistingFileGst), tdTestResultFailure() ],
5393 [ tdTestCopyFromDir( sSrc = self.oTestFiles.oManyDir.sPath), tdTestResultFailure() ],
5394 # Invalid flags:
5395 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'somefile'), afFlags = [0x40000000]),
5396 tdTestResultFailure() ],
5397 [ tdTestCopyFromDir( oSrc = oEmptyDirGst, sDst = os.path.join(sScratchHst, 'somedir'), afFlags = [ 0x40000000] ),
5398 tdTestResultFailure() ],
5399 # Non-existing sources:
5400 [ tdTestCopyFromFile(sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-file-or-directory'),
5401 sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
5402 [ tdTestCopyFromDir( sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-file-or-directory'),
5403 sDst = os.path.join(sScratchHst, 'somedir')), tdTestResultFailure() ],
5404 [ tdTestCopyFromFile(sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-directory', 'no-such-file'),
5405 sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
5406 [ tdTestCopyFromDir( sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-directory', 'no-such-subdir'),
5407 sDst = os.path.join(sScratchHst, 'somedir')), tdTestResultFailure() ],
5408 # Non-existing destinations:
5409 [ tdTestCopyFromFile(oSrc = oExistingFileGst,
5410 sDst = os.path.join(sScratchHst, 'no-such-directory', 'somefile') ), tdTestResultFailure() ],
5411 [ tdTestCopyFromDir( oSrc = oEmptyDirGst, sDst = os.path.join(sScratchHst, 'no-such-directory', 'somedir') ),
5412 tdTestResultFailure() ],
5413 [ tdTestCopyFromFile(oSrc = oExistingFileGst,
5414 sDst = os.path.join(sScratchHst, 'no-such-directory-slash' + os.path.sep)),
5415 tdTestResultFailure() ],
5416 # Wrong source type:
5417 [ tdTestCopyFromFile(oSrc = oNonEmptyDirGst, sDst = os.path.join(sScratchHst, 'somefile') ), tdTestResultFailure() ],
5418 [ tdTestCopyFromDir(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'somedir') ), tdTestResultFailure() ],
5419 ];
5420 # Bogus names:
5421 if sScratchHstInvalid:
5422 atTests.extend([
5423 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, sScratchHstInvalid)),
5424 tdTestResultFailure() ],
5425 [ tdTestCopyFromDir( sSrc = self.oTestFiles.oManyDir.sPath, sDst = os.path.join(sScratchHst, sScratchHstInvalid)),
5426 tdTestResultFailure() ],
5427 ]);
5428 if sScratchGstInvalid:
5429 atTests.extend([
5430 [ tdTestCopyFromFile(sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, sScratchGstInvalid),
5431 sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
5432 [ tdTestCopyFromDir( sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, sScratchGstInvalid),
5433 sDst = os.path.join(sScratchHst, 'somedir')), tdTestResultFailure() ],
5434 ]);
5435
5436 #
5437 # Single file copying.
5438 #
5439 atTests.extend([
5440 # Should succeed, as the file isn't there yet on the destination.
5441 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'copyfile1')), tdTestResultSuccess() ],
5442 # Overwrite the existing file.
5443 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'copyfile1')), tdTestResultSuccess() ],
5444 # Same file, but with a different name on the destination.
5445 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'copyfile2')), tdTestResultSuccess() ],
5446 ]);
5447
5448 if self.oTstDrv.fpApiVer > 5.2: # Copying files into directories via Main is supported only 6.0 and later.
5449 # Copy into a directory.
5450 atTests.extend([
5451 # This should fail, as sScratchHst exists and is a directory.
5452 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = sScratchHst), tdTestResultFailure() ],
5453 # Same existing host directory, but this time with a trailing slash.
5454 # This should succeed, as the file isn't there yet on the destination.
5455 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = sScratchHst + os.path.sep), tdTestResultSuccess() ],
5456 # Overwrite the existing file.
5457 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = sScratchHst + os.path.sep), tdTestResultSuccess() ],
5458 ]);
5459
5460 #
5461 # Directory handling.
5462 #
5463 if self.oTstDrv.fpApiVer > 5.2: # Copying directories via Main is supported only in versions > 5.2.
5464 atTests.extend([
5465 # Without a trailing slash added to the destination this should fail,
5466 # as the destination directory already exist.
5467 [ tdTestCopyFromDir(sSrc = oEmptyDirGst.sPath, sDst = sScratchDstDir1Hst), tdTestResultFailure() ],
5468 # Same existing host directory, but this time with DirectoryCopyFlag_CopyIntoExisting set.
5469 # This should copy the contents of oEmptyDirGst to sScratchDstDir1Hst (empty, but anyway).
5470 [ tdTestCopyFromDir(sSrc = oEmptyDirGst.sPath, sDst = sScratchDstDir1Hst,
5471 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5472 # Try again.
5473 [ tdTestCopyFromDir(sSrc = oEmptyDirGst.sPath, sDst = sScratchDstDir1Hst,
5474 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5475 # With a trailing slash added to the destination, copy the empty guest directory
5476 # (should end up as sScratchHst/empty):
5477 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir2Hst + os.path.sep), tdTestResultSuccess() ],
5478 # Repeat -- this time it should fail, as the destination directory already exists (and
5479 # DirectoryCopyFlag_CopyIntoExisting is not specified):
5480 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir2Hst + os.path.sep), tdTestResultFailure() ],
5481 # Add the DirectoryCopyFlag_CopyIntoExisting flag being set and it should work (again).
5482 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir2Hst + os.path.sep,
5483 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5484 # Copy with a different destination name just for the heck of it:
5485 [ tdTestCopyFromDir(sSrc = oEmptyDirGst.sPath, sDst = os.path.join(sScratchDstDir2Hst, 'empty2'),
5486 fIntoDst = True),
5487 tdTestResultSuccess() ],
5488 ]);
5489 atTests.extend([
5490 # Now the same using a directory with files in it:
5491 [ tdTestCopyFromDir(oSrc = oNonEmptyDirGst, sDst = sScratchDstDir3Hst + os.path.sep), tdTestResultSuccess() ],
5492 # Again.
5493 [ tdTestCopyFromDir(oSrc = oNonEmptyDirGst, sDst = sScratchDstDir3Hst, fIntoDst = True,
5494 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5495 ]);
5496 atTests.extend([
5497 # Copy the entire test tree:
5498 [ tdTestCopyFromDir(oSrc = oTreeDirGst, sDst = sScratchDstDir4Hst + os.path.sep), tdTestResultSuccess() ],
5499 # Again, should fail this time.
5500 [ tdTestCopyFromDir(oSrc = oTreeDirGst, sDst = sScratchDstDir4Hst + os.path.sep), tdTestResultFailure() ],
5501 # Works again, as DirectoryCopyFlag_CopyIntoExisting is specified.
5502 [ tdTestCopyFromDir(oSrc = oTreeDirGst, sDst = sScratchDstDir4Hst + os.path.sep,
5503 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
5504 ]);
5505 #
5506 # Dotdot path handling.
5507 #
5508 if self.oTstDrv.fpApiVer >= 6.1:
5509 atTests.extend([
5510 # Test if copying stuff from a guest dotdot ".." directory works.
5511 [ tdTestCopyFromDir(sSrc = sScratchDotDotDirGst, sDst = sScratchDstDir1Hst + os.path.sep,
5512 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]),
5513 tdTestResultFailure() ],
5514 # Test if copying stuff from the guest to a host's dotdot ".." directory works.
5515 # That should fail on destinations.
5516 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = sScratchDotDotDirHst), tdTestResultFailure() ],
5517 ]);
5518
5519 reporter.log2('Executing tests ...');
5520
5521 #
5522 # Execute the tests.
5523 #
5524 fRc = True;
5525 for (i, tTest) in enumerate(atTests):
5526 oCurTest = tTest[0]
5527 oCurRes = tTest[1] # type: tdTestResult
5528 if isinstance(oCurTest, tdTestCopyFrom):
5529 reporter.log('Testing #%d, %s: sSrc="%s", sDst="%s", afFlags="%s" ...'
5530 % (i, "directory" if isinstance(oCurTest, tdTestCopyFromDir) else "file",
5531 limitString(oCurTest.sSrc), limitString(oCurTest.sDst), oCurTest.afFlags,));
5532 else:
5533 reporter.log('Testing #%d, tdTestRemoveHostDir "%s" ...' % (i, oCurTest.sDir,));
5534 if isinstance(oCurTest, tdTestCopyFromDir) and self.oTstDrv.fpApiVer < 6.0:
5535 reporter.log('Skipping directoryCopyFromGuest test, not implemented in %s' % (self.oTstDrv.fpApiVer,));
5536 continue;
5537
5538 if isinstance(oCurTest, tdTestRemoveHostDir):
5539 fRc = oCurTest.execute(self.oTstDrv, oSession, oTxsSession, oTestVm, 'testing #%d' % (i,));
5540 else:
5541 fRc = oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
5542 if not fRc:
5543 break;
5544 fRc2, oCurGuestSession = oCurTest.createSession('testGuestCtrlCopyFrom: Test #%d' % (i,));
5545 if fRc2 is not True:
5546 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
5547 break;
5548
5549 if isinstance(oCurTest, tdTestCopyFromFile):
5550 fRc2 = self.gctrlCopyFileFrom(oCurGuestSession, oCurTest, oCurRes.fRc);
5551 else:
5552 fRc2 = self.gctrlCopyDirFrom(oCurGuestSession, oCurTest, oCurRes.fRc);
5553
5554 if fRc2 != oCurRes.fRc:
5555 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc));
5556
5557 fRc = oCurTest.closeSession() and fRc;
5558
5559 return (fRc, oTxsSession);
5560
5561 def testGuestCtrlUpdateAdditions(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
5562 """
5563 Tests updating the Guest Additions inside the guest.
5564
5565 """
5566
5567 ## @todo currently disabled everywhere.
5568 if self.oTstDrv.fpApiVer < 100.0:
5569 reporter.log("Skipping updating GAs everywhere for now...");
5570 return None;
5571
5572 # Skip test for updating Guest Additions if we run on a too old (Windows) guest.
5573 ##
5574 ## @todo make it work everywhere!
5575 ##
5576 if oTestVm.sKind in ('WindowsNT4', 'Windows2000', 'WindowsXP', 'Windows2003'):
5577 reporter.log("Skipping updating GAs on old windows vm (sKind=%s)" % (oTestVm.sKind,));
5578 return (None, oTxsSession);
5579 if oTestVm.isOS2():
5580 reporter.log("Skipping updating GAs on OS/2 guest");
5581 return (None, oTxsSession);
5582
5583 sVBoxValidationKitIso = self.oTstDrv.sVBoxValidationKitIso;
5584 if not os.path.isfile(sVBoxValidationKitIso):
5585 return reporter.log('Validation Kit .ISO not found at "%s"' % (sVBoxValidationKitIso,));
5586
5587 sScratch = os.path.join(self.oTstDrv.sScratchPath, "testGctrlUpdateAdditions");
5588 try:
5589 os.makedirs(sScratch);
5590 except OSError as e:
5591 if e.errno != errno.EEXIST:
5592 return reporter.error('Failed: Unable to create scratch directory \"%s\"' % (sScratch,));
5593 reporter.log('Scratch path is: %s' % (sScratch,));
5594
5595 atTests = [];
5596 if oTestVm.isWindows():
5597 atTests.extend([
5598 # Source is missing.
5599 [ tdTestUpdateAdditions(sSrc = ''), tdTestResultFailure() ],
5600
5601 # Wrong flags.
5602 [ tdTestUpdateAdditions(sSrc = self.oTstDrv.getGuestAdditionsIso(),
5603 afFlags = [ 1234 ]), tdTestResultFailure() ],
5604
5605 # Non-existing .ISO.
5606 [ tdTestUpdateAdditions(sSrc = "non-existing.iso"), tdTestResultFailure() ],
5607
5608 # Wrong .ISO.
5609 [ tdTestUpdateAdditions(sSrc = sVBoxValidationKitIso), tdTestResultFailure() ],
5610
5611 # The real thing.
5612 [ tdTestUpdateAdditions(sSrc = self.oTstDrv.getGuestAdditionsIso()),
5613 tdTestResultSuccess() ],
5614 # Test the (optional) installer arguments. This will extract the
5615 # installer into our guest's scratch directory.
5616 [ tdTestUpdateAdditions(sSrc = self.oTstDrv.getGuestAdditionsIso(),
5617 asArgs = [ '/extract', '/D=' + sScratch ]),
5618 tdTestResultSuccess() ]
5619 # Some debg ISO. Only enable locally.
5620 #[ tdTestUpdateAdditions(
5621 # sSrc = "V:\\Downloads\\VBoxGuestAdditions-r80354.iso"),
5622 # tdTestResultSuccess() ]
5623 ]);
5624 else:
5625 reporter.log('No OS-specific tests for non-Windows yet!');
5626
5627 fRc = True;
5628 for (i, tTest) in enumerate(atTests):
5629 oCurTest = tTest[0] # type: tdTestUpdateAdditions
5630 oCurRes = tTest[1] # type: tdTestResult
5631 reporter.log('Testing #%d, sSrc="%s", afFlags="%s" ...' % (i, oCurTest.sSrc, oCurTest.afFlags,));
5632
5633 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
5634 if not fRc:
5635 break;
5636 fRc, _ = oCurTest.createSession('Test #%d' % (i,));
5637 if fRc is not True:
5638 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
5639 break;
5640
5641 try:
5642 oCurProgress = oCurTest.oGuest.updateGuestAdditions(oCurTest.sSrc, oCurTest.asArgs, oCurTest.afFlags);
5643 except:
5644 reporter.maybeErrXcpt(oCurRes.fRc, 'Updating Guest Additions exception for sSrc="%s", afFlags="%s":'
5645 % (oCurTest.sSrc, oCurTest.afFlags,));
5646 fRc = False;
5647 else:
5648 if oCurProgress is not None:
5649 oWrapperProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr,
5650 self.oTstDrv, "gctrlUpGA");
5651 oWrapperProgress.wait();
5652 if not oWrapperProgress.isSuccess():
5653 oWrapperProgress.logResult(fIgnoreErrors = not oCurRes.fRc);
5654 fRc = False;
5655 else:
5656 fRc = reporter.error('No progress object returned');
5657
5658 oCurTest.closeSession();
5659 if fRc is oCurRes.fRc:
5660 if fRc:
5661 ## @todo Verify if Guest Additions were really updated (build, revision, ...).
5662 ## @todo r=bird: Not possible since you're installing the same GAs as before...
5663 ## Maybe check creation dates on certain .sys/.dll/.exe files?
5664 pass;
5665 else:
5666 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc, oCurRes.fRc));
5667 break;
5668
5669 return (fRc, oTxsSession);
5670
5671 def checkScreenShot(self, iWidth, iHeight, aRGBData): # pylint: disable=unused-argument
5672 """
5673 TBD: Implement basic validation of the captured screenshot content.
5674 """
5675 cPixels = iHeight * iWidth
5676
5677 if cPixels == 0:
5678 reporter.logXcpt("Empty screenshot");
5679 return False
5680
5681 # The simple algoritm below assumes that Windows OS desktop consists of a pixels that
5682 # are not too dark or bright but usually of blue tint.
5683 cDesktopPixels = 0
5684 cDesktopPixelsBlue = 0
5685 iThreshold = 20
5686 for i in range(0, cPixels, 4) :
5687 if sys.version_info[0] >= 3:
5688 iRed = aRGBData[i];
5689 iGreen = aRGBData[i + 1];
5690 iBlue = aRGBData[i + 2];
5691 else: # Python 2.7 treats a pixel data returned by takeScreenShotToArray as a string
5692 iRed = ord(aRGBData[i])
5693 iGreen = ord(aRGBData[i + 1])
5694 iBlue = ord(aRGBData[i + 2])
5695
5696 iBright = (3 * iRed + 6 * iGreen + iBlue) / 10
5697 if iThreshold < iBright < 255 - iThreshold :
5698 cDesktopPixels += 1;
5699 cDesktopPixelsBlue += int(iBlue > iRed and iBlue > iGreen);
5700
5701 fpRatioDesktop = float(cDesktopPixels) / float(cPixels);
5702 reporter.log2('Ratio of not too dark or bright pixels %.2f' % (fpRatioDesktop));
5703
5704 if fpRatioDesktop > 0.1:
5705 fpRatioBlue = float(cDesktopPixelsBlue) / float(cDesktopPixels);
5706 reporter.log2('Ratio of blue pixels %.2f ' % (fpRatioBlue));
5707 if fpRatioBlue > 0.5:
5708 return True
5709
5710 return True # Always return True until the parameters will be calibrated.
5711
5712 def testGuestCtrl3D(self, oSession, oTxsSession, oTestVm): # pylint: disable=unused-argument
5713 """
5714 Tests for VMSVGA device.
5715 """
5716
5717 if oTestVm.sKind not in ('Windows8_64', 'Windows10', 'Windows10_64', 'Windows11_64'):
5718 return (True, oTxsSession);
5719
5720 iScreenId = 0 # TBD: Use a loop to iterate and check all virtual displays
5721 try:
5722 if self.oTstDrv.fpApiVer >= 5.0:
5723 iWidth, iHeight, _, _, _, _ = oSession.o.console.display.getScreenResolution(iScreenId);
5724 else:
5725 iWidth, iHeight, _, _, _ = oSession.o.console.display.getScreenResolution(iScreenId);
5726
5727 aRGBData = oSession.o.console.display.takeScreenShotToArray(iScreenId, iWidth, iHeight,
5728 vboxcon.BitmapFormat_RGBA);
5729 except:
5730 reporter.logXcpt("Unable to take screenshot");
5731 return False
5732
5733 reporter.log2('Got screenshot (%s x %s) having %s bytes' % (iWidth, iHeight, len(aRGBData)));
5734 # @todo r=aeichner Where is this result incorporated in the test result?
5735 # It gets overwritten afterwards without being taken into account
5736 fRc = self.checkScreenShot(iWidth, iHeight, aRGBData);
5737
5738 fRc = fRc and self.oTstDrv.txsRunTest(oTxsSession, 'Checking DX11 feature level', 30 * 1000,
5739 '${CDROM}/${OS/ARCH}/ntDisplay${EXESUFF}', ('ntDisplay', ));
5740 fRc = True; # TBD: Fix for Unattended tests when the ValidationKit.iso is mounted as drive D:
5741 return (fRc, oTxsSession);
5742
5743class tdAddGuestCtrl(vbox.TestDriver): # pylint: disable=too-many-instance-attributes,too-many-public-methods
5744 """
5745 Guest control using VBoxService on the guest.
5746 """
5747
5748 def __init__(self):
5749 vbox.TestDriver.__init__(self);
5750 self.oTestVmSet = self.oTestVmManager.getSmokeVmSet('nat');
5751 self.asRsrcs = None;
5752 self.fQuick = False; # Don't skip lengthly tests by default.
5753 self.addSubTestDriver(SubTstDrvAddGuestCtrl(self));
5754
5755 #
5756 # Overridden methods.
5757 #
5758 def showUsage(self):
5759 """
5760 Shows the testdriver usage.
5761 """
5762 rc = vbox.TestDriver.showUsage(self);
5763 reporter.log('');
5764 reporter.log('tdAddGuestCtrl Options:');
5765 reporter.log(' --quick');
5766 reporter.log(' Same as --virt-modes hwvirt --cpu-counts 1.');
5767 return rc;
5768
5769 def parseOption(self, asArgs, iArg): # pylint: disable=too-many-branches,too-many-statements
5770 """
5771 Parses the testdriver arguments from the command line.
5772 """
5773 if asArgs[iArg] == '--quick':
5774 self.parseOption(['--virt-modes', 'hwvirt'], 0);
5775 self.parseOption(['--cpu-counts', '1'], 0);
5776 self.fQuick = True;
5777 else:
5778 return vbox.TestDriver.parseOption(self, asArgs, iArg);
5779 return iArg + 1;
5780
5781 def actionConfig(self):
5782 if not self.importVBoxApi(): # So we can use the constant below.
5783 return False;
5784
5785 eNic0AttachType = vboxcon.NetworkAttachmentType_NAT;
5786 sGaIso = self.getGuestAdditionsIso();
5787 return self.oTestVmSet.actionConfig(self, eNic0AttachType = eNic0AttachType, sDvdImage = sGaIso);
5788
5789 def actionExecute(self):
5790 return self.oTestVmSet.actionExecute(self, self.testOneCfg);
5791
5792 #
5793 # Test execution helpers.
5794 #
5795 def testOneCfg(self, oVM, oTestVm): # pylint: disable=too-many-statements
5796 """
5797 Runs the specified VM thru the tests.
5798
5799 Returns a success indicator on the general test execution. This is not
5800 the actual test result.
5801 """
5802
5803 self.logVmInfo(oVM);
5804
5805 fRc = True;
5806 oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(oTestVm.sVmName, fCdWait = False);
5807 reporter.log("TxsSession: %s" % (oTxsSession,));
5808 if oSession is not None:
5809 fRc, oTxsSession = self.aoSubTstDrvs[0].testIt(oTestVm, oSession, oTxsSession);
5810 self.terminateVmBySession(oSession);
5811 else:
5812 fRc = False;
5813 return fRc;
5814
5815 def onExit(self, iRc):
5816 return vbox.TestDriver.onExit(self, iRc);
5817
5818 def gctrlReportError(self, progress):
5819 """
5820 Helper function to report an error of a
5821 given progress object.
5822 """
5823 if progress is None:
5824 reporter.log('No progress object to print error for');
5825 else:
5826 errInfo = progress.errorInfo;
5827 if errInfo:
5828 reporter.log('%s' % (errInfo.text,));
5829 return False;
5830
5831 def gctrlGetRemainingTime(self, msTimeout, msStart):
5832 """
5833 Helper function to return the remaining time (in ms)
5834 based from a timeout value and the start time (both in ms).
5835 """
5836 if msTimeout == 0:
5837 return 0xFFFFFFFE; # Wait forever.
5838 msElapsed = base.timestampMilli() - msStart;
5839 if msElapsed > msTimeout:
5840 return 0; # No time left.
5841 return msTimeout - msElapsed;
5842
5843 def testGuestCtrlManual(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals,too-many-statements,unused-argument,unused-variable
5844 """
5845 For manually testing certain bits.
5846 """
5847
5848 reporter.log('Manual testing ...');
5849 fRc = True;
5850
5851 sUser = 'Administrator';
5852 sPassword = 'password';
5853
5854 oGuest = oSession.o.console.guest;
5855 oGuestSession = oGuest.createSession(sUser,
5856 sPassword,
5857 "", "Manual Test");
5858
5859 aWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
5860 _ = oGuestSession.waitForArray(aWaitFor, 30 * 1000);
5861
5862 #sCmd = self.getGuestSystemShell(oTestVm);
5863 #asArgs = [ sCmd, '/C', 'dir', '/S', 'c:\\windows' ];
5864 #aEnv = [];
5865 #afFlags = [];
5866
5867 # Fix this once being used (again).
5868 #for _ in xrange(100):
5869 # oProc = self.processCreateWrapper(oGuestSession, sCmd, asArgs if self.fpApiVer >= 5.0 else asArgs[1:],
5870 # "", # Working directory.
5871 # aEnv, afFlags, 30 * 1000);
5872 #
5873 # aWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate ];
5874 # _ = oProc.waitForArray(aWaitFor, 30 * 1000);
5875
5876 oGuestSession.close();
5877 oGuestSession = None;
5878
5879 time.sleep(5);
5880
5881 oSession.o.console.PowerDown();
5882
5883 return (fRc, oTxsSession);
5884
5885if __name__ == '__main__':
5886 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