VirtualBox

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

Last change on this file since 84179 was 84179, checked in by vboxsync, 5 years ago

Validation Kit/tdAddGuestCtrl: Logging.

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