VirtualBox

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

Last change on this file since 79452 was 79452, checked in by vboxsync, 6 years ago

ValKit/UnattendedInst1,++: Adjustments for ubuntu. bugref:9151

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 236.8 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-2019 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: 79452 $"
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
1338
1339class SubTstDrvAddGuestCtrl(base.SubTestDriverBase):
1340 """
1341 Sub-test driver for executing guest control (VBoxService, IGuest) tests.
1342 """
1343
1344 def __init__(self, oTstDrv):
1345 base.SubTestDriverBase.__init__(self, oTstDrv, 'add-guest-ctrl', 'Guest Control');
1346
1347 ## @todo base.TestBase.
1348 self.asTestsDef = [
1349 'session_basic', 'session_env', 'session_file_ref', 'session_dir_ref', 'session_proc_ref', 'session_reboot',
1350 'exec_basic', 'exec_timeout',
1351 'dir_create', 'dir_create_temp', 'dir_read',
1352 'file_open', 'file_remove', 'file_stat', 'file_read', 'file_write',
1353 'copy_to', 'copy_from',
1354 'update_additions'
1355 ];
1356 self.asTests = self.asTestsDef;
1357 self.fSkipKnownBugs = False;
1358 self.oTestFiles = None # type: vboxtestfileset.TestFileSet
1359
1360 def parseOption(self, asArgs, iArg): # pylint: disable=too-many-branches,too-many-statements
1361 if asArgs[iArg] == '--add-guest-ctrl-tests':
1362 iArg += 1;
1363 iNext = self.oTstDrv.requireMoreArgs(1, asArgs, iArg);
1364 if asArgs[iArg] == 'all': # Nice for debugging scripts.
1365 self.asTests = self.asTestsDef;
1366 else:
1367 self.asTests = asArgs[iArg].split(':');
1368 for s in self.asTests:
1369 if s not in self.asTestsDef:
1370 raise base.InvalidOption('The "--add-guest-ctrl-tests" value "%s" is not valid; valid values are: %s'
1371 % (s, ' '.join(self.asTestsDef)));
1372 return iNext;
1373 if asArgs[iArg] == '--add-guest-ctrl-skip-known-bugs':
1374 self.fSkipKnownBugs = True;
1375 return iArg + 1;
1376 if asArgs[iArg] == '--no-add-guest-ctrl-skip-known-bugs':
1377 self.fSkipKnownBugs = False;
1378 return iArg + 1;
1379 return iArg;
1380
1381 def showUsage(self):
1382 base.SubTestDriverBase.showUsage(self);
1383 reporter.log(' --add-guest-ctrl-tests <s1[:s2[:]]>');
1384 reporter.log(' Default: %s (all)' % (':'.join(self.asTestsDef)));
1385 reporter.log(' --add-guest-ctrl-skip-known-bugs');
1386 reporter.log(' Skips known bugs. Default: --no-add-guest-ctrl-skip-known-bugs');
1387 return True;
1388
1389 def testIt(self, oTestVm, oSession, oTxsSession):
1390 """
1391 Executes the test.
1392
1393 Returns fRc, oTxsSession. The latter may have changed.
1394 """
1395 reporter.log("Active tests: %s" % (self.asTests,));
1396
1397 # The tests. Must-succeed tests should be first.
1398 atTests = [
1399 ( True, self.prepareGuestForTesting, None, 'Preparations',),
1400 ( True, self.testGuestCtrlSession, 'session_basic', 'Session Basics',),
1401 ( True, self.testGuestCtrlExec, 'exec_basic', 'Execution',),
1402 ( False, self.testGuestCtrlExecTimeout, 'exec_timeout', 'Execution Timeouts',),
1403 ( False, self.testGuestCtrlSessionEnvironment, 'session_env', 'Session Environment',),
1404 ( False, self.testGuestCtrlSessionFileRefs, 'session_file_ref', 'Session File References',),
1405 #( False, self.testGuestCtrlSessionDirRefs, 'session_dir_ref', 'Session Directory References',),
1406 ( False, self.testGuestCtrlSessionProcRefs, 'session_proc_ref', 'Session Process References',),
1407 ( False, self.testGuestCtrlDirCreate, 'dir_create', 'Creating directories',),
1408 ( False, self.testGuestCtrlDirCreateTemp, 'dir_create_temp', 'Creating temporary directories',),
1409 ( False, self.testGuestCtrlDirRead, 'dir_read', 'Reading directories',),
1410 ( False, self.testGuestCtrlCopyTo, 'copy_to', 'Copy to guest',),
1411 ( False, self.testGuestCtrlCopyFrom, 'copy_from', 'Copy from guest',),
1412 ( False, self.testGuestCtrlFileStat, 'file_stat', 'Querying file information (stat)',),
1413 ( False, self.testGuestCtrlFileOpen, 'file_open', 'File open',),
1414 ( False, self.testGuestCtrlFileRead, 'file_read', 'File read',),
1415 ( False, self.testGuestCtrlFileWrite, 'file_write', 'File write',),
1416 ( False, self.testGuestCtrlFileRemove, 'file_remove', 'Removing files',), # Destroys prepped files.
1417 ( False, self.testGuestCtrlSessionReboot, 'session_reboot', 'Session w/ Guest Reboot',), # May zap /tmp.
1418 ( False, self.testGuestCtrlUpdateAdditions, 'update_additions', 'Updating Guest Additions',),
1419 ];
1420
1421 fRc = True;
1422 for fMustSucceed, fnHandler, sShortNm, sTestNm in atTests:
1423 reporter.testStart(sTestNm);
1424
1425 if sShortNm is None or sShortNm in self.asTests:
1426 # Returns (fRc, oTxsSession, oSession) - but only the first one is mandatory.
1427 aoResult = fnHandler(oSession, oTxsSession, oTestVm);
1428 if aoResult is None or isinstance(aoResult, bool):
1429 fRcTest = aoResult;
1430 else:
1431 fRcTest = aoResult[0];
1432 if len(aoResult) > 1:
1433 oTxsSession = aoResult[1];
1434 if len(aoResult) > 2:
1435 oSession = aoResult[2];
1436 assert len(aoResult) == 3;
1437 else:
1438 fRcTest = None;
1439
1440 if fRcTest is False and reporter.testErrorCount() == 0:
1441 fRcTest = reporter.error('Buggy test! Returned False w/o logging the error!');
1442 if reporter.testDone(fRcTest is None)[1] != 0:
1443 fRcTest = False;
1444 fRc = False;
1445
1446 # Stop execution if this is a must-succeed test and it failed.
1447 if fRcTest is False and fMustSucceed is True:
1448 reporter.log('Skipping any remaining tests since the previous one failed.');
1449 break;
1450
1451 return (fRc, oTxsSession);
1452
1453 #
1454 # Guest locations.
1455 #
1456
1457 @staticmethod
1458 def getGuestTempDir(oTestVm):
1459 """
1460 Helper for finding a temporary directory in the test VM.
1461
1462 Note! It may be necessary to create it!
1463 """
1464 if oTestVm.isWindows():
1465 return "C:\\Temp";
1466 if oTestVm.isOS2():
1467 return "C:\\Temp";
1468 return '/var/tmp';
1469
1470 @staticmethod
1471 def getGuestSystemDir(oTestVm):
1472 """
1473 Helper for finding a system directory in the test VM that we can play around with.
1474
1475 On Windows this is always the System32 directory, so this function can be used as
1476 basis for locating other files in or under that directory.
1477 """
1478 if oTestVm.isWindows():
1479 if oTestVm.sKind in ['WindowsNT4', 'WindowsNT3x',]:
1480 return 'C:\\Winnt\\System32';
1481 return 'C:\\Windows\\System32';
1482 if oTestVm.isOS2():
1483 return 'C:\\OS2\\DLL';
1484 return "/bin";
1485
1486 @staticmethod
1487 def getGuestSystemShell(oTestVm):
1488 """
1489 Helper for finding the default system shell in the test VM.
1490 """
1491 if oTestVm.isWindows():
1492 return SubTstDrvAddGuestCtrl.getGuestSystemDir(oTestVm) + '\\cmd.exe';
1493 if oTestVm.isOS2():
1494 return SubTstDrvAddGuestCtrl.getGuestSystemDir(oTestVm) + '\\..\\CMD.EXE';
1495 return "/bin/sh";
1496
1497 @staticmethod
1498 def getGuestSystemFileForReading(oTestVm):
1499 """
1500 Helper for finding a file in the test VM that we can read.
1501 """
1502 if oTestVm.isWindows():
1503 return SubTstDrvAddGuestCtrl.getGuestSystemDir(oTestVm) + '\\ntdll.dll';
1504 if oTestVm.isOS2():
1505 return SubTstDrvAddGuestCtrl.getGuestSystemDir(oTestVm) + '\\DOSCALL1.DLL';
1506 return "/bin/sh";
1507
1508 #
1509 # Guest test files.
1510 #
1511
1512 def prepareGuestForTesting(self, oSession, oTxsSession, oTestVm):
1513 """
1514 Prepares the VM for testing, uploading a bunch of files and stuff via TXS.
1515 Returns success indicator.
1516 """
1517 _ = oSession;
1518
1519 #
1520 # Make sure the temporary directory exists.
1521 #
1522 for sDir in [self.getGuestTempDir(oTestVm), ]:
1523 if oTxsSession.syncMkDirPath(sDir, 0o777) is not True:
1524 return reporter.error('Failed to create directory "%s"!' % (sDir,));
1525
1526 #
1527 # Generate and upload some random files and dirs to the guest.
1528 # Note! Make sure we don't run into too-long-path issues when using
1529 # the test files on the host if.
1530 #
1531 cchGst = len(self.getGuestTempDir(oTestVm)) + 1 + len('addgst-1') + 1;
1532 cchHst = len(self.oTstDrv.sScratchPath) + 1 + len('cp2/addgst-1') + 1;
1533 cchMaxPath = 230;
1534 if cchHst > cchGst:
1535 cchMaxPath -= cchHst - cchGst;
1536 reporter.log('cchMaxPath=%s (cchHst=%s, cchGst=%s)' % (cchMaxPath, cchHst, cchGst,));
1537 self.oTestFiles = vboxtestfileset.TestFileSet(oTestVm,
1538 self.getGuestTempDir(oTestVm), 'addgst-1',
1539 cchMaxPath = cchMaxPath);
1540 return self.oTestFiles.upload(oTxsSession, self.oTstDrv);
1541
1542
1543 #
1544 # gctrlXxxx stuff.
1545 #
1546
1547 def gctrlCopyFileFrom(self, oGuestSession, oTest, fExpected):
1548 """
1549 Helper function to copy a single file from the guest to the host.
1550 """
1551 #
1552 # Do the copying.
1553 #
1554 reporter.log2('Copying guest file "%s" to host "%s"' % (oTest.sSrc, oTest.sDst));
1555 try:
1556 if self.oTstDrv.fpApiVer >= 5.0:
1557 oCurProgress = oGuestSession.fileCopyFromGuest(oTest.sSrc, oTest.sDst, oTest.afFlags);
1558 else:
1559 oCurProgress = oGuestSession.copyFrom(oTest.sSrc, oTest.sDst, oTest.afFlags);
1560 except:
1561 reporter.maybeErrXcpt(fExpected, 'Copy from exception for sSrc="%s", sDst="%s":' % (oTest.sSrc, oTest.sDst,));
1562 return False;
1563 if oCurProgress is None:
1564 return reporter.error('No progress object returned');
1565 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlFileCopyFrom");
1566 oProgress.wait();
1567 if not oProgress.isSuccess():
1568 oProgress.logResult(fIgnoreErrors = not fExpected);
1569 return False;
1570
1571 #
1572 # Check the result if we can.
1573 #
1574 if oTest.oSrc:
1575 assert isinstance(oTest.oSrc, testfileset.TestFile);
1576 sDst = oTest.sDst;
1577 if os.path.isdir(sDst):
1578 sDst = os.path.join(sDst, oTest.oSrc.sName);
1579 try:
1580 oFile = open(sDst, 'rb');
1581 except:
1582 return reporter.errorXcpt('open(%s) failed during verfication' % (sDst,));
1583 fEqual = oTest.oSrc.equalFile(oFile);
1584 oFile.close();
1585 if not fEqual:
1586 return reporter.error('Content differs for "%s"' % (sDst,));
1587
1588 return True;
1589
1590 def __compareTestDir(self, oDir, sHostPath): # type: (testfileset.TestDir, str) -> bool
1591 """
1592 Recursively compare the content of oDir and sHostPath.
1593
1594 Returns True on success, False + error logging on failure.
1595
1596 Note! This ASSUMES that nothing else was copied to sHostPath!
1597 """
1598 #
1599 # First check out all the entries and files in the directory.
1600 #
1601 dLeftUpper = dict(oDir.dChildrenUpper);
1602 try:
1603 asEntries = os.listdir(sHostPath);
1604 except:
1605 return reporter.errorXcpt('os.listdir(%s) failed' % (sHostPath,));
1606
1607 fRc = True;
1608 for sEntry in asEntries:
1609 sEntryUpper = sEntry.upper();
1610 if sEntryUpper not in dLeftUpper:
1611 fRc = reporter.error('Unexpected entry "%s" in "%s"' % (sEntry, sHostPath,));
1612 else:
1613 oFsObj = dLeftUpper[sEntryUpper];
1614 del dLeftUpper[sEntryUpper];
1615
1616 if isinstance(oFsObj, testfileset.TestFile):
1617 sFilePath = os.path.join(sHostPath, oFsObj.sName);
1618 try:
1619 oFile = open(sFilePath, 'rb');
1620 except:
1621 fRc = reporter.errorXcpt('open(%s) failed during verfication' % (sFilePath,));
1622 else:
1623 fEqual = oFsObj.equalFile(oFile);
1624 oFile.close();
1625 if not fEqual:
1626 fRc = reporter.error('Content differs for "%s"' % (sFilePath,));
1627
1628 # List missing entries:
1629 for sKey in dLeftUpper:
1630 oEntry = dLeftUpper[sKey];
1631 fRc = reporter.error('%s: Missing %s "%s" (src path: %s)'
1632 % (sHostPath, oEntry.sName,
1633 'file' if isinstance(oEntry, testfileset.TestFile) else 'directory', oEntry.sPath));
1634
1635 #
1636 # Recurse into subdirectories.
1637 #
1638 for oFsObj in oDir.aoChildren:
1639 if isinstance(oFsObj, testfileset.TestDir):
1640 fRc = self.__compareTestDir(oFsObj, os.path.join(sHostPath, oFsObj.sName)) and fRc;
1641 return fRc;
1642
1643 def gctrlCopyDirFrom(self, oGuestSession, oTest, fExpected):
1644 """
1645 Helper function to copy a directory from the guest to the host.
1646 """
1647 #
1648 # Do the copying.
1649 #
1650 reporter.log2('Copying guest dir "%s" to host "%s"' % (oTest.sSrc, oTest.sDst));
1651 try:
1652 oCurProgress = oGuestSession.directoryCopyFromGuest(oTest.sSrc, oTest.sDst, oTest.afFlags);
1653 except:
1654 reporter.maybeErrXcpt(fExpected, 'Copy dir from exception for sSrc="%s", sDst="%s":' % (oTest.sSrc, oTest.sDst,));
1655 return False;
1656 if oCurProgress is None:
1657 return reporter.error('No progress object returned');
1658
1659 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlDirCopyFrom");
1660 oProgress.wait();
1661 if not oProgress.isSuccess():
1662 oProgress.logResult(fIgnoreErrors = not fExpected);
1663 return False;
1664
1665 #
1666 # Check the result if we can.
1667 #
1668 if oTest.oSrc:
1669 assert isinstance(oTest.oSrc, testfileset.TestDir);
1670 sDst = oTest.sDst;
1671 if oTest.fIntoDst:
1672 return self.__compareTestDir(oTest.oSrc, os.path.join(sDst, oTest.oSrc.sName));
1673 oDummy = testfileset.TestDir(None, 'dummy');
1674 oDummy.aoChildren = [oTest.oSrc,]
1675 oDummy.dChildrenUpper = { oTest.oSrc.sName.upper(): oTest.oSrc, };
1676 return self.__compareTestDir(oDummy, sDst);
1677 return True;
1678
1679 def gctrlCopyFileTo(self, oGuestSession, sSrc, sDst, afFlags, fIsError):
1680 """
1681 Helper function to copy a single file from the host to the guest.
1682 """
1683 reporter.log2('Copying host file "%s" to guest "%s" (flags %s)' % (sSrc, sDst, afFlags));
1684 try:
1685 if self.oTstDrv.fpApiVer >= 5.0:
1686 oCurProgress = oGuestSession.fileCopyToGuest(sSrc, sDst, afFlags);
1687 else:
1688 oCurProgress = oGuestSession.copyTo(sSrc, sDst, afFlags);
1689 except:
1690 reporter.maybeErrXcpt(fIsError, 'sSrc=%s sDst=%s' % (sSrc, sDst,));
1691 return False;
1692
1693 if oCurProgress is None:
1694 return reporter.error('No progress object returned');
1695 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlCopyFileTo");
1696
1697 try:
1698 oProgress.wait();
1699 if not oProgress.isSuccess():
1700 oProgress.logResult(fIgnoreErrors = not fIsError);
1701 return False;
1702 except:
1703 reporter.maybeErrXcpt(fIsError, 'Wait exception for sSrc="%s", sDst="%s":' % (sSrc, sDst));
1704 return False;
1705 return True;
1706
1707 def gctrlCopyDirTo(self, oGuestSession, sSrc, sDst, afFlags, fIsError):
1708 """
1709 Helper function to copy a directory tree from the host to the guest.
1710 """
1711 reporter.log2('Copying host directory "%s" to guest "%s" (flags %s)' % (sSrc, sDst, afFlags));
1712 try:
1713 oCurProgress = oGuestSession.directoryCopyToGuest(sSrc, sDst, afFlags);
1714 except:
1715 reporter.maybeErrXcpt(fIsError, 'sSrc=%s sDst=%s' % (sSrc, sDst,));
1716 return False;
1717
1718 if oCurProgress is None:
1719 return reporter.error('No progress object returned');
1720 oProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv, "gctrlCopyFileTo");
1721
1722 try:
1723 oProgress.wait();
1724 if not oProgress.isSuccess():
1725 oProgress.logResult(fIgnoreErrors = not fIsError);
1726 return False;
1727 except:
1728 reporter.maybeErrXcpt(fIsError, 'Wait exception for sSrc="%s", sDst="%s":' % (sSrc, sDst));
1729 return False;
1730 return True;
1731
1732 def gctrlCreateDir(self, oTest, oRes, oGuestSession):
1733 """
1734 Helper function to create a guest directory specified in the current test.
1735 """
1736 reporter.log2('Creating directory "%s"' % (oTest.sDirectory,));
1737 try:
1738 oGuestSession.directoryCreate(oTest.sDirectory, oTest.fMode, oTest.afFlags);
1739 except:
1740 reporter.maybeErrXcpt(oRes.fRc, 'Failed to create "%s" fMode=%o afFlags=%s'
1741 % (oTest.sDirectory, oTest.fMode, oTest.afFlags,));
1742 return not oRes.fRc;
1743 if oRes.fRc is not True:
1744 return reporter.error('Did not expect to create directory "%s"!' % (oTest.sDirectory,));
1745
1746 # Check if the directory now exists.
1747 try:
1748 if self.oTstDrv.fpApiVer >= 5.0:
1749 fDirExists = oGuestSession.directoryExists(oTest.sDirectory, False);
1750 else:
1751 fDirExists = oGuestSession.directoryExists(oTest.sDirectory);
1752 except:
1753 return reporter.errorXcpt('directoryExists failed on "%s"!' % (oTest.sDirectory,));
1754 if not fDirExists:
1755 return reporter.errorXcpt('directoryExists returned False on "%s" after directoryCreate succeeded!'
1756 % (oTest.sDirectory,));
1757 return True;
1758
1759 def gctrlReadDirTree(self, oTest, oGuestSession, fIsError, sSubDir = None):
1760 """
1761 Helper function to recursively read a guest directory tree specified in the current test.
1762 """
1763 sDir = oTest.sDirectory;
1764 sFilter = oTest.sFilter;
1765 afFlags = oTest.afFlags;
1766 oTestVm = oTest.oCreds.oTestVm;
1767 sCurDir = oTestVm.pathJoin(sDir, sSubDir) if sSubDir else sDir;
1768
1769 fRc = True; # Be optimistic.
1770 cDirs = 0; # Number of directories read.
1771 cFiles = 0; # Number of files read.
1772 cOthers = 0; # Other files.
1773
1774 ##
1775 ## @todo r=bird: Unlike fileOpen, directoryOpen will not fail if the directory does not exist.
1776 ## This is of course a bug in the implementation, as it is documented to return
1777 ## VBOX_E_OBJECT_NOT_FOUND or VBOX_E_IPRT_ERROR!
1778 ##
1779
1780 # Open the directory:
1781 #reporter.log2('Directory="%s", filter="%s", afFlags="%s"' % (sCurDir, sFilter, afFlags));
1782 try:
1783 oCurDir = oGuestSession.directoryOpen(sCurDir, sFilter, afFlags);
1784 except:
1785 reporter.maybeErrXcpt(fIsError, 'sCurDir=%s sFilter=%s afFlags=%s' % (sCurDir, sFilter, afFlags,))
1786 return (False, 0, 0, 0);
1787
1788 # Read the directory.
1789 while fRc is True:
1790 try:
1791 oFsObjInfo = oCurDir.read();
1792 except Exception as oXcpt:
1793 if vbox.ComError.notEqual(oXcpt, vbox.ComError.VBOX_E_OBJECT_NOT_FOUND):
1794 ##
1795 ## @todo r=bird: Change this to reporter.errorXcpt() once directoryOpen() starts
1796 ## working the way it is documented.
1797 ##
1798 reporter.maybeErrXcpt(fIsError, 'Error reading directory "%s":' % (sCurDir,)); # See above why 'maybe'.
1799 fRc = False;
1800 #else: reporter.log2('\tNo more directory entries for "%s"' % (sCurDir,));
1801 break;
1802
1803 try:
1804 sName = oFsObjInfo.name;
1805 eType = oFsObjInfo.type;
1806 except:
1807 fRc = reporter.errorXcpt();
1808 break;
1809
1810 if sName in ('.', '..', ):
1811 if eType != vboxcon.FsObjType_Directory:
1812 fRc = reporter.error('Wrong type for "%s": %d, expected %d (Directory)'
1813 % (sName, eType, vboxcon.FsObjType_Directory));
1814 elif eType == vboxcon.FsObjType_Directory:
1815 #reporter.log2(' Directory "%s"' % oFsObjInfo.name);
1816 aSubResult = self.gctrlReadDirTree(oTest, oGuestSession, fIsError,
1817 oTestVm.pathJoin(sSubDir, sName) if sSubDir else sName);
1818 fRc = aSubResult[0];
1819 cDirs += aSubResult[1] + 1;
1820 cFiles += aSubResult[2];
1821 cOthers += aSubResult[3];
1822 elif eType is vboxcon.FsObjType_File:
1823 #reporter.log2(' File "%s"' % oFsObjInfo.name);
1824 cFiles += 1;
1825 elif eType is vboxcon.FsObjType_Symlink:
1826 #reporter.log2(' Symlink "%s" -- not tested yet' % oFsObjInfo.name);
1827 cOthers += 1;
1828 elif oTestVm.isWindows() \
1829 or oTestVm.isOS2() \
1830 or eType not in (vboxcon.FsObjType_Fifo, vboxcon.FsObjType_DevChar, vboxcon.FsObjType_DevBlock,
1831 vboxcon.FsObjType_Socket, vboxcon.FsObjType_WhiteOut):
1832 fRc = reporter.error('Directory "%s" contains invalid directory entry "%s" (type %d)' %
1833 (sCurDir, oFsObjInfo.name, oFsObjInfo.type,));
1834 else:
1835 cOthers += 1;
1836
1837 # Close the directory
1838 try:
1839 oCurDir.close();
1840 except:
1841 fRc = reporter.errorXcpt('sCurDir=%s' % (sCurDir));
1842
1843 return (fRc, cDirs, cFiles, cOthers);
1844
1845 def gctrlReadDirTree2(self, oGuestSession, oDir): # type: (testfileset.TestDir) -> bool
1846 """
1847 Helper function to recursively read a guest directory tree specified in the current test.
1848 """
1849
1850 #
1851 # Process the directory.
1852 #
1853
1854 # Open the directory:
1855 try:
1856 oCurDir = oGuestSession.directoryOpen(oDir.sPath, '', None);
1857 except:
1858 return reporter.errorXcpt('sPath=%s' % (oDir.sPath,));
1859
1860 # Read the directory.
1861 dLeftUpper = dict(oDir.dChildrenUpper);
1862 cDot = 0;
1863 cDotDot = 0;
1864 fRc = True;
1865 while True:
1866 try:
1867 oFsObjInfo = oCurDir.read();
1868 except Exception as oXcpt:
1869 if vbox.ComError.notEqual(oXcpt, vbox.ComError.VBOX_E_OBJECT_NOT_FOUND):
1870 fRc = reporter.errorXcpt('Error reading directory "%s":' % (oDir.sPath,));
1871 break;
1872
1873 try:
1874 sName = oFsObjInfo.name;
1875 eType = oFsObjInfo.type;
1876 cbFile = oFsObjInfo.objectSize;
1877 ## @todo check further attributes.
1878 except:
1879 fRc = reporter.errorXcpt();
1880 break;
1881
1882 # '.' and '..' entries are not present in oDir.aoChildren, so special treatment:
1883 if sName in ('.', '..', ):
1884 if eType != vboxcon.FsObjType_Directory:
1885 fRc = reporter.error('Wrong type for "%s": %d, expected %d (Directory)'
1886 % (sName, eType, vboxcon.FsObjType_Directory));
1887 if sName == '.': cDot += 1;
1888 else: cDotDot += 1;
1889 else:
1890 # Find the child and remove it from the dictionary.
1891 sNameUpper = sName.upper();
1892 oFsObj = dLeftUpper.get(sNameUpper);
1893 if oFsObj is None:
1894 fRc = reporter.error('Unknown object "%s" found in "%s" (type %s, size %s)!'
1895 % (sName, oDir.sPath, eType, cbFile,));
1896 else:
1897 del dLeftUpper[sNameUpper];
1898
1899 # Check type
1900 if isinstance(oFsObj, testfileset.TestDir):
1901 if eType != vboxcon.FsObjType_Directory:
1902 fRc = reporter.error('%s: expected directory (%d), got eType=%d!'
1903 % (oFsObj.sPath, vboxcon.FsObjType_Directory, eType,));
1904 elif isinstance(oFsObj, testfileset.TestFile):
1905 if eType != vboxcon.FsObjType_File:
1906 fRc = reporter.error('%s: expected file (%d), got eType=%d!'
1907 % (oFsObj.sPath, vboxcon.FsObjType_File, eType,));
1908 else:
1909 fRc = reporter.error('%s: WTF? type=%s' % (oFsObj.sPath, type(oFsObj),));
1910
1911 # Check the name.
1912 if oFsObj.sName != sName:
1913 fRc = reporter.error('%s: expected name "%s", got "%s" instead!' % (oFsObj.sPath, oFsObj.sName, sName,));
1914
1915 # Check the size if a file.
1916 if isinstance(oFsObj, testfileset.TestFile) and cbFile != oFsObj.cbContent:
1917 fRc = reporter.error('%s: expected size %s, got %s instead!' % (oFsObj.sPath, oFsObj.cbContent, cbFile,));
1918
1919 ## @todo check timestamps and attributes.
1920
1921 # Close the directory
1922 try:
1923 oCurDir.close();
1924 except:
1925 fRc = reporter.errorXcpt('oDir.sPath=%s' % (oDir.sPath,));
1926
1927 # Any files left over?
1928 for sKey in dLeftUpper:
1929 oFsObj = dLeftUpper[sKey];
1930 fRc = reporter.error('%s: Was not returned! (%s)' % (oFsObj.sPath, type(oFsObj),));
1931
1932 # Check the dot and dot-dot counts.
1933 if cDot != 1:
1934 fRc = reporter.error('%s: Found %s "." entries, expected exactly 1!' % (oDir.sPath, cDot,));
1935 if cDotDot != 1:
1936 fRc = reporter.error('%s: Found %s ".." entries, expected exactly 1!' % (oDir.sPath, cDotDot,));
1937
1938 #
1939 # Recurse into subdirectories using info from oDir.
1940 #
1941 for oFsObj in oDir.aoChildren:
1942 if isinstance(oFsObj, testfileset.TestDir):
1943 fRc = self.gctrlReadDirTree2(oGuestSession, oFsObj) and fRc;
1944
1945 return fRc;
1946
1947 def gctrlExecDoTest(self, i, oTest, oRes, oGuestSession):
1948 """
1949 Wrapper function around gctrlExecute to provide more sanity checking
1950 when needed in actual execution tests.
1951 """
1952 reporter.log('Testing #%d, cmd="%s" ...' % (i, oTest.sCmd));
1953 fRcExec = self.gctrlExecute(oTest, oGuestSession, oRes.fRc);
1954 if fRcExec == oRes.fRc:
1955 fRc = True;
1956 if fRcExec is True:
1957 # Compare exit status / code on successful process execution.
1958 if oTest.uExitStatus != oRes.uExitStatus \
1959 or oTest.iExitCode != oRes.iExitCode:
1960 fRc = reporter.error('Test #%d (%s) failed: Got exit status + code %d,%d, expected %d,%d'
1961 % (i, oTest.asArgs, oTest.uExitStatus, oTest.iExitCode,
1962 oRes.uExitStatus, oRes.iExitCode));
1963
1964 # Compare test / result buffers on successful process execution.
1965 if oTest.sBuf is not None and oRes.sBuf is not None:
1966 if not utils.areBytesEqual(oTest.sBuf, oRes.sBuf):
1967 fRc = reporter.error('Test #%d (%s) failed: Got buffer\n%s (%d bytes), expected\n%s (%d bytes)'
1968 % (i, oTest.asArgs,
1969 map(hex, map(ord, oTest.sBuf)), len(oTest.sBuf),
1970 map(hex, map(ord, oRes.sBuf)), len(oRes.sBuf)));
1971 reporter.log2('Test #%d passed: Buffers match (%d bytes)' % (i, len(oRes.sBuf)));
1972 elif oRes.sBuf and not oTest.sBuf:
1973 fRc = reporter.error('Test #%d (%s) failed: Got no buffer data, expected\n%s (%dbytes)' %
1974 (i, oTest.asArgs, map(hex, map(ord, oRes.sBuf)), len(oRes.sBuf),));
1975
1976 if oRes.cbStdOut is not None and oRes.cbStdOut != oTest.cbStdOut:
1977 fRc = reporter.error('Test #%d (%s) failed: Got %d bytes of stdout data, expected %d'
1978 % (i, oTest.asArgs, oTest.cbStdOut, oRes.cbStdOut));
1979 if oRes.cbStdErr is not None and oRes.cbStdErr != oTest.cbStdErr:
1980 fRc = reporter.error('Test #%d (%s) failed: Got %d bytes of stderr data, expected %d'
1981 % (i, oTest.asArgs, oTest.cbStdErr, oRes.cbStdErr));
1982 else:
1983 fRc = reporter.error('Test #%d (%s) failed: Got %s, expected %s' % (i, oTest.asArgs, fRcExec, oRes.fRc));
1984 return fRc;
1985
1986 def gctrlExecute(self, oTest, oGuestSession, fIsError):
1987 """
1988 Helper function to execute a program on a guest, specified in the current test.
1989
1990 Note! This weirdo returns results (process exitcode and status) in oTest.
1991 """
1992 fRc = True; # Be optimistic.
1993
1994 # Reset the weird result stuff:
1995 oTest.cbStdOut = 0;
1996 oTest.cbStdErr = 0;
1997 oTest.sBuf = '';
1998 oTest.uExitStatus = 0;
1999 oTest.iExitCode = 0;
2000
2001 ## @todo Compare execution timeouts!
2002 #tsStart = base.timestampMilli();
2003
2004 try:
2005 reporter.log2('Using session user=%s, sDomain=%s, name=%s, timeout=%d'
2006 % (oGuestSession.user, oGuestSession.domain, oGuestSession.name, oGuestSession.timeout,));
2007 except:
2008 return reporter.errorXcpt();
2009
2010 #
2011 # Start the process:
2012 #
2013 reporter.log2('Executing sCmd=%s, afFlags=%s, timeoutMS=%d, asArgs=%s, asEnv=%s'
2014 % (oTest.sCmd, oTest.afFlags, oTest.timeoutMS, oTest.asArgs, oTest.aEnv,));
2015 try:
2016 oProcess = oGuestSession.processCreate(oTest.sCmd,
2017 oTest.asArgs if self.oTstDrv.fpApiVer >= 5.0 else oTest.asArgs[1:],
2018 oTest.aEnv, oTest.afFlags, oTest.timeoutMS);
2019 except:
2020 reporter.maybeErrXcpt(fIsError, 'asArgs=%s' % (oTest.asArgs,));
2021 return False;
2022 if oProcess is None:
2023 return reporter.error('oProcess is None! (%s)' % (oTest.asArgs,));
2024
2025 #time.sleep(5); # try this if you want to see races here.
2026
2027 # Wait for the process to start properly:
2028 reporter.log2('Process start requested, waiting for start (%dms) ...' % (oTest.timeoutMS,));
2029 iPid = -1;
2030 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Start, ];
2031 try:
2032 eWaitResult = oProcess.waitForArray(aeWaitFor, oTest.timeoutMS);
2033 except:
2034 reporter.maybeErrXcpt(fIsError, 'waitforArray failed for asArgs=%s' % (oTest.asArgs,));
2035 fRc = False;
2036 else:
2037 try:
2038 eStatus = oProcess.status;
2039 iPid = oProcess.PID;
2040 except:
2041 fRc = reporter.errorXcpt('asArgs=%s' % (oTest.asArgs,));
2042 else:
2043 reporter.log2('Wait result returned: %d, current process status is: %d' % (eWaitResult, eStatus,));
2044
2045 #
2046 # Wait for the process to run to completion if necessary.
2047 #
2048 # Note! The above eWaitResult return value can be ignored as it will
2049 # (mostly) reflect the process status anyway.
2050 #
2051 if eStatus == vboxcon.ProcessStatus_Started:
2052
2053 # What to wait for:
2054 aeWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate, ];
2055 if vboxcon.ProcessCreateFlag_WaitForStdOut in oTest.afFlags:
2056 aeWaitFor.append(vboxcon.ProcessWaitForFlag_StdOut);
2057 if vboxcon.ProcessCreateFlag_WaitForStdErr in oTest.afFlags:
2058 aeWaitFor.append(vboxcon.ProcessWaitForFlag_StdErr);
2059 ## @todo Add vboxcon.ProcessWaitForFlag_StdIn.
2060
2061 reporter.log2('Process (PID %d) started, waiting for termination (%dms), aeWaitFor=%s ...'
2062 % (iPid, oTest.timeoutMS, aeWaitFor));
2063 acbFdOut = [0,0,0];
2064 while True:
2065 try:
2066 eWaitResult = oProcess.waitForArray(aeWaitFor, oTest.timeoutMS);
2067 except KeyboardInterrupt: # Not sure how helpful this is, but whatever.
2068 reporter.error('Process (PID %d) execution interrupted' % (iPid,));
2069 try: oProcess.close();
2070 except: pass;
2071 break;
2072 except:
2073 fRc = reporter.errorXcpt('asArgs=%s' % (oTest.asArgs,));
2074 break;
2075 reporter.log2('Wait returned: %d' % (eWaitResult,));
2076
2077 # Process output:
2078 for eFdResult, iFd, sFdNm in [ (vboxcon.ProcessWaitResult_StdOut, 1, 'stdout'),
2079 (vboxcon.ProcessWaitResult_StdErr, 2, 'stderr'), ]:
2080 if eWaitResult in (eFdResult, vboxcon.ProcessWaitResult_WaitFlagNotSupported):
2081 reporter.log2('Reading %s ...' % (sFdNm,));
2082 try:
2083 abBuf = oProcess.Read(1, 64 * 1024, oTest.timeoutMS);
2084 except KeyboardInterrupt: # Not sure how helpful this is, but whatever.
2085 reporter.error('Process (PID %d) execution interrupted' % (iPid,));
2086 try: oProcess.close();
2087 except: pass;
2088 except:
2089 pass; ## @todo test for timeouts and fail on anything else!
2090 else:
2091 if abBuf:
2092 reporter.log2('Process (PID %d) got %d bytes of %s data' % (iPid, len(abBuf), sFdNm,));
2093 acbFdOut[iFd] += len(abBuf);
2094 oTest.sBuf = abBuf; ## @todo Figure out how to uniform + append!
2095
2096 ## Process input (todo):
2097 #if eWaitResult in (vboxcon.ProcessWaitResult_StdIn, vboxcon.ProcessWaitResult_WaitFlagNotSupported):
2098 # reporter.log2('Process (PID %d) needs stdin data' % (iPid,));
2099
2100 # Termination or error?
2101 if eWaitResult in (vboxcon.ProcessWaitResult_Terminate,
2102 vboxcon.ProcessWaitResult_Error,
2103 vboxcon.ProcessWaitResult_Timeout,):
2104 try: eStatus = oProcess.status;
2105 except: fRc = reporter.errorXcpt('asArgs=%s' % (oTest.asArgs,));
2106 reporter.log2('Process (PID %d) reported terminate/error/timeout: %d, status: %d'
2107 % (iPid, eWaitResult, eStatus,));
2108 break;
2109
2110 # End of the wait loop.
2111 _, oTest.cbStdOut, oTest.cbStdErr = acbFdOut;
2112
2113 try: eStatus = oProcess.status;
2114 except: fRc = reporter.errorXcpt('asArgs=%s' % (oTest.asArgs,));
2115 reporter.log2('Final process status (PID %d) is: %d' % (iPid, eStatus));
2116 reporter.log2('Process (PID %d) %d stdout, %d stderr' % (iPid, oTest.cbStdOut, oTest.cbStdErr));
2117
2118 #
2119 # Get the final status and exit code of the process.
2120 #
2121 try:
2122 oTest.uExitStatus = oProcess.status;
2123 oTest.iExitCode = oProcess.exitCode;
2124 except:
2125 fRc = reporter.errorXcpt('asArgs=%s' % (oTest.asArgs,));
2126 reporter.log2('Process (PID %d) has exit code: %d; status: %d ' % (iPid, oTest.iExitCode, oTest.uExitStatus));
2127 return fRc;
2128
2129 def testGuestCtrlSessionEnvironment(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
2130 """
2131 Tests the guest session environment changes.
2132 """
2133 aoTests = [
2134 # Check basic operations.
2135 tdTestSessionEx([ # Initial environment is empty.
2136 tdStepSessionCheckEnv(),
2137 # Check clearing empty env.
2138 tdStepSessionClearEnv(),
2139 tdStepSessionCheckEnv(),
2140 # Check set.
2141 tdStepSessionSetEnv('FOO', 'BAR'),
2142 tdStepSessionCheckEnv(['FOO=BAR',]),
2143 tdStepRequireMinimumApiVer(5.0), # 4.3 can't cope with the remainder.
2144 tdStepSessionClearEnv(),
2145 tdStepSessionCheckEnv(),
2146 # Check unset.
2147 tdStepSessionUnsetEnv('BAR'),
2148 tdStepSessionCheckEnv(['BAR']),
2149 tdStepSessionClearEnv(),
2150 tdStepSessionCheckEnv(),
2151 # Set + unset.
2152 tdStepSessionSetEnv('FOO', 'BAR'),
2153 tdStepSessionCheckEnv(['FOO=BAR',]),
2154 tdStepSessionUnsetEnv('FOO'),
2155 tdStepSessionCheckEnv(['FOO']),
2156 # Bulk environment changes (via attrib) (shall replace existing 'FOO').
2157 tdStepSessionBulkEnv( ['PATH=/bin:/usr/bin', 'TMPDIR=/var/tmp', 'USER=root']),
2158 tdStepSessionCheckEnv(['PATH=/bin:/usr/bin', 'TMPDIR=/var/tmp', 'USER=root']),
2159 ]),
2160 tdTestSessionEx([ # Check that setting the same value several times works.
2161 tdStepSessionSetEnv('FOO','BAR'),
2162 tdStepSessionCheckEnv([ 'FOO=BAR',]),
2163 tdStepSessionSetEnv('FOO','BAR2'),
2164 tdStepSessionCheckEnv([ 'FOO=BAR2',]),
2165 tdStepSessionSetEnv('FOO','BAR3'),
2166 tdStepSessionCheckEnv([ 'FOO=BAR3',]),
2167 tdStepRequireMinimumApiVer(5.0), # 4.3 can't cope with the remainder.
2168 # Add a little unsetting to the mix.
2169 tdStepSessionSetEnv('BAR', 'BEAR'),
2170 tdStepSessionCheckEnv([ 'FOO=BAR3', 'BAR=BEAR',]),
2171 tdStepSessionUnsetEnv('FOO'),
2172 tdStepSessionCheckEnv([ 'FOO', 'BAR=BEAR',]),
2173 tdStepSessionSetEnv('FOO','BAR4'),
2174 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR',]),
2175 # The environment is case sensitive.
2176 tdStepSessionSetEnv('foo','BAR5'),
2177 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR', 'foo=BAR5']),
2178 tdStepSessionUnsetEnv('foo'),
2179 tdStepSessionCheckEnv([ 'FOO=BAR4', 'BAR=BEAR', 'foo']),
2180 ]),
2181 tdTestSessionEx([ # Bulk settings merges stuff, last entry standing.
2182 tdStepSessionBulkEnv(['FOO=bar', 'foo=bar', 'FOO=doofus', 'TMPDIR=/tmp', 'foo=bar2']),
2183 tdStepSessionCheckEnv(['FOO=doofus', 'TMPDIR=/tmp', 'foo=bar2']),
2184 tdStepRequireMinimumApiVer(5.0), # 4.3 is buggy!
2185 tdStepSessionBulkEnv(['2=1+1', 'FOO=doofus2', ]),
2186 tdStepSessionCheckEnv(['2=1+1', 'FOO=doofus2' ]),
2187 ]),
2188 # Invalid variable names.
2189 tdTestSessionEx([
2190 tdStepSessionSetEnv('', 'FOO', vbox.ComError.E_INVALIDARG),
2191 tdStepSessionCheckEnv(),
2192 tdStepRequireMinimumApiVer(5.0), # 4.3 is too relaxed checking input!
2193 tdStepSessionSetEnv('=', '===', vbox.ComError.E_INVALIDARG),
2194 tdStepSessionCheckEnv(),
2195 tdStepSessionSetEnv('FOO=', 'BAR', vbox.ComError.E_INVALIDARG),
2196 tdStepSessionCheckEnv(),
2197 tdStepSessionSetEnv('=FOO', 'BAR', vbox.ComError.E_INVALIDARG),
2198 tdStepSessionCheckEnv(),
2199 tdStepRequireMinimumApiVer(5.0), # 4.3 is buggy and too relaxed!
2200 tdStepSessionBulkEnv(['', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2201 tdStepSessionCheckEnv(),
2202 tdStepSessionBulkEnv(['=', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2203 tdStepSessionCheckEnv(),
2204 tdStepSessionBulkEnv(['=FOO', 'foo=bar'], vbox.ComError.E_INVALIDARG),
2205 tdStepSessionCheckEnv(),
2206 ]),
2207 # A bit more weird keys/values.
2208 tdTestSessionEx([ tdStepSessionSetEnv('$$$', ''),
2209 tdStepSessionCheckEnv([ '$$$=',]), ]),
2210 tdTestSessionEx([ tdStepSessionSetEnv('$$$', '%%%'),
2211 tdStepSessionCheckEnv([ '$$$=%%%',]),
2212 ]),
2213 tdTestSessionEx([ tdStepRequireMinimumApiVer(5.0), # 4.3 is buggy!
2214 tdStepSessionSetEnv(u'ß$%ß&', ''),
2215 tdStepSessionCheckEnv([ u'ß$%ß&=',]),
2216 ]),
2217 # Misc stuff.
2218 tdTestSessionEx([ tdStepSessionSetEnv('FOO', ''),
2219 tdStepSessionCheckEnv(['FOO=',]),
2220 ]),
2221 tdTestSessionEx([ tdStepSessionSetEnv('FOO', 'BAR'),
2222 tdStepSessionCheckEnv(['FOO=BAR',])
2223 ],),
2224 tdTestSessionEx([ tdStepSessionSetEnv('FOO', 'BAR'),
2225 tdStepSessionSetEnv('BAR', 'BAZ'),
2226 tdStepSessionCheckEnv([ 'FOO=BAR', 'BAR=BAZ',]),
2227 ]),
2228 ];
2229 return tdTestSessionEx.executeListTestSessions(aoTests, self.oTstDrv, oSession, oTxsSession, oTestVm, 'SessionEnv');
2230
2231 def testGuestCtrlSession(self, oSession, oTxsSession, oTestVm):
2232 """
2233 Tests the guest session handling.
2234 """
2235
2236 #
2237 # Tests:
2238 #
2239 atTests = [
2240 # Invalid parameters.
2241 [ tdTestSession(sUser = ''), tdTestResultSession() ],
2242 # User account without a passwort - forbidden.
2243 [ tdTestSession(sPassword = "" ), tdTestResultSession() ],
2244 # Various wrong credentials.
2245 # Note! Only windows cares about sDomain, the other guests ignores it.
2246 # Note! On Guest Additions < 4.3 this always succeeds because these don't
2247 # support creating dedicated sessions. Instead, guest process creation
2248 # then will fail. See note below.
2249 [ tdTestSession(sPassword = 'bar'), tdTestResultSession() ],
2250 [ tdTestSession(sUser = 'foo', sPassword = 'bar'), tdTestResultSession() ],
2251 [ tdTestSession(sPassword = 'bar', sDomain = 'boo'), tdTestResultSession() ],
2252 [ tdTestSession(sUser = 'foo', sPassword = 'bar', sDomain = 'boo'), tdTestResultSession() ],
2253 ];
2254 if oTestVm.isWindows(): # domain is ignored elsewhere.
2255 atTests.append([ tdTestSession(sDomain = 'boo'), tdTestResultSession() ]);
2256
2257 # Finally, correct credentials.
2258 atTests.append([ tdTestSession(), tdTestResultSession(fRc = True, cNumSessions = 1) ]);
2259
2260 #
2261 # Run the tests.
2262 #
2263 fRc = True;
2264 for (i, tTest) in enumerate(atTests):
2265 oCurTest = tTest[0] # type: tdTestSession
2266 oCurRes = tTest[1] # type: tdTestResult
2267
2268 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
2269 reporter.log('Testing #%d, user="%s", sPassword="%s", sDomain="%s" ...'
2270 % (i, oCurTest.oCreds.sUser, oCurTest.oCreds.sPassword, oCurTest.oCreds.sDomain));
2271 sCurGuestSessionName = 'testGuestCtrlSession: Test #%d' % (i,);
2272 fRc2, oCurGuestSession = oCurTest.createSession(sCurGuestSessionName, fIsError = oCurRes.fRc);
2273
2274 # See note about < 4.3 Guest Additions above.
2275 uProtocolVersion = 2;
2276 if oCurGuestSession is not None:
2277 try:
2278 uProtocolVersion = oCurGuestSession.protocolVersion;
2279 except:
2280 fRc = reporter.errorXcpt('Test #%d' % (i,));
2281
2282 if uProtocolVersion >= 2 and fRc2 is not oCurRes.fRc:
2283 fRc = reporter.error('Test #%d failed: Session creation failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc,));
2284
2285 if fRc2 and oCurGuestSession is None:
2286 fRc = reporter.error('Test #%d failed: no session object' % (i,));
2287 fRc2 = False;
2288
2289 if fRc2:
2290 if uProtocolVersion >= 2: # For Guest Additions < 4.3 getSessionCount() always will return 1.
2291 cCurSessions = oCurTest.getSessionCount(self.oTstDrv.oVBoxMgr);
2292 if cCurSessions != oCurRes.cNumSessions:
2293 fRc = reporter.error('Test #%d failed: Session count does not match: Got %d, expected %d'
2294 % (i, cCurSessions, oCurRes.cNumSessions));
2295 try:
2296 sObjName = oCurGuestSession.name;
2297 except:
2298 fRc = reporter.errorXcpt('Test #%d' % (i,));
2299 else:
2300 if sObjName != sCurGuestSessionName:
2301 fRc = reporter.error('Test #%d failed: Session name does not match: Got "%s", expected "%s"'
2302 % (i, sObjName, sCurGuestSessionName));
2303 fRc2 = oCurTest.closeSession();
2304 if fRc2 is False:
2305 fRc = reporter.error('Test #%d failed: Session could not be closed' % (i,));
2306
2307 if fRc is False:
2308 return (False, oTxsSession);
2309
2310 #
2311 # Multiple sessions.
2312 #
2313 cMaxGuestSessions = 31; # Maximum number of concurrent guest session allowed.
2314 # Actually, this is 32, but we don't test session 0.
2315 aoMultiSessions = {};
2316 reporter.log2('Opening multiple guest tsessions at once ...');
2317 for i in xrange(cMaxGuestSessions + 1):
2318 aoMultiSessions[i] = tdTestSession(sSessionName = 'MultiSession #%d' % (i,));
2319 aoMultiSessions[i].setEnvironment(oSession, oTxsSession, oTestVm);
2320
2321 cCurSessions = aoMultiSessions[i].getSessionCount(self.oTstDrv.oVBoxMgr);
2322 reporter.log2('MultiSession test #%d count is %d' % (i, cCurSessions));
2323 if cCurSessions != i:
2324 return (reporter.error('MultiSession count is %d, expected %d' % (cCurSessions, i)), oTxsSession);
2325 fRc2, _ = aoMultiSessions[i].createSession('MultiSession #%d' % (i,), i < cMaxGuestSessions);
2326 if fRc2 is not True:
2327 if i < cMaxGuestSessions:
2328 return (reporter.error('MultiSession #%d test failed' % (i,)), oTxsSession);
2329 reporter.log('MultiSession #%d exceeded concurrent guest session count, good' % (i,));
2330 break;
2331
2332 cCurSessions = aoMultiSessions[i].getSessionCount(self.oTstDrv.oVBoxMgr);
2333 if cCurSessions is not cMaxGuestSessions:
2334 return (reporter.error('Final session count %d, expected %d ' % (cCurSessions, cMaxGuestSessions,)), oTxsSession);
2335
2336 reporter.log2('Closing MultiSessions ...');
2337 for i in xrange(cMaxGuestSessions):
2338 # Close this session:
2339 oClosedGuestSession = aoMultiSessions[i].oGuestSession;
2340 fRc2 = aoMultiSessions[i].closeSession();
2341 cCurSessions = aoMultiSessions[i].getSessionCount(self.oTstDrv.oVBoxMgr)
2342 reporter.log2('MultiSession #%d count is %d' % (i, cCurSessions,));
2343 if fRc2 is False:
2344 fRc = reporter.error('Closing MultiSession #%d failed' % (i,));
2345 elif cCurSessions != cMaxGuestSessions - (i + 1):
2346 fRc = reporter.error('Expected %d session after closing #%d, got %d instead'
2347 % (cMaxGuestSessions - (i + 1), cCurSessions, i,));
2348 assert aoMultiSessions[i].oGuestSession is None or not fRc2;
2349 ## @todo any way to check that the session is closed other than the 'sessions' attribute?
2350
2351 # Try check that none of the remaining sessions got closed.
2352 try:
2353 aoGuestSessions = self.oTstDrv.oVBoxMgr.getArray(atTests[0][0].oGuest, 'sessions');
2354 except:
2355 return (reporter.errorXcpt('i=%d/%d' % (i, cMaxGuestSessions,)), oTxsSession);
2356 if oClosedGuestSession in aoGuestSessions:
2357 fRc = reporter.error('i=%d/%d: %s should not be in %s'
2358 % (i, cMaxGuestSessions, oClosedGuestSession, aoGuestSessions));
2359 if i + 1 < cMaxGuestSessions: # Not sure what xrange(2,2) does...
2360 for j in xrange(i + 1, cMaxGuestSessions):
2361 if aoMultiSessions[j].oGuestSession not in aoGuestSessions:
2362 fRc = reporter.error('i=%d/j=%d/%d: %s should be in %s'
2363 % (i, j, cMaxGuestSessions, aoMultiSessions[j].oGuestSession, aoGuestSessions));
2364 ## @todo any way to check that they work?
2365
2366 ## @todo Test session timeouts.
2367
2368 return (fRc, oTxsSession);
2369
2370 def testGuestCtrlSessionFileRefs(self, oSession, oTxsSession, oTestVm):
2371 """
2372 Tests the guest session file reference handling.
2373 """
2374
2375 # Find a file to play around with:
2376 sFile = self.getGuestSystemFileForReading(oTestVm);
2377
2378 # Use credential defaults.
2379 oCreds = tdCtxCreds();
2380 oCreds.applyDefaultsIfNotSet(oTestVm);
2381
2382 # Number of stale guest files to create.
2383 cStaleFiles = 10;
2384
2385 #
2386 # Start a session.
2387 #
2388 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
2389 try:
2390 oGuest = oSession.o.console.guest;
2391 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionFileRefs");
2392 eWaitResult = oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
2393 except:
2394 return (reporter.errorXcpt(), oTxsSession);
2395
2396 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
2397 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
2398 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
2399 reporter.log('Session successfully started');
2400
2401 #
2402 # Open guest files and "forget" them (stale entries).
2403 # For them we don't have any references anymore intentionally.
2404 #
2405 reporter.log2('Opening stale files');
2406 fRc = True;
2407 for i in xrange(0, cStaleFiles):
2408 try:
2409 if self.oTstDrv.fpApiVer >= 5.0:
2410 oGuestSession.fileOpen(sFile, vboxcon.FileAccessMode_ReadOnly, vboxcon.FileOpenAction_OpenExisting, 0);
2411 else:
2412 oGuestSession.fileOpen(sFile, "r", "oe", 0);
2413 # Note: Use a timeout in the call above for not letting the stale processes
2414 # hanging around forever. This can happen if the installed Guest Additions
2415 # do not support terminating guest processes.
2416 except:
2417 fRc = reporter.errorXcpt('Opening stale file #%d failed:' % (i,));
2418 break;
2419
2420 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
2421 except: fRc = reporter.errorXcpt();
2422 else:
2423 if cFiles != cStaleFiles:
2424 fRc = reporter.error('Got %d stale files, expected %d' % (cFiles, cStaleFiles));
2425
2426 if fRc is True:
2427 #
2428 # Open non-stale files and close them again.
2429 #
2430 reporter.log2('Opening non-stale files');
2431 aoFiles = [];
2432 for i in xrange(0, cStaleFiles):
2433 try:
2434 if self.oTstDrv.fpApiVer >= 5.0:
2435 oCurFile = oGuestSession.fileOpen(sFile, vboxcon.FileAccessMode_ReadOnly,
2436 vboxcon.FileOpenAction_OpenExisting, 0);
2437 else:
2438 oCurFile = oGuestSession.fileOpen(sFile, "r", "oe", 0);
2439 aoFiles.append(oCurFile);
2440 except:
2441 fRc = reporter.errorXcpt('Opening non-stale file #%d failed:' % (i,));
2442 break;
2443
2444 # Check the count.
2445 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
2446 except: fRc = reporter.errorXcpt();
2447 else:
2448 if cFiles != cStaleFiles * 2:
2449 fRc = reporter.error('Got %d total files, expected %d' % (cFiles, cStaleFiles * 2));
2450
2451 # Close them.
2452 reporter.log2('Closing all non-stale files again ...');
2453 for i, oFile in enumerate(aoFiles):
2454 try:
2455 oFile.close();
2456 except:
2457 fRc = reporter.errorXcpt('Closing non-stale file #%d failed:' % (i,));
2458
2459 # Check the count again.
2460 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
2461 except: fRc = reporter.errorXcpt();
2462 # Here we count the stale files (that is, files we don't have a reference
2463 # anymore for) and the opened and then closed non-stale files (that we still keep
2464 # a reference in aoFiles[] for).
2465 if cFiles != cStaleFiles:
2466 fRc = reporter.error('Got %d total files, expected %d' % (cFiles, cStaleFiles));
2467
2468 #
2469 # Check that all (referenced) non-stale files are now in the "closed" state.
2470 #
2471 reporter.log2('Checking statuses of all non-stale files ...');
2472 for i, oFile in enumerate(aoFiles):
2473 try:
2474 eFileStatus = aoFiles[i].status;
2475 except:
2476 fRc = reporter.errorXcpt('Checking status of file #%d failed:' % (i,));
2477 else:
2478 if eFileStatus != vboxcon.FileStatus_Closed:
2479 fRc = reporter.error('Non-stale file #%d has status %d, expected %d'
2480 % (i, eFileStatus, vboxcon.FileStatus_Closed));
2481
2482 if fRc is True:
2483 reporter.log2('All non-stale files closed');
2484
2485 try: cFiles = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'files'));
2486 except: fRc = reporter.errorXcpt();
2487 else: reporter.log2('Final guest session file count: %d' % (cFiles,));
2488
2489 #
2490 # Now try to close the session and see what happens.
2491 # Note! Session closing is why we've been doing all the 'if fRc is True' stuff above rather than returning.
2492 #
2493 reporter.log2('Closing guest session ...');
2494 try:
2495 oGuestSession.close();
2496 except:
2497 fRc = reporter.errorXcpt('Testing for stale processes failed:');
2498
2499 return (fRc, oTxsSession);
2500
2501 #def testGuestCtrlSessionDirRefs(self, oSession, oTxsSession, oTestVm):
2502 # """
2503 # Tests the guest session directory reference handling.
2504 # """
2505
2506 # fRc = True;
2507 # return (fRc, oTxsSession);
2508
2509 def testGuestCtrlSessionProcRefs(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
2510 """
2511 Tests the guest session process reference handling.
2512 """
2513
2514 sCmd = self.getGuestSystemShell(oTestVm);
2515 asArgs = [sCmd,];
2516
2517 # Use credential defaults.
2518 oCreds = tdCtxCreds();
2519 oCreds.applyDefaultsIfNotSet(oTestVm);
2520
2521 # Number of stale guest processes to create.
2522 cStaleProcs = 10;
2523
2524 #
2525 # Start a session.
2526 #
2527 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
2528 try:
2529 oGuest = oSession.o.console.guest;
2530 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionProcRefs");
2531 eWaitResult = oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
2532 except:
2533 return (reporter.errorXcpt(), oTxsSession);
2534
2535 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
2536 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
2537 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
2538 reporter.log('Session successfully started');
2539
2540 #
2541 # Fire off forever-running processes and "forget" them (stale entries).
2542 # For them we don't have any references anymore intentionally.
2543 #
2544 reporter.log2('Starting stale processes...');
2545 fRc = True;
2546 for i in xrange(0, cStaleProcs):
2547 try:
2548 oGuestSession.processCreate(sCmd,
2549 asArgs if self.oTstDrv.fpApiVer >= 5.0 else asArgs[1:], [],
2550 [ vboxcon.ProcessCreateFlag_WaitForStdOut ], 30 * 1000);
2551 # Note: Use a timeout in the call above for not letting the stale processes
2552 # hanging around forever. This can happen if the installed Guest Additions
2553 # do not support terminating guest processes.
2554 except:
2555 fRc = reporter.errorXcpt('Creating stale process #%d failed:' % (i,));
2556 break;
2557
2558 try: cProcesses = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
2559 except: fRc = reporter.errorXcpt();
2560 else:
2561 if cProcesses != cStaleProcs:
2562 fRc = reporter.error('Got %d stale processes, expected %d' % (cProcesses, cStaleProcs));
2563
2564 if fRc is True:
2565 #
2566 # Fire off non-stale processes and wait for termination.
2567 #
2568 if oTestVm.isWindows() or oTestVm.isOS2():
2569 asArgs = [ sCmd, '/C', 'dir', '/S', self.getGuestSystemDir(oTestVm), ];
2570 else:
2571 asArgs = [ sCmd, '-c', 'ls -la ' + self.getGuestSystemDir(oTestVm), ];
2572 reporter.log2('Starting non-stale processes...');
2573 aoProcesses = [];
2574 for i in xrange(0, cStaleProcs):
2575 try:
2576 oCurProc = oGuestSession.processCreate(sCmd, asArgs if self.oTstDrv.fpApiVer >= 5.0 else asArgs[1:],
2577 [], [], 0); # Infinite timeout.
2578 aoProcesses.append(oCurProc);
2579 except:
2580 fRc = reporter.errorXcpt('Creating non-stale process #%d failed:' % (i,));
2581 break;
2582
2583 reporter.log2('Waiting for non-stale processes to terminate...');
2584 for i, oProcess in enumerate(aoProcesses):
2585 try:
2586 eWaitResult = oProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate, ], 120 * 1000);
2587 eProcessStatus = oProcess.status;
2588 except:
2589 fRc = reporter.errorXcpt('Waiting for non-stale process #%d failed:' % (i,));
2590 else:
2591 if eProcessStatus != vboxcon.ProcessStatus_TerminatedNormally:
2592 fRc = reporter.error('Waiting for non-stale processes #%d resulted in status %d, expected %d (wr=%d)'
2593 % (i, eProcessStatus, vboxcon.ProcessStatus_TerminatedNormally, eWaitResult));
2594
2595 try: cProcesses = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
2596 except: fRc = reporter.errorXcpt();
2597 else:
2598 # Here we count the stale processes (that is, processes we don't have a reference
2599 # anymore for) and the started + terminated non-stale processes (that we still keep
2600 # a reference in aoProcesses[] for).
2601 if cProcesses != (cStaleProcs * 2):
2602 fRc = reporter.error('Got %d total processes, expected %d' % (cProcesses, cStaleProcs));
2603
2604 if fRc is True:
2605 reporter.log2('All non-stale processes terminated');
2606
2607 #
2608 # Fire off non-stale blocking processes which are terminated via terminate().
2609 #
2610 if oTestVm.isWindows() or oTestVm.isOS2():
2611 asArgs = [ sCmd, '/C', 'pause'];
2612 else:
2613 asArgs = [ sCmd ];
2614 reporter.log2('Starting blocking processes...');
2615 aoProcesses = [];
2616 for i in xrange(0, cStaleProcs):
2617 try:
2618 oCurProc = oGuestSession.processCreate(sCmd, asArgs if self.oTstDrv.fpApiVer >= 5.0 else asArgs[1:],
2619 [], [], 30 * 1000);
2620 # Note: Use a timeout in the call above for not letting the stale processes
2621 # hanging around forever. This can happen if the installed Guest Additions
2622 # do not support terminating guest processes.
2623 aoProcesses.append(oCurProc);
2624 except:
2625 fRc = reporter.errorXcpt('Creating non-stale blocking process #%d failed:' % (i,));
2626 break;
2627
2628 reporter.log2('Terminating blocking processes...');
2629 for i, oProcess in enumerate(aoProcesses):
2630 try:
2631 oProcess.terminate();
2632 except: # Termination might not be supported, just skip and log it.
2633 reporter.logXcpt('Termination of blocking process #%d failed, skipped:' % (i,));
2634
2635 # There still should be 20 processes because we terminated the 10 newest ones.
2636 try: cProcesses = len(self.oTstDrv.oVBoxMgr.getArray(oGuestSession, 'processes'));
2637 except: fRc = reporter.errorXcpt();
2638 else:
2639 if cProcesses != (cStaleProcs * 2):
2640 fRc = reporter.error('Got %d total processes, expected %d' % (cProcesses, cStaleProcs));
2641 reporter.log2('Final guest session processes count: %d' % (cProcesses,));
2642
2643 #
2644 # Now try to close the session and see what happens.
2645 #
2646 reporter.log2('Closing guest session ...');
2647 try:
2648 oGuestSession.close();
2649 except:
2650 fRc = reporter.errorXcpt('Testing for stale processes failed:');
2651
2652 return (fRc, oTxsSession);
2653
2654 def testGuestCtrlExec(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals,too-many-statements
2655 """
2656 Tests the basic execution feature.
2657 """
2658
2659 # Paths:
2660 sVBoxControl = None; ## @todo Get path of installed Guest Additions. Later.
2661 sShell = self.getGuestSystemShell(oTestVm);
2662 sShellOpt = '/C' if oTestVm.isWindows() or oTestVm.isOS2() else '-c';
2663 sSystemDir = self.getGuestSystemDir(oTestVm);
2664 sFileForReading = self.getGuestSystemFileForReading(oTestVm);
2665 if oTestVm.isWindows() or oTestVm.isOS2():
2666 sImageOut = self.getGuestSystemShell(oTestVm);
2667 if oTestVm.isWindows():
2668 sVBoxControl = "C:\\Program Files\\Oracle\\VirtualBox Guest Additions\\VBoxControl.exe";
2669 else:
2670 sImageOut = "/bin/ls";
2671 if oTestVm.isLinux(): ## @todo check solaris and darwin.
2672 sVBoxControl = "/usr/bin/VBoxControl"; # Symlink
2673
2674 # Use credential defaults.
2675 oCreds = tdCtxCreds();
2676 oCreds.applyDefaultsIfNotSet(oTestVm);
2677
2678 atInvalid = [
2679 # Invalid parameters.
2680 [ tdTestExec(), tdTestResultExec() ],
2681 # Non-existent / invalid image.
2682 [ tdTestExec(sCmd = "non-existent"), tdTestResultExec() ],
2683 [ tdTestExec(sCmd = "non-existent2"), tdTestResultExec() ],
2684 # Use an invalid format string.
2685 [ tdTestExec(sCmd = "%$%%%&"), tdTestResultExec() ],
2686 # More stuff.
2687 [ tdTestExec(sCmd = u"ƒ‰‹ˆ÷‹¸"), tdTestResultExec() ],
2688 [ tdTestExec(sCmd = "???://!!!"), tdTestResultExec() ],
2689 [ tdTestExec(sCmd = "<>!\\"), tdTestResultExec() ],
2690 # Enable as soon as ERROR_BAD_DEVICE is implemented.
2691 #[ tdTestExec(sCmd = "CON", tdTestResultExec() ],
2692 ];
2693
2694 atExec = [];
2695 if oTestVm.isWindows() or oTestVm.isOS2():
2696 atExec += [
2697 # Basic execution.
2698 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
2699 tdTestResultExec(fRc = True) ],
2700 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sFileForReading ]),
2701 tdTestResultExec(fRc = True) ],
2702 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir + '\\nonexist.dll' ]),
2703 tdTestResultExec(fRc = True, iExitCode = 1) ],
2704 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', '/wrongparam' ]),
2705 tdTestResultExec(fRc = True, iExitCode = 1) ],
2706 [ tdTestExec(sCmd = sShell, asArgs = [ sShell, sShellOpt, 'wrongcommand' ]),
2707 tdTestResultExec(fRc = True, iExitCode = 1) ],
2708 # StdOut.
2709 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
2710 tdTestResultExec(fRc = True) ],
2711 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', 'stdout-non-existing' ]),
2712 tdTestResultExec(fRc = True, iExitCode = 1) ],
2713 # StdErr.
2714 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
2715 tdTestResultExec(fRc = True) ],
2716 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', 'stderr-non-existing' ]),
2717 tdTestResultExec(fRc = True, iExitCode = 1) ],
2718 # StdOut + StdErr.
2719 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', sSystemDir ]),
2720 tdTestResultExec(fRc = True) ],
2721 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'dir', '/S', 'stdouterr-non-existing' ]),
2722 tdTestResultExec(fRc = True, iExitCode = 1) ],
2723 ];
2724 # atExec.extend([
2725 # FIXME: Failing tests.
2726 # Environment variables.
2727 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_NONEXIST' ],
2728 # tdTestResultExec(fRc = True, iExitCode = 1) ]
2729 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'windir' ],
2730 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2731 # tdTestResultExec(fRc = True, sBuf = 'windir=C:\\WINDOWS\r\n') ],
2732 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
2733 # aEnv = [ 'TEST_FOO=BAR' ],
2734 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2735 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ],
2736 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
2737 # aEnv = [ 'TEST_FOO=BAR', 'TEST_BAZ=BAR' ],
2738 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2739 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ]
2740
2741 ## @todo Create some files (or get files) we know the output size of to validate output length!
2742 ## @todo Add task which gets killed at some random time while letting the guest output something.
2743 #];
2744 else:
2745 atExec += [
2746 # Basic execution.
2747 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '-R', sSystemDir ]),
2748 tdTestResultExec(fRc = True) ],
2749 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sFileForReading ]),
2750 tdTestResultExec(fRc = True) ],
2751 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '--wrong-parameter' ]),
2752 tdTestResultExec(fRc = True, iExitCode = 2) ],
2753 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/non/existent' ]),
2754 tdTestResultExec(fRc = True, iExitCode = 2) ],
2755 [ tdTestExec(sCmd = sShell, asArgs = [ sShell, sShellOpt, 'wrongcommand' ]),
2756 tdTestResultExec(fRc = True, iExitCode = 127) ],
2757 # StdOut.
2758 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sSystemDir ]),
2759 tdTestResultExec(fRc = True) ],
2760 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, 'stdout-non-existing' ]),
2761 tdTestResultExec(fRc = True, iExitCode = 2) ],
2762 # StdErr.
2763 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sSystemDir ]),
2764 tdTestResultExec(fRc = True) ],
2765 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, 'stderr-non-existing' ]),
2766 tdTestResultExec(fRc = True, iExitCode = 2) ],
2767 # StdOut + StdErr.
2768 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, sSystemDir ]),
2769 tdTestResultExec(fRc = True) ],
2770 [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, 'stdouterr-non-existing' ]),
2771 tdTestResultExec(fRc = True, iExitCode = 2) ],
2772 ];
2773 # atExec.extend([
2774 # FIXME: Failing tests.
2775 # Environment variables.
2776 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_NONEXIST' ],
2777 # tdTestResultExec(fRc = True, iExitCode = 1) ]
2778 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'windir' ],
2779 #
2780 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2781 # tdTestResultExec(fRc = True, sBuf = 'windir=C:\\WINDOWS\r\n') ],
2782 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
2783 # aEnv = [ 'TEST_FOO=BAR' ],
2784 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2785 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ],
2786 # [ tdTestExec(sCmd = sImageOut, asArgs = [ sImageOut, '/C', 'set', 'TEST_FOO' ],
2787 # aEnv = [ 'TEST_FOO=BAR', 'TEST_BAZ=BAR' ],
2788 # afFlags = [ vboxcon.ProcessCreateFlag_WaitForStdOut, vboxcon.ProcessCreateFlag_WaitForStdErr ]),
2789 # tdTestResultExec(fRc = True, sBuf = 'TEST_FOO=BAR\r\n') ]
2790
2791 ## @todo Create some files (or get files) we know the output size of to validate output length!
2792 ## @todo Add task which gets killed at some random time while letting the guest output something.
2793 #];
2794
2795 #
2796 for iExitCode in xrange(0, 127):
2797 atExec.append([ tdTestExec(sCmd = sShell, asArgs = [ sShell, sShellOpt, 'exit %s' % iExitCode ]),
2798 tdTestResultExec(fRc = True, iExitCode = iExitCode) ]);
2799
2800 if sVBoxControl:
2801 # Paths with spaces on windows.
2802 atExec.append([ tdTestExec(sCmd = sVBoxControl, asArgs = [ sVBoxControl, 'version' ]),
2803 tdTestResultExec(fRc = True) ]);
2804
2805 # Build up the final test array for the first batch.
2806 atTests = atInvalid + atExec;
2807
2808 #
2809 # First batch: One session per guest process.
2810 #
2811 reporter.log('One session per guest process ...');
2812 fRc = True;
2813 for (i, tTest) in enumerate(atTests):
2814 oCurTest = tTest[0] # type: tdTestExec
2815 oCurRes = tTest[1] # type: tdTestResultExec
2816 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
2817 fRc2, oCurGuestSession = oCurTest.createSession('testGuestCtrlExec: Test #%d' % (i,));
2818 if fRc2 is not True:
2819 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
2820 break;
2821 fRc = self.gctrlExecDoTest(i, oCurTest, oCurRes, oCurGuestSession) and fRc;
2822 fRc = oCurTest.closeSession() and fRc;
2823
2824 reporter.log('Execution of all tests done, checking for stale sessions');
2825
2826 # No sessions left?
2827 try:
2828 aSessions = self.oTstDrv.oVBoxMgr.getArray(oSession.o.console.guest, 'sessions');
2829 except:
2830 fRc = reporter.errorXcpt();
2831 else:
2832 cSessions = len(aSessions);
2833 if cSessions != 0:
2834 fRc = reporter.error('Found %d stale session(s), expected 0:' % (cSessions,));
2835 for (i, aSession) in enumerate(aSessions):
2836 try: reporter.log(' Stale session #%d ("%s")' % (aSession.id, aSession.name));
2837 except: reporter.errorXcpt();
2838
2839 if fRc is not True:
2840 return (fRc, oTxsSession);
2841
2842 reporter.log('Now using one guest session for all tests ...');
2843
2844 #
2845 # Second batch: One session for *all* guest processes.
2846 #
2847
2848 # Create session.
2849 reporter.log('Creating session for all tests ...');
2850 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start, ];
2851 try:
2852 oGuest = oSession.o.console.guest;
2853 oCurGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain,
2854 'testGuestCtrlExec: One session for all tests');
2855 except:
2856 return (reporter.errorXcpt(), oTxsSession);
2857
2858 try:
2859 eWaitResult = oCurGuestSession.waitForArray(aeWaitFor, 30 * 1000);
2860 except:
2861 fRc = reporter.errorXcpt('Waiting for guest session to start failed:');
2862 else:
2863 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
2864 fRc = reporter.error('Session did not start successfully, returned wait result: %d' % (eWaitResult,));
2865 else:
2866 reporter.log('Session successfully started');
2867
2868 # Do the tests within this session.
2869 for (i, tTest) in enumerate(atTests):
2870 oCurTest = tTest[0] # type: tdTestExec
2871 oCurRes = tTest[1] # type: tdTestResultExec
2872
2873 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
2874 fRc = self.gctrlExecDoTest(i, oCurTest, oCurRes, oCurGuestSession);
2875 if fRc is False:
2876 break;
2877
2878 # Close the session.
2879 reporter.log2('Closing guest session ...');
2880 try:
2881 oCurGuestSession.close();
2882 oCurGuestSession = None;
2883 except:
2884 fRc = reporter.errorXcpt('Closing guest session failed:');
2885
2886 # No sessions left?
2887 reporter.log('Execution of all tests done, checking for stale sessions again');
2888 try: cSessions = len(self.oTstDrv.oVBoxMgr.getArray(oSession.o.console.guest, 'sessions'));
2889 except: fRc = reporter.errorXcpt();
2890 else:
2891 if cSessions != 0:
2892 fRc = reporter.error('Found %d stale session(s), expected 0' % (cSessions,));
2893 return (fRc, oTxsSession);
2894
2895 def threadForTestGuestCtrlSessionReboot(self, oGuestProcess):
2896 """
2897 Thread routine which waits for the stale guest process getting terminated (or some error)
2898 while the main test routine reboots the guest. It then compares the expected guest process result
2899 and logs an error if appropriate.
2900 """
2901 reporter.log('Waiting for process to get terminated at reboot ...');
2902 try:
2903 eWaitResult = oGuestProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate ], 5 * 60 * 1000);
2904 except:
2905 return reporter.errorXcpt('waitForArray failed');
2906 try:
2907 eStatus = oGuestProcess.status
2908 except:
2909 return reporter.errorXcpt('failed to get status (wait result %d)' % (eWaitResult,));
2910
2911 if eWaitResult == vboxcon.ProcessWaitResult_Terminate and eStatus == vboxcon.ProcessStatus_Down:
2912 reporter.log('Stale process was correctly terminated (status: down)');
2913 return True;
2914
2915 return reporter.error('Process wait across reboot failed: eWaitResult=%d, expected %d; eStatus=%d, expected %d'
2916 % (eWaitResult, vboxcon.ProcessWaitResult_Terminate, eStatus, vboxcon.ProcessStatus_Down,));
2917
2918 def testGuestCtrlSessionReboot(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
2919 """
2920 Tests guest object notifications when a guest gets rebooted / shutdown.
2921
2922 These notifications gets sent from the guest sessions in order to make API clients
2923 aware of guest session changes.
2924
2925 To test that we create a stale guest process and trigger a reboot of the guest.
2926 """
2927
2928 ## @todo backport fixes to 6.0 and maybe 5.2
2929 if self.oTstDrv.fpApiVer <= 6.0:
2930 reporter.log('Skipping: Required fixes not yet backported!');
2931 return None;
2932
2933 # Use credential defaults.
2934 oCreds = tdCtxCreds();
2935 oCreds.applyDefaultsIfNotSet(oTestVm);
2936
2937 fRc = True;
2938
2939 #
2940 # Start a session.
2941 #
2942 aeWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
2943 try:
2944 oGuest = oSession.o.console.guest;
2945 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlSessionReboot");
2946 eWaitResult = oGuestSession.waitForArray(aeWaitFor, 30 * 1000);
2947 except:
2948 return (reporter.errorXcpt(), oTxsSession);
2949
2950 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
2951 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
2952 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
2953 reporter.log('Session successfully started');
2954
2955 #
2956 # Create a process.
2957 #
2958 sImage = self.getGuestSystemShell(oTestVm);
2959 asArgs = [ sImage, ];
2960 aEnv = [];
2961 afFlags = [];
2962 try:
2963 oGuestProcess = oGuestSession.processCreate(sImage,
2964 asArgs if self.oTstDrv.fpApiVer >= 5.0 else asArgs[1:], aEnv, afFlags,
2965 30 * 1000);
2966 except:
2967 fRc = reporter.error('Failed to start shell process (%s)' % (sImage,));
2968 else:
2969 try:
2970 eWaitResult = oGuestProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
2971 except:
2972 fRc = reporter.errorXcpt('Waiting for shell process (%s) to start failed' % (sImage,));
2973 else:
2974 # Check the result and state:
2975 try: eStatus = oGuestProcess.status;
2976 except: fRc = reporter.errorXcpt('Waiting for shell process (%s) to start failed' % (sImage,));
2977 else:
2978 reporter.log2('Starting process wait result returned: %d; Process status is: %d' % (eWaitResult, eStatus,));
2979 if eWaitResult != vboxcon.ProcessWaitResult_Start:
2980 fRc = reporter.error('wait for ProcessWaitForFlag_Start failed: %d, expected %d (Start)'
2981 % (eWaitResult, vboxcon.ProcessWaitResult_Start,));
2982 elif eStatus != vboxcon.ProcessStatus_Started:
2983 fRc = reporter.error('Unexpected process status after startup: %d, wanted %d (Started)'
2984 % (eStatus, vboxcon.ProcessStatus_Started,));
2985 else:
2986 # Create a thread that waits on the process to terminate
2987 reporter.log('Creating reboot thread ...');
2988 oThreadReboot = threading.Thread(target = self.threadForTestGuestCtrlSessionReboot,
2989 args = (oGuestProcess,),
2990 name = ('threadForTestGuestCtrlSessionReboot'));
2991 oThreadReboot.setDaemon(True);
2992 oThreadReboot.start();
2993
2994 # Not sure why this fudge is needed...
2995 reporter.log('5 second wait fudge before triggering reboot ...');
2996 self.oTstDrv.sleep(5);
2997
2998 # Do the reboot.
2999 reporter.log('Rebooting guest and reconnecting TXS ...');
3000 (oSession, oTxsSession) = self.oTstDrv.txsRebootAndReconnectViaTcp(oSession, oTxsSession,
3001 cMsTimeout = 3 * 60000);
3002 if not oSession or not oTxsSession:
3003 try: oGuestProcess.terminate();
3004 except: reporter.logXcpt();
3005 fRc = False;
3006
3007 reporter.log('Waiting for thread to finish ...');
3008 oThreadReboot.join();
3009
3010 #
3011 # Try make sure we don't leave with a stale process on failure.
3012 #
3013 try: oGuestProcess.terminate();
3014 except: reporter.logXcpt();
3015
3016 #
3017 # Close the session.
3018 #
3019 reporter.log2('Closing guest session ...');
3020 try:
3021 oGuestSession.close();
3022 except:
3023 fRc = reporter.errorXcpt();
3024
3025 return (fRc, oTxsSession);
3026
3027 def testGuestCtrlExecTimeout(self, oSession, oTxsSession, oTestVm):
3028 """
3029 Tests handling of timeouts of started guest processes.
3030 """
3031
3032 sShell = self.getGuestSystemShell(oTestVm);
3033
3034 # Use credential defaults.
3035 oCreds = tdCtxCreds();
3036 oCreds.applyDefaultsIfNotSet(oTestVm);
3037
3038 #
3039 # Create a session.
3040 #
3041 try:
3042 oGuest = oSession.o.console.guest;
3043 oGuestSession = oGuest.createSession(oCreds.sUser, oCreds.sPassword, oCreds.sDomain, "testGuestCtrlExecTimeout");
3044 eWaitResult = oGuestSession.waitForArray([ vboxcon.GuestSessionWaitForFlag_Start, ], 30 * 1000);
3045 except:
3046 return (reporter.errorXcpt(), oTxsSession);
3047
3048 # Be nice to Guest Additions < 4.3: They don't support session handling and therefore return WaitFlagNotSupported.
3049 if eWaitResult not in (vboxcon.GuestSessionWaitResult_Start, vboxcon.GuestSessionWaitResult_WaitFlagNotSupported):
3050 return (reporter.error('Session did not start successfully - wait error: %d' % (eWaitResult,)), oTxsSession);
3051 reporter.log('Session successfully started');
3052
3053 #
3054 # Create a process which never terminates and should timeout when
3055 # waiting for termination.
3056 #
3057 fRc = True;
3058 try:
3059 oCurProcess = oGuestSession.processCreate(sShell, [sShell,] if self.oTstDrv.fpApiVer >= 5.0 else [],
3060 [], [], 30 * 1000);
3061 except:
3062 fRc = reporter.errorXcpt();
3063 else:
3064 reporter.log('Waiting for process 1 being started ...');
3065 try:
3066 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
3067 except:
3068 fRc = reporter.errorXcpt();
3069 else:
3070 if eWaitResult != vboxcon.ProcessWaitResult_Start:
3071 fRc = reporter.error('Waiting for process 1 to start failed, got status %d' % (eWaitResult,));
3072 else:
3073 for msWait in (1, 32, 2000,):
3074 reporter.log('Waiting for process 1 to time out within %sms ...' % (msWait,));
3075 try:
3076 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate, ], msWait);
3077 except:
3078 fRc = reporter.errorXcpt();
3079 break;
3080 if eWaitResult != vboxcon.ProcessWaitResult_Timeout:
3081 fRc = reporter.error('Waiting for process 1 did not time out in %sms as expected: %d'
3082 % (msWait, eWaitResult,));
3083 break;
3084 reporter.log('Waiting for process 1 timed out in %u ms, good' % (msWait,));
3085
3086 try:
3087 oCurProcess.terminate();
3088 except:
3089 reporter.errorXcpt();
3090 oCurProcess = None;
3091
3092 #
3093 # Create another process that doesn't terminate, but which will be killed by VBoxService
3094 # because it ran out of execution time (3 seconds).
3095 #
3096 try:
3097 oCurProcess = oGuestSession.processCreate(sShell, [sShell,] if self.oTstDrv.fpApiVer >= 5.0 else [],
3098 [], [], 3 * 1000);
3099 except:
3100 fRc = reporter.errorXcpt();
3101 else:
3102 reporter.log('Waiting for process 2 being started ...');
3103 try:
3104 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Start ], 30 * 1000);
3105 except:
3106 fRc = reporter.errorXcpt();
3107 else:
3108 if eWaitResult != vboxcon.ProcessWaitResult_Start:
3109 fRc = reporter.error('Waiting for process 2 to start failed, got status %d' % (eWaitResult,));
3110 else:
3111 reporter.log('Waiting for process 2 to get killed for running out of execution time ...');
3112 try:
3113 eWaitResult = oCurProcess.waitForArray([ vboxcon.ProcessWaitForFlag_Terminate, ], 15 * 1000);
3114 except:
3115 fRc = reporter.errorXcpt();
3116 else:
3117 if eWaitResult != vboxcon.ProcessWaitResult_Timeout:
3118 fRc = reporter.error('Waiting for process 2 did not time out when it should, got wait result %d'
3119 % (eWaitResult,));
3120 else:
3121 reporter.log('Waiting for process 2 did not time out, good: %s' % (eWaitResult,));
3122 try:
3123 eStatus = oCurProcess.status;
3124 except:
3125 fRc = reporter.errorXcpt();
3126 else:
3127 if eStatus != vboxcon.ProcessStatus_TimedOutKilled:
3128 fRc = reporter.error('Status of process 2 wrong; excepted %d, got %d'
3129 % (vboxcon.ProcessStatus_TimedOutKilled, eStatus));
3130 else:
3131 reporter.log('Status of process 2 is TimedOutKilled (%d) is it should be.'
3132 % (vboxcon.ProcessStatus_TimedOutKilled,));
3133 try:
3134 oCurProcess.terminate();
3135 except:
3136 reporter.logXcpt();
3137 oCurProcess = None;
3138
3139 #
3140 # Clean up the session.
3141 #
3142 try:
3143 oGuestSession.close();
3144 except:
3145 fRc = reporter.errorXcpt();
3146
3147 return (fRc, oTxsSession);
3148
3149 def testGuestCtrlDirCreate(self, oSession, oTxsSession, oTestVm):
3150 """
3151 Tests creation of guest directories.
3152 """
3153
3154 sScratch = oTestVm.pathJoin(self.getGuestTempDir(oTestVm), 'testGuestCtrlDirCreate');
3155
3156 atTests = [
3157 # Invalid stuff.
3158 [ tdTestDirCreate(sDirectory = '' ), tdTestResultFailure() ],
3159 # More unusual stuff.
3160 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin('..', '.') ), tdTestResultFailure() ],
3161 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin('..', '..') ), tdTestResultFailure() ],
3162 [ tdTestDirCreate(sDirectory = '..' ), tdTestResultFailure() ],
3163 [ tdTestDirCreate(sDirectory = '../' ), tdTestResultFailure() ],
3164 [ tdTestDirCreate(sDirectory = '../../' ), tdTestResultFailure() ],
3165 [ tdTestDirCreate(sDirectory = '/' ), tdTestResultFailure() ],
3166 [ tdTestDirCreate(sDirectory = '/..' ), tdTestResultFailure() ],
3167 [ tdTestDirCreate(sDirectory = '/../' ), tdTestResultFailure() ],
3168 ];
3169 if oTestVm.isWindows() or oTestVm.isOS2():
3170 atTests.extend([
3171 [ tdTestDirCreate(sDirectory = 'C:\\' ), tdTestResultFailure() ],
3172 [ tdTestDirCreate(sDirectory = 'C:\\..' ), tdTestResultFailure() ],
3173 [ tdTestDirCreate(sDirectory = 'C:\\..\\' ), tdTestResultFailure() ],
3174 [ tdTestDirCreate(sDirectory = 'C:/' ), tdTestResultFailure() ],
3175 [ tdTestDirCreate(sDirectory = 'C:/.' ), tdTestResultFailure() ],
3176 [ tdTestDirCreate(sDirectory = 'C:/./' ), tdTestResultFailure() ],
3177 [ tdTestDirCreate(sDirectory = 'C:/..' ), tdTestResultFailure() ],
3178 [ tdTestDirCreate(sDirectory = 'C:/../' ), tdTestResultFailure() ],
3179 [ tdTestDirCreate(sDirectory = '\\\\uncrulez\\foo' ), tdTestResultFailure() ],
3180 ]);
3181 atTests.extend([
3182 # Existing directories and files.
3183 [ tdTestDirCreate(sDirectory = self.getGuestSystemDir(oTestVm) ), tdTestResultFailure() ],
3184 [ tdTestDirCreate(sDirectory = self.getGuestSystemShell(oTestVm) ), tdTestResultFailure() ],
3185 [ tdTestDirCreate(sDirectory = self.getGuestSystemFileForReading(oTestVm) ), tdTestResultFailure() ],
3186 # Creating directories.
3187 [ tdTestDirCreate(sDirectory = sScratch ), tdTestResultSuccess() ],
3188 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo', 'bar', 'baz'),
3189 afFlags = (vboxcon.DirectoryCreateFlag_Parents,) ), tdTestResultSuccess() ],
3190 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo', 'bar', 'baz'),
3191 afFlags = (vboxcon.DirectoryCreateFlag_Parents,) ), tdTestResultSuccess() ],
3192 # Long random names.
3193 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(36, 28))),
3194 tdTestResultSuccess() ],
3195 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(140, 116))),
3196 tdTestResultSuccess() ],
3197 # Too long names. ASSUMES a guests has a 255 filename length limitation.
3198 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(2048, 256))),
3199 tdTestResultFailure() ],
3200 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, self.oTestFiles.generateFilenameEx(2048, 256))),
3201 tdTestResultFailure() ],
3202 # Missing directory in path.
3203 [ tdTestDirCreate(sDirectory = oTestVm.pathJoin(sScratch, 'foo1', 'bar') ), tdTestResultFailure() ],
3204 ]);
3205
3206 fRc = True;
3207 for (i, tTest) in enumerate(atTests):
3208 oCurTest = tTest[0] # type: tdTestDirCreate
3209 oCurRes = tTest[1] # type: tdTestResult
3210 reporter.log('Testing #%d, sDirectory="%s" ...' % (i, oCurTest.sDirectory));
3211
3212 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3213 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirCreate: Test #%d' % (i,));
3214 if fRc is False:
3215 return reporter.error('Test #%d failed: Could not create session' % (i,));
3216
3217 fRc = self.gctrlCreateDir(oCurTest, oCurRes, oCurGuestSession);
3218
3219 fRc = oCurTest.closeSession() and fRc;
3220 if fRc is False:
3221 fRc = reporter.error('Test #%d failed' % (i,));
3222
3223 return (fRc, oTxsSession);
3224
3225 def testGuestCtrlDirCreateTemp(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
3226 """
3227 Tests creation of temporary directories.
3228 """
3229
3230 sSystemDir = self.getGuestSystemDir(oTestVm);
3231 atTests = [
3232 # Invalid stuff (template must have one or more trailin 'X'es (upper case only), or a cluster of three or more).
3233 [ tdTestDirCreateTemp(sDirectory = ''), tdTestResultFailure() ],
3234 [ tdTestDirCreateTemp(sDirectory = sSystemDir, fMode = 1234), tdTestResultFailure() ],
3235 [ tdTestDirCreateTemp(sTemplate = 'xXx', sDirectory = sSystemDir, fMode = 0o700), tdTestResultFailure() ],
3236 [ tdTestDirCreateTemp(sTemplate = 'xxx', sDirectory = sSystemDir, fMode = 0o700), tdTestResultFailure() ],
3237 [ tdTestDirCreateTemp(sTemplate = 'XXx', sDirectory = sSystemDir, fMode = 0o700), tdTestResultFailure() ],
3238 [ tdTestDirCreateTemp(sTemplate = 'bar', sDirectory = 'whatever', fMode = 0o700), tdTestResultFailure() ],
3239 [ tdTestDirCreateTemp(sTemplate = 'foo', sDirectory = 'it is not used', fMode = 0o700), tdTestResultFailure() ],
3240 [ tdTestDirCreateTemp(sTemplate = 'X,so', sDirectory = 'pointless test', fMode = 0o700), tdTestResultFailure() ],
3241 # Non-existing stuff.
3242 [ tdTestDirCreateTemp(sTemplate = 'XXXXXXX',
3243 sDirectory = oTestVm.pathJoin(self.getGuestTempDir(oTestVm), 'non', 'existing')),
3244 tdTestResultFailure() ],
3245 # Working stuff:
3246 [ tdTestDirCreateTemp(sTemplate = 'X', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3247 [ tdTestDirCreateTemp(sTemplate = 'XX', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3248 [ tdTestDirCreateTemp(sTemplate = 'XXX', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3249 [ tdTestDirCreateTemp(sTemplate = 'XXXXXXX', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3250 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3251 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3252 [ tdTestDirCreateTemp(sTemplate = 'tmpXXXtst', sDirectory = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3253 ## @todo test fSecure and pass weird fMode values once these parameters are implemented in the API.
3254 ];
3255
3256 fRc = True;
3257 for (i, tTest) in enumerate(atTests):
3258 oCurTest = tTest[0] # type: tdTestDirCreateTemp
3259 oCurRes = tTest[1] # type: tdTestResult
3260 reporter.log('Testing #%d, sTemplate="%s", fMode=%#o, path="%s", secure="%s" ...' %
3261 (i, oCurTest.sTemplate, oCurTest.fMode, oCurTest.sDirectory, oCurTest.fSecure));
3262
3263 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3264 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirCreateTemp: Test #%d' % (i,));
3265 if fRc is False:
3266 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
3267 break;
3268
3269 sDirTemp = '';
3270 try:
3271 sDirTemp = oCurGuestSession.directoryCreateTemp(oCurTest.sTemplate, oCurTest.fMode,
3272 oCurTest.sDirectory, oCurTest.fSecure);
3273 except:
3274 if oCurRes.fRc is True:
3275 fRc = reporter.errorXcpt('Creating temp directory "%s" failed:' % (oCurTest.sDirectory,));
3276 else:
3277 reporter.logXcpt('Creating temp directory "%s" failed expectedly, skipping:' % (oCurTest.sDirectory,));
3278 else:
3279 reporter.log2('Temporary directory is: "%s"' % (sDirTemp,));
3280 if not sDirTemp:
3281 fRc = reporter.error('Resulting directory is empty!');
3282 else:
3283 ## @todo This does not work for some unknown reason.
3284 #try:
3285 # if self.oTstDrv.fpApiVer >= 5.0:
3286 # fExists = oCurGuestSession.directoryExists(sDirTemp, False);
3287 # else:
3288 # fExists = oCurGuestSession.directoryExists(sDirTemp);
3289 #except:
3290 # fRc = reporter.errorXcpt('sDirTemp=%s' % (sDirTemp,));
3291 #else:
3292 # if fExists is not True:
3293 # fRc = reporter.error('Test #%d failed: Temporary directory "%s" does not exists (%s)'
3294 # % (i, sDirTemp, fExists));
3295 try:
3296 oFsObjInfo = oCurGuestSession.fsObjQueryInfo(sDirTemp, False);
3297 eType = oFsObjInfo.type;
3298 except:
3299 fRc = reporter.errorXcpt('sDirTemp="%s"' % (sDirTemp,));
3300 else:
3301 reporter.log2('%s: eType=%s (dir=%d)' % (sDirTemp, eType, vboxcon.FsObjType_Directory,));
3302 if eType != vboxcon.FsObjType_Directory:
3303 fRc = reporter.error('Temporary directory "%s" not created as a directory: eType=%d'
3304 % (sDirTemp, eType));
3305 fRc = oCurTest.closeSession() and fRc;
3306 return (fRc, oTxsSession);
3307
3308 def testGuestCtrlDirRead(self, oSession, oTxsSession, oTestVm):
3309 """
3310 Tests opening and reading (enumerating) guest directories.
3311 """
3312
3313 sSystemDir = self.getGuestSystemDir(oTestVm);
3314 atTests = [
3315 # Invalid stuff.
3316 [ tdTestDirRead(sDirectory = ''), tdTestResultDirRead() ],
3317 [ tdTestDirRead(sDirectory = sSystemDir, afFlags = [ 1234 ]), tdTestResultDirRead() ],
3318 [ tdTestDirRead(sDirectory = sSystemDir, sFilter = '*.foo'), tdTestResultDirRead() ],
3319 # Non-existing stuff.
3320 [ tdTestDirRead(sDirectory = oTestVm.pathJoin(sSystemDir, 'really-no-such-subdir')), tdTestResultDirRead() ],
3321 [ tdTestDirRead(sDirectory = oTestVm.pathJoin(sSystemDir, 'non', 'existing')), tdTestResultDirRead() ],
3322 ];
3323
3324 if oTestVm.isWindows() or oTestVm.isOS2():
3325 atTests.extend([
3326 # More unusual stuff.
3327 [ tdTestDirRead(sDirectory = 'z:\\'), tdTestResultDirRead() ],
3328 [ tdTestDirRead(sDirectory = '\\\\uncrulez\\foo'), tdTestResultDirRead() ],
3329 ]);
3330
3331 # Read the system directory (ASSUMES at least 5 files in it):
3332 # Windows 7+ has inaccessible system32/com/dmp directory that screws up this test, so skip it on windows:
3333 if not oTestVm.isWindows():
3334 atTests.append([ tdTestDirRead(sDirectory = sSystemDir),
3335 tdTestResultDirRead(fRc = True, cFiles = -5, cDirs = None) ]);
3336 ## @todo trailing slash
3337
3338 # Read from the test file set.
3339 atTests.extend([
3340 [ tdTestDirRead(sDirectory = self.oTestFiles.oEmptyDir.sPath),
3341 tdTestResultDirRead(fRc = True, cFiles = 0, cDirs = 0, cOthers = 0) ],
3342 [ tdTestDirRead(sDirectory = self.oTestFiles.oManyDir.sPath),
3343 tdTestResultDirRead(fRc = True, cFiles = len(self.oTestFiles.oManyDir.aoChildren), cDirs = 0, cOthers = 0) ],
3344 [ tdTestDirRead(sDirectory = self.oTestFiles.oTreeDir.sPath),
3345 tdTestResultDirRead(fRc = True, cFiles = self.oTestFiles.cTreeFiles, cDirs = self.oTestFiles.cTreeDirs,
3346 cOthers = self.oTestFiles.cTreeOthers) ],
3347 ]);
3348
3349
3350 fRc = True;
3351 for (i, tTest) in enumerate(atTests):
3352 oCurTest = tTest[0] # type: tdTestExec
3353 oCurRes = tTest[1] # type: tdTestResultDirRead
3354
3355 reporter.log('Testing #%d, dir="%s" ...' % (i, oCurTest.sDirectory));
3356 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3357 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirRead: Test #%d' % (i,));
3358 if fRc is not True:
3359 break;
3360 (fRc2, cDirs, cFiles, cOthers) = self.gctrlReadDirTree(oCurTest, oCurGuestSession, oCurRes.fRc);
3361 fRc = oCurTest.closeSession() and fRc;
3362
3363 reporter.log2('Test #%d: Returned %d directories, %d files total' % (i, cDirs, cFiles));
3364 if fRc2 is oCurRes.fRc:
3365 if fRc2 is True:
3366 if oCurRes.cFiles is None:
3367 pass; # ignore
3368 elif oCurRes.cFiles >= 0 and cFiles != oCurRes.cFiles:
3369 fRc = reporter.error('Test #%d failed: Got %d files, expected %d' % (i, cFiles, oCurRes.cFiles));
3370 elif oCurRes.cFiles < 0 and cFiles < -oCurRes.cFiles:
3371 fRc = reporter.error('Test #%d failed: Got %d files, expected at least %d'
3372 % (i, cFiles, -oCurRes.cFiles));
3373 if oCurRes.cDirs is None:
3374 pass; # ignore
3375 elif oCurRes.cDirs >= 0 and cDirs != oCurRes.cDirs:
3376 fRc = reporter.error('Test #%d failed: Got %d directories, expected %d' % (i, cDirs, oCurRes.cDirs));
3377 elif oCurRes.cDirs < 0 and cDirs < -oCurRes.cDirs:
3378 fRc = reporter.error('Test #%d failed: Got %d directories, expected at least %d'
3379 % (i, cDirs, -oCurRes.cDirs));
3380 if oCurRes.cOthers is None:
3381 pass; # ignore
3382 elif oCurRes.cOthers >= 0 and cOthers != oCurRes.cOthers:
3383 fRc = reporter.error('Test #%d failed: Got %d other types, expected %d' % (i, cOthers, oCurRes.cOthers));
3384 elif oCurRes.cOthers < 0 and cOthers < -oCurRes.cOthers:
3385 fRc = reporter.error('Test #%d failed: Got %d other types, expected at least %d'
3386 % (i, cOthers, -oCurRes.cOthers));
3387
3388 else:
3389 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc));
3390
3391
3392 #
3393 # Go over a few directories in the test file set and compare names,
3394 # types and sizes rather than just the counts like we did above.
3395 #
3396 if fRc is True:
3397 oCurTest = tdTestDirRead();
3398 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3399 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlDirRead: gctrlReadDirTree2');
3400 if fRc is True:
3401 for oDir in (self.oTestFiles.oEmptyDir, self.oTestFiles.oManyDir, self.oTestFiles.oTreeDir):
3402 reporter.log('Checking "%s" ...' % (oDir.sPath,));
3403 fRc = self.gctrlReadDirTree2(oCurGuestSession, oDir) and fRc;
3404 fRc = oCurTest.closeSession() and fRc;
3405
3406 return (fRc, oTxsSession);
3407
3408
3409 def testGuestCtrlFileRemove(self, oSession, oTxsSession, oTestVm):
3410 """
3411 Tests removing guest files.
3412 """
3413
3414 #
3415 # Create a directory with a few files in it using TXS that we'll use for the initial tests.
3416 #
3417 asTestDirs = [
3418 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-1'), # [0]
3419 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-1', 'subdir-1'), # [1]
3420 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-1', 'subdir-1', 'subsubdir-1'), # [2]
3421 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-2'), # [3]
3422 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-2', 'subdir-2'), # [4]
3423 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-2', 'subdir-2', 'subsbudir-2'), # [5]
3424 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-3'), # [6]
3425 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-4'), # [7]
3426 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-5'), # [8]
3427 oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'rmtestdir-5', 'subdir-5'), # [9]
3428 ]
3429 asTestFiles = [
3430 oTestVm.pathJoin(asTestDirs[0], 'file-0'), # [0]
3431 oTestVm.pathJoin(asTestDirs[0], 'file-1'), # [1]
3432 oTestVm.pathJoin(asTestDirs[0], 'file-2'), # [2]
3433 oTestVm.pathJoin(asTestDirs[1], 'file-3'), # [3] - subdir-1
3434 oTestVm.pathJoin(asTestDirs[1], 'file-4'), # [4] - subdir-1
3435 oTestVm.pathJoin(asTestDirs[2], 'file-5'), # [5] - subsubdir-1
3436 oTestVm.pathJoin(asTestDirs[3], 'file-6'), # [6] - rmtestdir-2
3437 oTestVm.pathJoin(asTestDirs[4], 'file-7'), # [7] - subdir-2
3438 oTestVm.pathJoin(asTestDirs[5], 'file-8'), # [8] - subsubdir-2
3439 ];
3440 for sDir in asTestDirs:
3441 if oTxsSession.syncMkDir(sDir, 0o777) is not True:
3442 return reporter.error('Failed to create test dir "%s"!' % (sDir,));
3443 for sFile in asTestFiles:
3444 if oTxsSession.syncUploadString(sFile, sFile, 0o666) is not True:
3445 return reporter.error('Failed to create test file "%s"!' % (sFile,));
3446
3447 #
3448 # Tear down the directories and files.
3449 #
3450 aoTests = [
3451 # Negative tests first:
3452 tdTestRemoveFile(asTestDirs[0], fRcExpect = False),
3453 tdTestRemoveDir(asTestDirs[0], fRcExpect = False),
3454 tdTestRemoveDir(asTestFiles[0], fRcExpect = False),
3455 tdTestRemoveFile(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-file'), fRcExpect = False),
3456 tdTestRemoveDir(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-dir'), fRcExpect = False),
3457 tdTestRemoveFile(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-dir', 'no-file'), fRcExpect = False),
3458 tdTestRemoveDir(oTestVm.pathJoin(self.oTestFiles.oEmptyDir.sPath, 'no-such-dir', 'no-subdir'), fRcExpect = False),
3459 tdTestRemoveTree(asTestDirs[0], afFlags = [], fRcExpect = False), # Only removes empty dirs, this isn't empty.
3460 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_None,], fRcExpect = False), # ditto
3461 # Empty paths:
3462 tdTestRemoveFile('', fRcExpect = False),
3463 tdTestRemoveDir('', fRcExpect = False),
3464 tdTestRemoveTree('', fRcExpect = False),
3465 # Now actually remove stuff:
3466 tdTestRemoveDir(asTestDirs[7], fRcExpect = True),
3467 tdTestRemoveFile(asTestDirs[6], fRcExpect = False),
3468 tdTestRemoveDir(asTestDirs[6], fRcExpect = True),
3469 tdTestRemoveFile(asTestFiles[0], fRcExpect = True),
3470 tdTestRemoveFile(asTestFiles[0], fRcExpect = False),
3471 # 17:
3472 tdTestRemoveTree(asTestDirs[8], fRcExpect = True), # Removes empty subdirs and leaves the dir itself.
3473 tdTestRemoveDir(asTestDirs[8], fRcExpect = True),
3474 tdTestRemoveTree(asTestDirs[3], fRcExpect = False), # Have subdirs & files,
3475 tdTestRemoveTree(asTestDirs[3], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentOnly,], fRcExpect = True),
3476 tdTestRemoveDir(asTestDirs[3], fRcExpect = True),
3477 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentAndDir,], fRcExpect = True),
3478 # No error if already delete (RTDirRemoveRecursive artifact).
3479 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentAndDir,], fRcExpect = True),
3480 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentOnly,],
3481 fNotExist = True, fRcExpect = True),
3482 tdTestRemoveTree(asTestDirs[0], afFlags = [vboxcon.DirectoryRemoveRecFlag_None,], fNotExist = True, fRcExpect = True),
3483 ];
3484
3485 #
3486 # Execution loop
3487 #
3488 fRc = True;
3489 for (i, oTest) in enumerate(aoTests): # int, tdTestRemoveBase
3490 reporter.log('Testing #%d, path="%s" %s ...' % (i, oTest.sPath, oTest.__class__.__name__));
3491 oTest.setEnvironment(oSession, oTxsSession, oTestVm);
3492 fRc, _ = oTest.createSession('testGuestCtrlFileRemove: Test #%d' % (i,));
3493 if fRc is False:
3494 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
3495 break;
3496 fRc = oTest.execute(self) and fRc;
3497 fRc = oTest.closeSession() and fRc;
3498
3499 if fRc is True:
3500 oCurTest = tdTestDirRead();
3501 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3502 fRc, oCurGuestSession = oCurTest.createSession('remove final');
3503 if fRc is True:
3504
3505 #
3506 # Delete all the files in the many subdir of the test set.
3507 #
3508 reporter.log('Deleting the file in "%s" ...' % (self.oTestFiles.oManyDir.sPath,));
3509 for oFile in self.oTestFiles.oManyDir.aoChildren:
3510 reporter.log2('"%s"' % (oFile.sPath,));
3511 try:
3512 if self.oTstDrv.fpApiVer >= 5.0:
3513 oCurGuestSession.fsObjRemove(oFile.sPath);
3514 else:
3515 oCurGuestSession.fileRemove(oFile.sPath);
3516 except:
3517 fRc = reporter.errorXcpt('Removing "%s" failed' % (oFile.sPath,));
3518
3519 # Remove the directory itself to verify that we've removed all the files in it:
3520 reporter.log('Removing the directory "%s" ...' % (self.oTestFiles.oManyDir.sPath,));
3521 try:
3522 oCurGuestSession.directoryRemove(self.oTestFiles.oManyDir.sPath);
3523 except:
3524 fRc = reporter.errorXcpt('Removing directory "%s" failed' % (self.oTestFiles.oManyDir.sPath,));
3525
3526 #
3527 # Recursively delete the entire test file tree from the root up.
3528 #
3529 # Note! On unix we cannot delete the root dir itself since it is residing
3530 # in /var/tmp where only the owner may delete it. Root is the owner.
3531 #
3532 if oTestVm.isWindows() or oTestVm.isOS2():
3533 afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentAndDir,];
3534 else:
3535 afFlags = [vboxcon.DirectoryRemoveRecFlag_ContentOnly,];
3536 try:
3537 oProgress = oCurGuestSession.directoryRemoveRecursive(self.oTestFiles.oRoot.sPath, afFlags);
3538 except:
3539 fRc = reporter.errorXcpt('Removing tree "%s" failed' % (self.oTestFiles.oRoot.sPath,));
3540 else:
3541 oWrappedProgress = vboxwrappers.ProgressWrapper(oProgress, self.oTstDrv.oVBoxMgr, self.oTstDrv,
3542 "remove-tree-root: %s" % (self.oTestFiles.oRoot.sPath,));
3543 reporter.log2('waiting ...')
3544 oWrappedProgress.wait();
3545 reporter.log2('isSuccess=%s' % (oWrappedProgress.isSuccess(),));
3546 if not oWrappedProgress.isSuccess():
3547 fRc = oWrappedProgress.logResult();
3548
3549 fRc = oCurTest.closeSession() and fRc;
3550
3551 return (fRc, oTxsSession);
3552
3553
3554 def testGuestCtrlFileStat(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
3555 """
3556 Tests querying file information through stat.
3557 """
3558
3559 # Basic stuff, existing stuff.
3560 aoTests = [
3561 tdTestSessionEx([
3562 tdStepStatDir('.'),
3563 tdStepStatDir('..'),
3564 tdStepStatDir(self.getGuestTempDir(oTestVm)),
3565 tdStepStatDir(self.getGuestSystemDir(oTestVm)),
3566 tdStepStatDirEx(self.oTestFiles.oRoot),
3567 tdStepStatDirEx(self.oTestFiles.oEmptyDir),
3568 tdStepStatDirEx(self.oTestFiles.oTreeDir),
3569 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
3570 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
3571 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
3572 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
3573 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
3574 tdStepStatDirEx(self.oTestFiles.chooseRandomDirFromTree()),
3575 tdStepStatFile(self.getGuestSystemFileForReading(oTestVm)),
3576 tdStepStatFile(self.getGuestSystemShell(oTestVm)),
3577 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
3578 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
3579 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
3580 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
3581 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
3582 tdStepStatFileEx(self.oTestFiles.chooseRandomFile()),
3583 ]),
3584 ];
3585
3586 # None existing stuff.
3587 sSysDir = self.getGuestSystemDir(oTestVm);
3588 sSep = oTestVm.pathSep();
3589 aoTests += [
3590 tdTestSessionEx([
3591 tdStepStatFileNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory')),
3592 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory') + sSep),
3593 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', '.')),
3594 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', 'NoSuchFileOrSubDirectory')),
3595 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', 'NoSuchFileOrSubDirectory') + sSep),
3596 tdStepStatPathNotFound(oTestVm.pathJoin(sSysDir, 'NoSuchFileOrDirectory', 'NoSuchFileOrSubDirectory', '.')),
3597 #tdStepStatPathNotFound('N:\\'), # ASSUMES nothing mounted on N:!
3598 #tdStepStatPathNotFound('\\\\NoSuchUncServerName\\NoSuchShare'),
3599 ]),
3600 ];
3601 # Invalid parameter check.
3602 aoTests += [ tdTestSessionEx([ tdStepStat('', vbox.ComError.E_INVALIDARG), ]), ];
3603
3604 #
3605 # Execute the tests.
3606 #
3607 fRc, oTxsSession = tdTestSessionEx.executeListTestSessions(aoTests, self.oTstDrv, oSession, oTxsSession,
3608 oTestVm, 'FsStat');
3609 #
3610 # Test the full test file set.
3611 #
3612 if self.oTstDrv.fpApiVer < 5.0:
3613 return (fRc, oTxsSession);
3614
3615 oTest = tdTestGuestCtrlBase();
3616 oTest.setEnvironment(oSession, oTxsSession, oTestVm);
3617 fRc2, oGuestSession = oTest.createSession('FsStat on TestFileSet');
3618 if fRc2 is not True:
3619 return (False, oTxsSession);
3620
3621 for sPath in self.oTestFiles.dPaths:
3622 oFsObj = self.oTestFiles.dPaths[sPath];
3623 reporter.log2('testGuestCtrlFileStat: %s sPath=%s'
3624 % ('file' if isinstance(oFsObj, testfileset.TestFile) else 'dir ', oFsObj.sPath,));
3625
3626 # Query the information:
3627 try:
3628 oFsInfo = oGuestSession.fsObjQueryInfo(oFsObj.sPath, False);
3629 except:
3630 fRc = reporter.errorXcpt('sPath=%s type=%s: fsObjQueryInfo trouble!' % (oFsObj.sPath, type(oFsObj),));
3631 continue;
3632 if oFsInfo is None:
3633 fRc = reporter.error('sPath=%s type=%s: No info object returned!' % (oFsObj.sPath, type(oFsObj),));
3634 continue;
3635
3636 # Check attributes:
3637 try:
3638 eType = oFsInfo.type;
3639 cbObject = oFsInfo.objectSize;
3640 except:
3641 fRc = reporter.errorXcpt('sPath=%s type=%s: attribute access trouble!' % (oFsObj.sPath, type(oFsObj),));
3642 continue;
3643
3644 if isinstance(oFsObj, testfileset.TestFile):
3645 if eType != vboxcon.FsObjType_File:
3646 fRc = reporter.error('sPath=%s type=file: eType=%s, expected %s!'
3647 % (oFsObj.sPath, eType, vboxcon.FsObjType_File));
3648 if cbObject != oFsObj.cbContent:
3649 fRc = reporter.error('sPath=%s type=file: cbObject=%s, expected %s!'
3650 % (oFsObj.sPath, cbObject, oFsObj.cbContent));
3651 fFileExists = True;
3652 fDirExists = False;
3653 elif isinstance(oFsObj, testfileset.TestDir):
3654 if eType != vboxcon.FsObjType_Directory:
3655 fRc = reporter.error('sPath=%s type=dir: eType=%s, expected %s!'
3656 % (oFsObj.sPath, eType, vboxcon.FsObjType_Directory));
3657 fFileExists = False;
3658 fDirExists = True;
3659 else:
3660 fRc = reporter.error('sPath=%s type=%s: Unexpected oFsObj type!' % (oFsObj.sPath, type(oFsObj),));
3661 continue;
3662
3663 # Check the directoryExists and fileExists results too.
3664 try:
3665 fExistsResult = oGuestSession.fileExists(oFsObj.sPath, False);
3666 except:
3667 fRc = reporter.errorXcpt('sPath=%s type=%s: fileExists trouble!' % (oFsObj.sPath, type(oFsObj),));
3668 else:
3669 if fExistsResult != fFileExists:
3670 fRc = reporter.error('sPath=%s type=%s: fileExists returned %s, expected %s!'
3671 % (oFsObj.sPath, type(oFsObj), fExistsResult, fFileExists));
3672
3673 if not self.fSkipKnownBugs: ## @todo At least two different failures here.
3674 try:
3675 fExistsResult = oGuestSession.directoryExists(oFsObj.sPath, False);
3676 except:
3677 fRc = reporter.errorXcpt('sPath=%s type=%s: directoryExists trouble!' % (oFsObj.sPath, type(oFsObj),));
3678 else:
3679 if fExistsResult != fDirExists:
3680 fRc = reporter.error('sPath=%s type=%s: directoryExists returned %s, expected %s!'
3681 % (oFsObj.sPath, type(oFsObj), fExistsResult, fDirExists));
3682
3683 fRc = oTest.closeSession() and fRc;
3684 return (fRc, oTxsSession);
3685
3686 def testGuestCtrlFileOpen(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
3687 """
3688 Tests opening guest files.
3689 """
3690 if self.oTstDrv.fpApiVer < 5.0:
3691 reporter.log('Skipping because of pre 5.0 API');
3692 return None;
3693
3694 #
3695 # Paths.
3696 #
3697 sTempDir = self.getGuestTempDir(oTestVm);
3698 sFileForReading = self.getGuestSystemFileForReading(oTestVm);
3699 asFiles = [
3700 oTestVm.pathJoin(sTempDir, 'file-open-0'),
3701 oTestVm.pathJoin(sTempDir, 'file-open-1'),
3702 oTestVm.pathJoin(sTempDir, 'file-open-2'),
3703 oTestVm.pathJoin(sTempDir, 'file-open-3'),
3704 oTestVm.pathJoin(sTempDir, 'file-open-4'),
3705 ];
3706 asNonEmptyFiles = [
3707 oTestVm.pathJoin(sTempDir, 'file-open-10'),
3708 oTestVm.pathJoin(sTempDir, 'file-open-11'),
3709 oTestVm.pathJoin(sTempDir, 'file-open-12'),
3710 oTestVm.pathJoin(sTempDir, 'file-open-13'),
3711 ];
3712 sContent = 'abcdefghijklmnopqrstuvwxyz0123456789';
3713 for sFile in asNonEmptyFiles:
3714 if oTxsSession.syncUploadString(sContent, sFile, 0o666) is not True:
3715 return reporter.error('Failed to create "%s" via TXS' % (sFile,));
3716
3717 #
3718 # The tests.
3719 #
3720 atTests = [
3721 # Invalid stuff.
3722 [ tdTestFileOpen(sFile = ''), tdTestResultFailure() ],
3723 # Wrong open mode.
3724 [ tdTestFileOpen(sFile = sFileForReading, eAccessMode = -1), tdTestResultFailure() ],
3725 # Wrong disposition.
3726 [ tdTestFileOpen(sFile = sFileForReading, eAction = -1), tdTestResultFailure() ],
3727 # Non-existing file or path.
3728 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir')), tdTestResultFailure() ],
3729 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir'),
3730 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultFailure() ],
3731 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir'),
3732 eAccessMode = vboxcon.FileAccessMode_WriteOnly,
3733 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultFailure() ],
3734 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-file-or-dir'),
3735 eAccessMode = vboxcon.FileAccessMode_ReadWrite,
3736 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultFailure() ],
3737 [ tdTestFileOpen(sFile = oTestVm.pathJoin(sTempDir, 'no-such-dir', 'no-such-file')), tdTestResultFailure() ],
3738 ];
3739 if oTestVm.isWindows() or not self.fSkipKnownBugs: # We can open directories on linux, but we shouldn't, right...
3740 atTests.extend([
3741 # Wrong type:
3742 [ tdTestFileOpen(sFile = self.getGuestTempDir(oTestVm)), tdTestResultFailure() ],
3743 [ tdTestFileOpen(sFile = self.getGuestSystemDir(oTestVm)), tdTestResultFailure() ],
3744 ]);
3745 atTests.extend([
3746 # O_EXCL and such:
3747 [ tdTestFileOpen(sFile = sFileForReading, eAction = vboxcon.FileOpenAction_CreateNew,
3748 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultFailure() ],
3749 [ tdTestFileOpen(sFile = sFileForReading, eAction = vboxcon.FileOpenAction_CreateNew), tdTestResultFailure() ],
3750 # Open a file.
3751 [ tdTestFileOpen(sFile = sFileForReading), tdTestResultSuccess() ],
3752 [ tdTestFileOpen(sFile = sFileForReading,
3753 eAction = vboxcon.FileOpenAction_OpenOrCreate), tdTestResultSuccess() ],
3754 # Create a new file.
3755 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_CreateNew,
3756 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3757 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_CreateNew,
3758 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultFailure() ],
3759 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_OpenExisting,
3760 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3761 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_CreateOrReplace,
3762 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3763 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_OpenOrCreate,
3764 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3765 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_OpenExistingTruncated,
3766 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3767 [ tdTestFileOpenCheckSize(sFile = asFiles[0], eAction = vboxcon.FileOpenAction_AppendOrCreate,
3768 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3769 # Open or create a new file.
3770 [ tdTestFileOpenCheckSize(sFile = asFiles[1], eAction = vboxcon.FileOpenAction_OpenOrCreate,
3771 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3772 # Create or replace a new file.
3773 [ tdTestFileOpenCheckSize(sFile = asFiles[2], eAction = vboxcon.FileOpenAction_CreateOrReplace,
3774 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3775 # Create and append to file (weird stuff).
3776 [ tdTestFileOpenCheckSize(sFile = asFiles[3], eAction = vboxcon.FileOpenAction_AppendOrCreate,
3777 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3778 [ tdTestFileOpenCheckSize(sFile = asFiles[4], eAction = vboxcon.FileOpenAction_AppendOrCreate,
3779 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3780 # Open the non-empty files in non-destructive modes.
3781 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], cbOpenExpected = len(sContent)), tdTestResultSuccess() ],
3782 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], cbOpenExpected = len(sContent),
3783 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3784 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], cbOpenExpected = len(sContent),
3785 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3786
3787 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], cbOpenExpected = len(sContent),
3788 eAction = vboxcon.FileOpenAction_OpenOrCreate,
3789 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3790 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], cbOpenExpected = len(sContent),
3791 eAction = vboxcon.FileOpenAction_OpenOrCreate,
3792 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3793 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], cbOpenExpected = len(sContent),
3794 eAction = vboxcon.FileOpenAction_OpenOrCreate,
3795 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3796
3797 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], cbOpenExpected = len(sContent),
3798 eAction = vboxcon.FileOpenAction_AppendOrCreate,
3799 eAccessMode = vboxcon.FileAccessMode_ReadWrite), tdTestResultSuccess() ],
3800 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], cbOpenExpected = len(sContent),
3801 eAction = vboxcon.FileOpenAction_AppendOrCreate,
3802 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3803 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], cbOpenExpected = len(sContent),
3804 eAction = vboxcon.FileOpenAction_AppendOrCreate,
3805 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3806
3807 # Now the destructive stuff:
3808 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[0], eAccessMode = vboxcon.FileAccessMode_WriteOnly,
3809 eAction = vboxcon.FileOpenAction_OpenExistingTruncated), tdTestResultSuccess() ],
3810 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[1], eAccessMode = vboxcon.FileAccessMode_WriteOnly,
3811 eAction = vboxcon.FileOpenAction_CreateOrReplace), tdTestResultSuccess() ],
3812 [ tdTestFileOpenCheckSize(sFile = asNonEmptyFiles[2], eAction = vboxcon.FileOpenAction_CreateOrReplace,
3813 eAccessMode = vboxcon.FileAccessMode_WriteOnly), tdTestResultSuccess() ],
3814 ]);
3815
3816 #
3817 # Do the testing.
3818 #
3819 fRc = True;
3820 for (i, tTest) in enumerate(atTests):
3821 oCurTest = tTest[0] # type: tdTestFileOpen
3822 oCurRes = tTest[1] # type: tdTestResult
3823
3824 reporter.log('Testing #%d: %s - sFile="%s", eAccessMode=%d, eAction=%d, (%s, %s, %s) ...'
3825 % (i, oCurTest.__class__.__name__, oCurTest.sFile, oCurTest.eAccessMode, oCurTest.eAction,
3826 oCurTest.eSharing, oCurTest.fCreationMode, oCurTest.afOpenFlags,));
3827
3828 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
3829 fRc, _ = oCurTest.createSession('testGuestCtrlFileOpen: Test #%d' % (i,));
3830 if fRc is not True:
3831 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
3832 break;
3833
3834 fRc2 = oCurTest.doSteps(oCurRes.fRc, self);
3835 if fRc2 != oCurRes.fRc:
3836 fRc = reporter.error('Test #%d result mismatch: Got %s, expected %s' % (i, fRc2, oCurRes.fRc,));
3837
3838 fRc = oCurTest.closeSession() and fRc;
3839
3840 return (fRc, oTxsSession);
3841
3842
3843 def testGuestCtrlFileRead(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-branches,too-many-statements
3844 """
3845 Tests reading from guest files.
3846 """
3847 if self.oTstDrv.fpApiVer < 5.0:
3848 reporter.log('Skipping because of pre 5.0 API');
3849 return None;
3850
3851 #
3852 # Do everything in one session.
3853 #
3854 oTest = tdTestGuestCtrlBase();
3855 oTest.setEnvironment(oSession, oTxsSession, oTestVm);
3856 fRc2, oGuestSession = oTest.createSession('FsStat on TestFileSet');
3857 if fRc2 is not True:
3858 return (False, oTxsSession);
3859
3860 #
3861 # Create a really big zero filled, up to 1 GiB, adding it to the list of
3862 # files from the set.
3863 #
3864 # Note! This code sucks a bit because we don't have a working setSize nor
3865 # any way to figure out how much free space there is in the guest.
3866 #
3867 aoExtraFiles = [];
3868 sBigName = self.oTestFiles.generateFilenameEx();
3869 sBigPath = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, sBigName);
3870 fRc = True;
3871 try:
3872 oFile = oGuestSession.fileOpenEx(sBigPath, vboxcon.FileAccessMode_ReadWrite, vboxcon.FileOpenAction_CreateOrReplace,
3873 vboxcon.FileSharingMode_All, 0, []);
3874 except:
3875 fRc = reporter.errorXcpt('sBigName=%s' % (sBigPath,));
3876 else:
3877 # Does setSize work now?
3878 fUseFallback = True;
3879 try:
3880 oFile.setSize(0);
3881 oFile.setSize(64);
3882 fUseFallback = False;
3883 except Exception as oXcpt:
3884 reporter.logXcpt();
3885
3886 # Grow the file till we hit trouble, typical VERR_DISK_FULL, then
3887 # reduce the file size if we have a working setSize.
3888 cbBigFile = 0;
3889 while cbBigFile < (1024 + 32)*1024*1024:
3890 if not fUseFallback:
3891 cbBigFile += 16*1024*1024;
3892 try:
3893 oFile.setSize(cbBigFile);
3894 except Exception as oXcpt:
3895 reporter.logXcpt('cbBigFile=%s' % (sBigPath,));
3896 try:
3897 cbBigFile -= 16*1024*1024;
3898 oFile.setSize(cbBigFile);
3899 except:
3900 reporter.logXcpt('cbBigFile=%s' % (sBigPath,));
3901 break;
3902 else:
3903 cbBigFile += 32*1024*1024;
3904 try:
3905 oFile.seek(cbBigFile, vboxcon.FileSeekOrigin_Begin);
3906 oFile.write(bytearray(1), 60*1000);
3907 except:
3908 reporter.logXcpt('cbBigFile=%s' % (sBigPath,));
3909 break;
3910 try:
3911 cbBigFile = oFile.seek(0, vboxcon.FileSeekOrigin_End);
3912 except:
3913 fRc = reporter.errorXcpt('sBigName=%s' % (sBigPath,));
3914 try:
3915 oFile.close();
3916 except:
3917 fRc = reporter.errorXcpt('sBigName=%s' % (sBigPath,));
3918 if fRc is True:
3919 reporter.log('Big file: %s bytes: %s' % (cbBigFile, sBigPath,));
3920 aoExtraFiles.append(testfileset.TestFileZeroFilled(None, sBigPath, cbBigFile));
3921 else:
3922 try:
3923 oGuestSession.fsObjRemove(sBigPath);
3924 except:
3925 reporter.errorXcpt('fsObjRemove(sBigName=%s)' % (sBigPath,));
3926
3927 #
3928 # Open and read all the files in the test file set.
3929 #
3930 for oTestFile in aoExtraFiles + self.oTestFiles.aoFiles: # type: testfileset.TestFile
3931 reporter.log2('Test file: %s bytes, "%s" ...' % (oTestFile.cbContent, oTestFile.sPath,));
3932
3933 #
3934 # Open it:
3935 #
3936 try:
3937 oFile = oGuestSession.fileOpenEx(oTestFile.sPath, vboxcon.FileAccessMode_ReadOnly,
3938 vboxcon.FileOpenAction_OpenExisting, vboxcon.FileSharingMode_All, 0, []);
3939 except:
3940 fRc = reporter.errorXcpt('sPath=%s' % (oTestFile.sPath, ));
3941 continue;
3942
3943 #
3944 # Read the file in different sized chunks:
3945 #
3946 if oTestFile.cbContent < 128:
3947 acbChunks = xrange(1,128);
3948 elif oTestFile.cbContent < 1024:
3949 acbChunks = (2048, 127, 63, 32, 29, 17, 16, 15, 9);
3950 elif oTestFile.cbContent < 8*1024*1024:
3951 acbChunks = (128*1024, 32*1024, 8191, 255);
3952 else:
3953 acbChunks = (768*1024, 128*1024);
3954
3955 for cbChunk in acbChunks:
3956 # Read the whole file straight thru:
3957 #if oTestFile.cbContent >= 1024*1024: reporter.log2('... cbChunk=%s' % (cbChunk,));
3958 offFile = 0;
3959 cReads = 0;
3960 while offFile <= oTestFile.cbContent:
3961 try:
3962 abRead = oFile.read(cbChunk, 30*1000);
3963 except:
3964 fRc = reporter.errorXcpt('%s: offFile=%s cbChunk=%s cbContent=%s'
3965 % (oTestFile.sPath, offFile, cbChunk, oTestFile.cbContent));
3966 break;
3967 cbRead = len(abRead);
3968 if cbRead == 0 and offFile == oTestFile.cbContent:
3969 break;
3970 if cbRead <= 0:
3971 fRc = reporter.error('%s @%s: cbRead=%s, cbContent=%s'
3972 % (oTestFile.sPath, offFile, cbRead, oTestFile.cbContent));
3973 break;
3974 if not oTestFile.equalMemory(abRead, offFile):
3975 fRc = reporter.error('%s: read mismatch @ %s LB %s' % (oTestFile.sPath, offFile, cbRead));
3976 break;
3977 offFile += cbRead;
3978 cReads += 1;
3979 if cReads > 8192:
3980 break;
3981
3982 # Seek to start of file.
3983 try:
3984 offFile = oFile.seek(0, vboxcon.FileSeekOrigin_Begin);
3985 except:
3986 fRc = reporter.errorXcpt('%s: error seeking to start of file' % (oTestFile.sPath,));
3987 break;
3988 if offFile != 0:
3989 fRc = reporter.error('%s: seek to start of file returned %u, expected 0' % (oTestFile.sPath, offFile));
3990 break;
3991
3992 #
3993 # Random reads.
3994 #
3995 for _ in xrange(8):
3996 offFile = self.oTestFiles.oRandom.randrange(0, oTestFile.cbContent + 1024);
3997 cbToRead = self.oTestFiles.oRandom.randrange(1, min(oTestFile.cbContent + 256, 768*1024));
3998 #if oTestFile.cbContent >= 1024*1024: reporter.log2('... %s LB %s' % (offFile, cbToRead,));
3999
4000 try:
4001 offActual = oFile.seek(offFile, vboxcon.FileSeekOrigin_Begin);
4002 except:
4003 fRc = reporter.errorXcpt('%s: error seeking to %s' % (oTestFile.sPath, offFile));
4004 break;
4005 if offActual != offFile:
4006 fRc = reporter.error('%s: seek(%s,Begin) -> %s, expected %s'
4007 % (oTestFile.sPath, offFile, offActual, offFile));
4008 break;
4009
4010 try:
4011 abRead = oFile.read(cbToRead, 30*1000);
4012 except:
4013 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s'
4014 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4015 cbRead = 0;
4016 else:
4017 cbRead = len(abRead);
4018 if not oTestFile.equalMemory(abRead, offFile):
4019 fRc = reporter.error('%s: random read mismatch @ %s LB %s' % (oTestFile.sPath, offFile, cbRead,));
4020
4021 try:
4022 offActual = oFile.offset;
4023 except:
4024 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#1)'
4025 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4026 else:
4027 if offActual != offFile + cbRead:
4028 fRc = reporter.error('%s: IFile.offset is %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#1)'
4029 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4030 try:
4031 offActual = oFile.seek(0, vboxcon.FileSeekOrigin_Current);
4032 except:
4033 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#1)'
4034 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4035 else:
4036 if offActual != offFile + cbRead:
4037 fRc = reporter.error('%s: seek(0,cur) -> %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#1)'
4038 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4039
4040 #
4041 # Random reads using readAt.
4042 #
4043 for _ in xrange(12):
4044 offFile = self.oTestFiles.oRandom.randrange(0, oTestFile.cbContent + 1024);
4045 cbToRead = self.oTestFiles.oRandom.randrange(1, min(oTestFile.cbContent + 256, 768*1024));
4046 #if oTestFile.cbContent >= 1024*1024: reporter.log2('... %s LB %s (readAt)' % (offFile, cbToRead,));
4047
4048 try:
4049 abRead = oFile.readAt(offFile, cbToRead, 30*1000);
4050 except:
4051 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s'
4052 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4053 cbRead = 0;
4054 else:
4055 cbRead = len(abRead);
4056 if not oTestFile.equalMemory(abRead, offFile):
4057 fRc = reporter.error('%s: random readAt mismatch @ %s LB %s' % (oTestFile.sPath, offFile, cbRead,));
4058
4059 try:
4060 offActual = oFile.offset;
4061 except:
4062 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#2)'
4063 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4064 else:
4065 if offActual != offFile + cbRead:
4066 fRc = reporter.error('%s: IFile.offset is %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#2)'
4067 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4068
4069 try:
4070 offActual = oFile.seek(0, vboxcon.FileSeekOrigin_Current);
4071 except:
4072 fRc = reporter.errorXcpt('%s: offFile=%s cbToRead=%s cbContent=%s (#2)'
4073 % (oTestFile.sPath, offFile, cbToRead, oTestFile.cbContent));
4074 else:
4075 if offActual != offFile + cbRead:
4076 fRc = reporter.error('%s: seek(0,cur) -> %s, expected %s (offFile=%s cbToRead=%s cbRead=%s) (#2)'
4077 % (oTestFile.sPath, offActual, offFile + cbRead, offFile, cbToRead, cbRead));
4078
4079 #
4080 # A few negative things.
4081 #
4082
4083 # Zero byte reads -> E_INVALIDARG.
4084 try:
4085 abRead = oFile.read(0, 30*1000);
4086 except Exception as oXcpt:
4087 if vbox.ComError.notEqual(oXcpt, vbox.ComError.E_INVALIDARG):
4088 fRc = reporter.errorXcpt('read(0,30s) did not raise E_INVALIDARG as expected!');
4089 else:
4090 fRc = reporter.error('read(0,30s) did not fail!');
4091
4092 try:
4093 abRead = oFile.readAt(0, 0, 30*1000);
4094 except Exception as oXcpt:
4095 if vbox.ComError.notEqual(oXcpt, vbox.ComError.E_INVALIDARG):
4096 fRc = reporter.errorXcpt('readAt(0,0,30s) did not raise E_INVALIDARG as expected!');
4097 else:
4098 fRc = reporter.error('readAt(0,0,30s) did not fail!');
4099
4100 # See what happens when we read 1GiB. We should get a max of 1MiB back.
4101 ## @todo Document this behaviour in VirtualBox.xidl.
4102 try:
4103 oFile.seek(0, vboxcon.FileSeekOrigin_Begin);
4104 except:
4105 fRc = reporter.error('seek(0)');
4106 try:
4107 abRead = oFile.read(1024*1024*1024, 30*1000);
4108 except:
4109 fRc = reporter.errorXcpt('read(1GiB,30s)');
4110 else:
4111 if len(abRead) != min(oTestFile.cbContent, 1024*1024):
4112 fRc = reporter.error('Expected read(1GiB,30s) to return %s bytes, got %s bytes instead'
4113 % (min(oTestFile.cbContent, 1024*1024), len(abRead),));
4114
4115 try:
4116 abRead = oFile.readAt(0, 1024*1024*1024, 30*1000);
4117 except:
4118 fRc = reporter.errorXcpt('readAt(0,1GiB,30s)');
4119 else:
4120 if len(abRead) != min(oTestFile.cbContent, 1024*1024):
4121 reporter.error('Expected readAt(0, 1GiB,30s) to return %s bytes, got %s bytes instead'
4122 % (min(oTestFile.cbContent, 1024*1024), len(abRead),));
4123
4124 #
4125 # Check stat info on the file as well as querySize.
4126 #
4127 if self.oTstDrv.fpApiVer > 5.2:
4128 try:
4129 oFsObjInfo = oFile.queryInfo();
4130 except:
4131 fRc = reporter.errorXcpt('%s: queryInfo()' % (oTestFile.sPath,));
4132 else:
4133 if oFsObjInfo is None:
4134 fRc = reporter.error('IGuestFile::queryInfo returned None');
4135 else:
4136 try:
4137 cbFile = oFsObjInfo.objectSize;
4138 except:
4139 fRc = reporter.errorXcpt();
4140 else:
4141 if cbFile != oTestFile.cbContent:
4142 fRc = reporter.error('%s: queryInfo returned incorrect file size: %s, expected %s'
4143 % (oTestFile.sPath, cbFile, oTestFile.cbContent));
4144
4145 try:
4146 cbFile = oFile.querySize();
4147 except:
4148 fRc = reporter.errorXcpt('%s: querySize()' % (oTestFile.sPath,));
4149 else:
4150 if cbFile != oTestFile.cbContent:
4151 fRc = reporter.error('%s: querySize returned incorrect file size: %s, expected %s'
4152 % (oTestFile.sPath, cbFile, oTestFile.cbContent));
4153
4154 #
4155 # Use seek to test the file size and do a few other end-relative seeks.
4156 #
4157 try:
4158 cbFile = oFile.seek(0, vboxcon.FileSeekOrigin_End);
4159 except:
4160 fRc = reporter.errorXcpt('%s: seek(0,End)' % (oTestFile.sPath,));
4161 else:
4162 if cbFile != oTestFile.cbContent:
4163 fRc = reporter.error('%s: seek(0,End) returned incorrect file size: %s, expected %s'
4164 % (oTestFile.sPath, cbFile, oTestFile.cbContent));
4165 if oTestFile.cbContent > 0:
4166 for _ in xrange(5):
4167 offSeek = self.oTestFiles.oRandom.randrange(oTestFile.cbContent + 1);
4168 try:
4169 offFile = oFile.seek(-offSeek, vboxcon.FileSeekOrigin_End);
4170 except:
4171 fRc = reporter.errorXcpt('%s: seek(%s,End)' % (oTestFile.sPath, -offSeek,));
4172 else:
4173 if offFile != oTestFile.cbContent - offSeek:
4174 fRc = reporter.error('%s: seek(%s,End) returned incorrect offset: %s, expected %s (cbContent=%s)'
4175 % (oTestFile.sPath, -offSeek, offSeek, oTestFile.cbContent - offSeek,
4176 oTestFile.cbContent,));
4177
4178 #
4179 # Close it and we're done with this file.
4180 #
4181 try:
4182 oFile.close();
4183 except:
4184 fRc = reporter.errorXcpt('%s: error closing the file' % (oTestFile.sPath,));
4185
4186 #
4187 # Clean up.
4188 #
4189 for oTestFile in aoExtraFiles:
4190 try:
4191 oGuestSession.fsObjRemove(sBigPath);
4192 except:
4193 fRc = reporter.errorXcpt('fsObjRemove(%s)' % (sBigPath,));
4194
4195 fRc = oTest.closeSession() and fRc;
4196
4197 return (fRc, oTxsSession);
4198
4199
4200 def testGuestCtrlFileWrite(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4201 """
4202 Tests writing to guest files.
4203 """
4204 if self.oTstDrv.fpApiVer < 5.0:
4205 reporter.log('Skipping because of pre 5.0 API');
4206 return None;
4207
4208 #
4209 # The test file and its content.
4210 #
4211 sFile = oTestVm.pathJoin(self.getGuestTempDir(oTestVm), 'gctrl-write-1');
4212 abContent = bytearray(0);
4213
4214 #
4215 # The tests.
4216 #
4217 def randBytes(cbHowMany):
4218 """ Returns an bytearray of random bytes. """
4219 return bytearray(self.oTestFiles.oRandom.getrandbits(8) for _ in xrange(cbHowMany));
4220
4221 aoTests = [
4222 # Write at end:
4223 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_CreateNew, abContent = abContent,
4224 atChunks = [(None, randBytes(1)), (None, randBytes(77)), (None, randBytes(98)),]),
4225 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 1+77+98), # 176
4226 # Appending:
4227 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_AppendOrCreate, abContent = abContent,
4228 atChunks = [(None, randBytes(255)), (None, randBytes(33)),]),
4229 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 176 + 255+33), # 464
4230 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_AppendOrCreate, abContent = abContent,
4231 atChunks = [(10, randBytes(44)),]),
4232 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 464 + 44), # 508
4233 # Write within existing:
4234 tdTestFileOpenAndWrite(sFile = sFile, eAction = vboxcon.FileOpenAction_OpenExisting, abContent = abContent,
4235 atChunks = [(0, randBytes(1)), (50, randBytes(77)), (255, randBytes(199)),]),
4236 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 508),
4237 # Writing around and over the end:
4238 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent,
4239 atChunks = [(500, randBytes(9)), (508, randBytes(15)), (512, randBytes(12)),]),
4240 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 512+12),
4241
4242 # writeAt appending:
4243 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True,
4244 atChunks = [(0, randBytes(23)), (6, randBytes(1018)),]),
4245 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 6+1018), # 1024
4246 # writeAt within existing:
4247 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True,
4248 atChunks = [(1000, randBytes(23)), (1, randBytes(990)),]),
4249 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 1024),
4250 # writeAt around and over the end:
4251 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True,
4252 atChunks = [(1024, randBytes(63)), (1080, randBytes(968)),]),
4253 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 1080+968), # 2048
4254
4255 # writeAt beyond the end (gap is filled with zeros):
4256 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, fUseAtApi = True, atChunks = [(3070, randBytes(2)),]),
4257 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 3072),
4258 # write beyond the end (gap is filled with zeros):
4259 tdTestFileOpenAndWrite(sFile = sFile, abContent = abContent, atChunks = [(4090, randBytes(6)),]),
4260 tdTestFileOpenAndCheckContent(sFile = sFile, abContent = abContent, cbContentExpected = 4096),
4261 ];
4262
4263 for (i, oCurTest) in enumerate(aoTests):
4264 reporter.log('Testing #%d: %s ...' % (i, oCurTest.toString(),));
4265
4266 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4267 fRc, _ = oCurTest.createSession('testGuestCtrlFileWrite: Test #%d' % (i,));
4268 if fRc is not True:
4269 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4270 break;
4271
4272 fRc2 = oCurTest.doSteps(True, self);
4273 if fRc2 is not True:
4274 fRc = reporter.error('Test #%d failed!' % (i,));
4275
4276 fRc = oCurTest.closeSession() and fRc;
4277
4278 #
4279 # Cleanup
4280 #
4281 if oTxsSession.syncRmFile(sFile) is not True:
4282 fRc = reporter.error('Failed to remove write-test file: %s' % (sFile, ));
4283
4284 return (fRc, oTxsSession);
4285
4286 @staticmethod
4287 def __generateFile(sName, cbFile):
4288 """ Helper for generating a file with a given size. """
4289 oFile = open(sName, 'wb');
4290 while cbFile > 0:
4291 cb = cbFile if cbFile < 256*1024 else 256*1024;
4292 oFile.write(bytearray(random.getrandbits(8) for _ in xrange(cb)));
4293 cbFile -= cb;
4294 oFile.close();
4295
4296 def testGuestCtrlCopyTo(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4297 """
4298 Tests copying files from host to the guest.
4299 """
4300
4301 #
4302 # Paths and test files.
4303 #
4304 sScratchHst = os.path.join(self.oTstDrv.sScratchPath, 'cp2');
4305 sScratchTestFilesHst = os.path.join(sScratchHst, self.oTestFiles.sSubDir);
4306 sScratchEmptyDirHst = os.path.join(sScratchTestFilesHst, self.oTestFiles.oEmptyDir.sName);
4307 sScratchNonEmptyDirHst = self.oTestFiles.chooseRandomDirFromTree().buildPath(sScratchHst, os.path.sep);
4308 sScratchTreeDirHst = os.path.join(sScratchTestFilesHst, self.oTestFiles.oTreeDir.sName);
4309
4310 sScratchGst = oTestVm.pathJoin(self.getGuestTempDir(oTestVm), 'cp2');
4311 sScratchDstDir1Gst = oTestVm.pathJoin(sScratchGst, 'dstdir1');
4312 sScratchDstDir2Gst = oTestVm.pathJoin(sScratchGst, 'dstdir2');
4313 sScratchDstDir3Gst = oTestVm.pathJoin(sScratchGst, 'dstdir3');
4314 sScratchDstDir4Gst = oTestVm.pathJoin(sScratchGst, 'dstdir4');
4315 #sScratchGstNotExist = oTestVm.pathJoin(self.getGuestTempDir(oTestVm), 'no-such-file-or-directory');
4316 sScratchHstNotExist = os.path.join(self.oTstDrv.sScratchPath, 'no-such-file-or-directory');
4317 sScratchGstPathNotFound = oTestVm.pathJoin(self.getGuestTempDir(oTestVm), 'no-such-directory', 'or-file');
4318 #sScratchHstPathNotFound = os.path.join(self.oTstDrv.sScratchPath, 'no-such-directory', 'or-file');
4319
4320 if oTestVm.isWindows() or oTestVm.isOS2():
4321 sScratchGstInvalid = "?*|<invalid-name>";
4322 else:
4323 sScratchGstInvalid = None;
4324 if utils.getHostOs() in ('win', 'os2'):
4325 sScratchHstInvalid = "?*|<invalid-name>";
4326 else:
4327 sScratchHstInvalid = None;
4328
4329 for sDir in (sScratchGst, sScratchDstDir1Gst, sScratchDstDir2Gst, sScratchDstDir3Gst, sScratchDstDir4Gst):
4330 if oTxsSession.syncMkDir(sDir, 0o777) is not True:
4331 return reporter.error('TXS failed to create directory "%s"!' % (sDir,));
4332
4333 # Put the test file set under sScratchHst.
4334 if os.path.exists(sScratchHst):
4335 if base.wipeDirectory(sScratchHst) != 0:
4336 return reporter.error('Failed to wipe "%s"' % (sScratchHst,));
4337 else:
4338 try:
4339 os.mkdir(sScratchHst);
4340 except:
4341 return reporter.errorXcpt('os.mkdir(%s)' % (sScratchHst, ));
4342 if self.oTestFiles.writeToDisk(sScratchHst) is not True:
4343 return reporter.error('Filed to write test files to "%s" on the host!' % (sScratchHst,));
4344
4345 # Generate a test file in 32MB to 64 MB range.
4346 sBigFileHst = os.path.join(self.oTstDrv.sScratchPath, 'gctrl-random.data');
4347 cbBigFileHst = random.randrange(32*1024*1024, 64*1024*1024);
4348 reporter.log('cbBigFileHst=%s' % (cbBigFileHst,));
4349 cbLeft = cbBigFileHst;
4350 try:
4351 self.__generateFile(sBigFileHst, cbBigFileHst);
4352 except:
4353 return reporter.errorXcpt('sBigFileHst=%s cbBigFileHst=%s cbLeft=%s' % (sBigFileHst, cbBigFileHst, cbLeft,));
4354 reporter.log('cbBigFileHst=%s' % (cbBigFileHst,));
4355
4356 # Generate an empty file on the host that we can use to save space in the guest.
4357 sEmptyFileHst = os.path.join(self.oTstDrv.sScratchPath, 'gctrl-empty.data');
4358 try:
4359 oFile = open(sEmptyFileHst, "wb");
4360 oFile.close();
4361 except:
4362 return reporter.errorXcpt('sEmptyFileHst=%s' % (sEmptyFileHst,));
4363
4364 #
4365 # Tests.
4366 #
4367 atTests = [
4368 # Nothing given:
4369 [ tdTestCopyToFile(), tdTestResultFailure() ],
4370 [ tdTestCopyToDir(), tdTestResultFailure() ],
4371 # Only source given:
4372 [ tdTestCopyToFile(sSrc = sBigFileHst), tdTestResultFailure() ],
4373 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst), tdTestResultFailure() ],
4374 # Only destination given:
4375 [ tdTestCopyToFile(sDst = oTestVm.pathJoin(sScratchGst, 'dstfile')), tdTestResultFailure() ],
4376 [ tdTestCopyToDir( sDst = sScratchGst), tdTestResultFailure() ],
4377 ];
4378 if not self.fSkipKnownBugs:
4379 atTests.extend([
4380 ## @todo Apparently Main doesn't check the flags, so the first test succeeds.
4381 # Both given, but invalid flags.
4382 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGst, afFlags = [ 0x40000000] ), tdTestResultFailure() ],
4383 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst, sDst = sScratchGst, afFlags = [ 0x40000000] ),
4384 tdTestResultFailure() ],
4385 ]);
4386 atTests.extend([
4387 # Non-existing source, but no destination:
4388 [ tdTestCopyToFile(sSrc = sScratchHstNotExist), tdTestResultFailure() ],
4389 [ tdTestCopyToDir( sSrc = sScratchHstNotExist), tdTestResultFailure() ],
4390 # Valid sources, but destination path not found:
4391 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGstPathNotFound), tdTestResultFailure() ],
4392 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst, sDst = sScratchGstPathNotFound), tdTestResultFailure() ],
4393 # Valid destination, but source file/dir not found:
4394 [ tdTestCopyToFile(sSrc = sScratchHstNotExist, sDst = oTestVm.pathJoin(sScratchGst, 'dstfile')),
4395 tdTestResultFailure() ],
4396 [ tdTestCopyToDir( sSrc = sScratchHstNotExist, sDst = sScratchGst), tdTestResultFailure() ],
4397 # Wrong type:
4398 [ tdTestCopyToFile(sSrc = sScratchEmptyDirHst, sDst = oTestVm.pathJoin(sScratchGst, 'dstfile')),
4399 tdTestResultFailure() ],
4400 [ tdTestCopyToDir( sSrc = sBigFileHst, sDst = sScratchGst), tdTestResultFailure() ],
4401 ]);
4402 # Invalid characters in destination or source path:
4403 if sScratchGstInvalid is not None:
4404 atTests.extend([
4405 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, sScratchGstInvalid)),
4406 tdTestResultFailure() ],
4407 [ tdTestCopyToDir( sSrc = sScratchEmptyDirHst, sDst = oTestVm.pathJoin(sScratchGst, sScratchGstInvalid)),
4408 tdTestResultFailure() ],
4409 ]);
4410 if sScratchHstInvalid is not None:
4411 atTests.extend([
4412 [ tdTestCopyToFile(sSrc = os.path.join(self.oTstDrv.sScratchPath, sScratchHstInvalid), sDst = sScratchGst),
4413 tdTestResultFailure() ],
4414 [ tdTestCopyToDir( sSrc = os.path.join(self.oTstDrv.sScratchPath, sScratchHstInvalid), sDst = sScratchGst),
4415 tdTestResultFailure() ],
4416 ]);
4417
4418 #
4419 # Single file handling.
4420 #
4421 atTests.extend([
4422 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat')),
4423 tdTestResultSuccess() ],
4424 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat')), # Overwrite
4425 tdTestResultSuccess() ],
4426 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat')), # Overwrite
4427 tdTestResultSuccess() ],
4428 ]);
4429 if self.oTstDrv.fpApiVer > 5.2: # Copying files into directories via Main is supported only 6.0 and later.
4430 atTests.extend([
4431 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGst), tdTestResultSuccess() ],
4432 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = sScratchGst), tdTestResultSuccess() ], # Overwrite
4433 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = oTestVm.pathJoin(sScratchGst, os.path.split(sBigFileHst)[1])),
4434 tdTestResultSuccess() ], # Overwrite
4435 ]);
4436
4437 if oTestVm.isWindows():
4438 # Copy to a Windows alternative data stream (ADS).
4439 atTests.extend([
4440 [ tdTestCopyToFile(sSrc = sBigFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat:ADS-Test')),
4441 tdTestResultSuccess() ],
4442 [ tdTestCopyToFile(sSrc = sEmptyFileHst, sDst = oTestVm.pathJoin(sScratchGst, 'HostGABig.dat:ADS-Test')),
4443 tdTestResultSuccess() ],
4444 ]);
4445
4446 #
4447 # Directory handling.
4448 #
4449 if self.oTstDrv.fpApiVer > 5.2: # Copying directories via Main is supported only in versions > 5.2.
4450 atTests.extend([
4451 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir1Gst), tdTestResultSuccess() ],
4452 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir1Gst), tdTestResultFailure() ],
4453 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir1Gst,
4454 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting]), tdTestResultSuccess() ],
4455 # Try again with trailing slash, should yield the same result:
4456 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir2Gst + oTestVm.pathSep()),
4457 tdTestResultSuccess() ],
4458 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir2Gst + oTestVm.pathSep()),
4459 tdTestResultFailure() ],
4460 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = sScratchDstDir2Gst + oTestVm.pathSep(),
4461 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting]),
4462 tdTestResultSuccess() ],
4463 ]);
4464 if not self.fSkipKnownBugs:
4465 atTests.extend([
4466 # Copy with a different destination name just for the heck of it:
4467 [ tdTestCopyToDir(sSrc = sScratchEmptyDirHst, sDst = oTestVm.pathJoin(sScratchDstDir1Gst, 'empty2')),
4468 tdTestResultSuccess() ],
4469 ]);
4470 atTests.extend([
4471 # Now the same using a directory with files in it:
4472 [ tdTestCopyToDir(sSrc = sScratchNonEmptyDirHst, sDst = sScratchDstDir3Gst), tdTestResultSuccess() ],
4473 [ tdTestCopyToDir(sSrc = sScratchNonEmptyDirHst, sDst = sScratchDstDir3Gst), tdTestResultFailure() ],
4474 ]);
4475 if not self.fSkipKnownBugs:
4476 atTests.extend([
4477 [ tdTestCopyToDir(sSrc = sScratchNonEmptyDirHst, sDst = sScratchDstDir3Gst,
4478 afFlags = [vboxcon.DirectoryCopyFlag_CopyIntoExisting]), tdTestResultSuccess() ],
4479 ]);
4480 atTests.extend([
4481 #[ tdTestRemoveGuestDir(sScratchDstDir2Gst, tdTestResult() ],
4482 # Copy the entire test tree:
4483 [ tdTestCopyToDir(sSrc = sScratchTreeDirHst, sDst = sScratchDstDir4Gst), tdTestResultSuccess() ],
4484 #[ tdTestRemoveGuestDir(sScratchDstDir3Gst, tdTestResult() ],
4485 ]);
4486
4487 fRc = True;
4488 for (i, tTest) in enumerate(atTests):
4489 oCurTest = tTest[0]; # tdTestCopyTo
4490 oCurRes = tTest[1]; # tdTestResult
4491 reporter.log('Testing #%d, sSrc=%s, sDst=%s, afFlags=%s ...' % (i, oCurTest.sSrc, oCurTest.sDst, oCurTest.afFlags));
4492
4493 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4494 fRc, oCurGuestSession = oCurTest.createSession('testGuestCtrlCopyTo: Test #%d' % (i,));
4495 if fRc is not True:
4496 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4497 break;
4498
4499 fRc2 = False;
4500 if isinstance(oCurTest, tdTestCopyToFile):
4501 fRc2 = self.gctrlCopyFileTo(oCurGuestSession, oCurTest.sSrc, oCurTest.sDst, oCurTest.afFlags, oCurRes.fRc);
4502 else:
4503 fRc2 = self.gctrlCopyDirTo(oCurGuestSession, oCurTest.sSrc, oCurTest.sDst, oCurTest.afFlags, oCurRes.fRc);
4504 if fRc2 is not oCurRes.fRc:
4505 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc));
4506
4507 fRc = oCurTest.closeSession() and fRc;
4508
4509 return (fRc, oTxsSession);
4510
4511 def testGuestCtrlCopyFrom(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4512 """
4513 Tests copying files from guest to the host.
4514 """
4515
4516 #
4517 # Paths.
4518 #
4519 sScratchHst = os.path.join(self.oTstDrv.sScratchPath, "testGctrlCopyFrom");
4520 sScratchDstDir1Hst = os.path.join(sScratchHst, "dstdir1");
4521 sScratchDstDir2Hst = os.path.join(sScratchHst, "dstdir2");
4522 sScratchDstDir3Hst = os.path.join(sScratchHst, "dstdir3");
4523 oExistingFileGst = self.oTestFiles.chooseRandomFile();
4524 oNonEmptyDirGst = self.oTestFiles.chooseRandomDirFromTree(fNonEmpty = True);
4525 oEmptyDirGst = self.oTestFiles.oEmptyDir;
4526
4527 if oTestVm.isWindows() or oTestVm.isOS2():
4528 sScratchGstInvalid = "?*|<invalid-name>";
4529 else:
4530 sScratchGstInvalid = None;
4531 if utils.getHostOs() in ('win', 'os2'):
4532 sScratchHstInvalid = "?*|<invalid-name>";
4533 else:
4534 sScratchHstInvalid = None;
4535
4536 if os.path.exists(sScratchHst):
4537 if base.wipeDirectory(sScratchHst) != 0:
4538 return reporter.error('Failed to wipe "%s"' % (sScratchHst,));
4539 else:
4540 try:
4541 os.mkdir(sScratchHst);
4542 except:
4543 return reporter.errorXcpt('os.mkdir(%s)' % (sScratchHst, ));
4544
4545 for sSubDir in (sScratchDstDir1Hst, sScratchDstDir2Hst, sScratchDstDir3Hst):
4546 try:
4547 os.mkdir(sSubDir);
4548 except:
4549 return reporter.errorXcpt('os.mkdir(%s)' % (sSubDir, ));
4550
4551 #
4552 # Bad parameter tests.
4553 #
4554 atTests = [
4555 # Missing both source and destination:
4556 [ tdTestCopyFromFile(), tdTestResultFailure() ],
4557 [ tdTestCopyFromDir(), tdTestResultFailure() ],
4558 # Missing source.
4559 [ tdTestCopyFromFile(sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
4560 [ tdTestCopyFromDir( sDst = sScratchHst), tdTestResultFailure() ],
4561 # Missing destination.
4562 [ tdTestCopyFromFile(oSrc = oExistingFileGst), tdTestResultFailure() ],
4563 [ tdTestCopyFromDir( sSrc = self.oTestFiles.oManyDir.sPath), tdTestResultFailure() ],
4564 ##
4565 ## @todo main isn't validating flags, so these theses will succeed.
4566 ##
4567 ## Invalid flags:
4568 #[ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'somefile'), afFlags = [0x40000000]),
4569 # tdTestResultFailure() ],
4570 #[ tdTestCopyFromDir( oSrc = oEmptyDirGst, sDst = os.path.join(sScratchHst, 'somedir'), afFlags = [ 0x40000000] ),
4571 # tdTestResultFailure() ],
4572 # Non-existing sources:
4573 [ tdTestCopyFromFile(sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-file-or-directory'),
4574 sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
4575 [ tdTestCopyFromDir( sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-file-or-directory'),
4576 sDst = os.path.join(sScratchHst, 'somedir')), tdTestResultFailure() ],
4577 [ tdTestCopyFromFile(sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-directory', 'no-such-file'),
4578 sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
4579 [ tdTestCopyFromDir( sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, 'no-such-directory', 'no-such-subdir'),
4580 sDst = os.path.join(sScratchHst, 'somedir')), tdTestResultFailure() ],
4581 # Non-existing destinations:
4582 [ tdTestCopyFromFile(oSrc = oExistingFileGst,
4583 sDst = os.path.join(sScratchHst, 'no-such-directory', 'somefile') ), tdTestResultFailure() ],
4584 [ tdTestCopyFromDir( oSrc = oEmptyDirGst, sDst = os.path.join(sScratchHst, 'no-such-directory', 'somedir') ),
4585 tdTestResultFailure() ],
4586 [ tdTestCopyFromFile(oSrc = oExistingFileGst,
4587 sDst = os.path.join(sScratchHst, 'no-such-directory-slash' + os.path.sep)),
4588 tdTestResultFailure() ],
4589 # Wrong source type:
4590 [ tdTestCopyFromFile(oSrc = oNonEmptyDirGst, sDst = os.path.join(sScratchHst, 'somefile') ), tdTestResultFailure() ],
4591 [ tdTestCopyFromDir(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'somedir') ), tdTestResultFailure() ],
4592 ];
4593 # Bogus names:
4594 if sScratchHstInvalid:
4595 atTests.extend([
4596 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, sScratchHstInvalid)),
4597 tdTestResultFailure() ],
4598 [ tdTestCopyFromDir( sSrc = self.oTestFiles.oManyDir.sPath, sDst = os.path.join(sScratchHst, sScratchHstInvalid)),
4599 tdTestResultFailure() ],
4600 ]);
4601 if sScratchGstInvalid:
4602 atTests.extend([
4603 [ tdTestCopyFromFile(sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, sScratchGstInvalid),
4604 sDst = os.path.join(sScratchHst, 'somefile')), tdTestResultFailure() ],
4605 [ tdTestCopyFromDir( sSrc = oTestVm.pathJoin(self.oTestFiles.oRoot.sPath, sScratchGstInvalid),
4606 sDst = os.path.join(sScratchHst, 'somedir')), tdTestResultFailure() ],
4607 ]);
4608
4609 #
4610 # Single file copying.
4611 #
4612 atTests.extend([
4613 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'copyfile1')),
4614 tdTestResultSuccess() ],
4615 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'copyfile1')), # Overwrite it
4616 tdTestResultSuccess() ],
4617 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = os.path.join(sScratchHst, 'copyfile2')),
4618 tdTestResultSuccess() ],
4619 ]);
4620 if self.oTstDrv.fpApiVer > 5.2:
4621 # Copy into a directory.
4622 atTests.extend([
4623 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = sScratchHst), tdTestResultSuccess() ],
4624 [ tdTestCopyFromFile(oSrc = oExistingFileGst, sDst = sScratchHst + os.path.sep), tdTestResultSuccess() ],
4625 ]);
4626
4627 #
4628 # Directory tree copying:
4629 #
4630 atTests.extend([
4631 # Copy the empty guest directory (should end up as sScratchHst/empty):
4632 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir1Hst), tdTestResultSuccess() ],
4633 # Repeat -- this time it should fail, as the destination directory already exists (and
4634 # DirectoryCopyFlag_CopyIntoExisting is not specified):
4635 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir1Hst), tdTestResultFailure() ],
4636 # Add the DirectoryCopyFlag_CopyIntoExisting flag being set and it should work.
4637 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir1Hst,
4638 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
4639 # Try again with trailing slash, should yield the same result:
4640 [ tdTestRemoveHostDir(os.path.join(sScratchDstDir1Hst, 'empty')), tdTestResult() ],
4641 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir1Hst + os.path.sep),
4642 tdTestResultSuccess() ],
4643 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir1Hst + os.path.sep),
4644 tdTestResultFailure() ],
4645 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = sScratchDstDir1Hst + os.path.sep,
4646 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
4647 # Copy with a different destination name just for the heck of it:
4648 [ tdTestCopyFromDir(oSrc = oEmptyDirGst, sDst = os.path.join(sScratchHst, 'empty2'), fIntoDst = True),
4649 tdTestResultFailure() ],
4650 # Now the same using a directory with files in it:
4651 [ tdTestCopyFromDir(oSrc = oNonEmptyDirGst, sDst = sScratchDstDir2Hst), tdTestResultSuccess() ],
4652 [ tdTestCopyFromDir(oSrc = oNonEmptyDirGst, sDst = sScratchDstDir2Hst), tdTestResultFailure() ],
4653 [ tdTestCopyFromDir(oSrc = oNonEmptyDirGst, sDst = sScratchDstDir2Hst,
4654 afFlags = [ vboxcon.DirectoryCopyFlag_CopyIntoExisting, ]), tdTestResultSuccess() ],
4655 # Copy the entire test tree:
4656 [ tdTestCopyFromDir(sSrc = self.oTestFiles.oTreeDir.sPath, sDst = sScratchDstDir3Hst), tdTestResultSuccess() ],
4657 ]);
4658
4659 #
4660 # Execute the tests.
4661 #
4662 fRc = True;
4663 for (i, tTest) in enumerate(atTests):
4664 oCurTest = tTest[0]
4665 oCurRes = tTest[1] # type: tdTestResult
4666 if isinstance(oCurTest, tdTestCopyFrom):
4667 reporter.log('Testing #%d, %s: sSrc="%s", sDst="%s", afFlags="%s" ...'
4668 % (i, "directory" if isinstance(oCurTest, tdTestCopyFromDir) else "file",
4669 oCurTest.sSrc, oCurTest.sDst, oCurTest.afFlags,));
4670 else:
4671 reporter.log('Testing #%d, tdTestRemoveHostDir "%s" ...' % (i, oCurTest.sDir,));
4672 if isinstance(oCurTest, tdTestCopyFromDir) and self.oTstDrv.fpApiVer < 6.0:
4673 reporter.log('Skipping directoryCopyFromGuest test, not implemented in %s' % (self.oTstDrv.fpApiVer,));
4674 continue;
4675
4676 if isinstance(oCurTest, tdTestRemoveHostDir):
4677 fRc = oCurTest.execute(self.oTstDrv, oSession, oTxsSession, oTestVm, 'testing #%d' % (i,));
4678 else:
4679 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4680 fRc2, oCurGuestSession = oCurTest.createSession('testGuestCtrlCopyFrom: Test #%d' % (i,));
4681 if fRc2 is not True:
4682 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4683 break;
4684
4685 if isinstance(oCurTest, tdTestCopyFromFile):
4686 fRc2 = self.gctrlCopyFileFrom(oCurGuestSession, oCurTest, oCurRes.fRc);
4687 else:
4688 fRc2 = self.gctrlCopyDirFrom(oCurGuestSession, oCurTest, oCurRes.fRc);
4689
4690 if fRc2 != oCurRes.fRc:
4691 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc2, oCurRes.fRc));
4692
4693 fRc = oCurTest.closeSession() and fRc;
4694
4695 return (fRc, oTxsSession);
4696
4697 def testGuestCtrlUpdateAdditions(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals
4698 """
4699 Tests updating the Guest Additions inside the guest.
4700
4701 """
4702
4703 ## @todo currently disabled everywhere.
4704 if self.oTstDrv.fpApiVer < 100.0:
4705 reporter.log("Skipping updating GAs everywhere for now...");
4706 return None;
4707
4708 # Skip test for updating Guest Additions if we run on a too old (Windows) guest.
4709 ##
4710 ## @todo make it work everywhere!
4711 ##
4712 if oTestVm.sKind in ('WindowsNT4', 'Windows2000', 'WindowsXP', 'Windows2003'):
4713 reporter.log("Skipping updating GAs on old windows vm (sKind=%s)" % (oTestVm.sKind,));
4714 return (None, oTxsSession);
4715 if oTestVm.isOS2():
4716 reporter.log("Skipping updating GAs on OS/2 guest");
4717 return (None, oTxsSession);
4718
4719 sVBoxValidationKitIso = self.oTstDrv.sVBoxValidationKitIso;
4720 if not os.path.isfile(sVBoxValidationKitIso):
4721 return reporter.log('Validation Kit .ISO not found at "%s"' % (sVBoxValidationKitIso,));
4722
4723 sScratch = os.path.join(self.oTstDrv.sScratchPath, "testGctrlUpdateAdditions");
4724 try:
4725 os.makedirs(sScratch);
4726 except OSError as e:
4727 if e.errno != errno.EEXIST:
4728 return reporter.error('Failed: Unable to create scratch directory \"%s\"' % (sScratch,));
4729 reporter.log('Scratch path is: %s' % (sScratch,));
4730
4731 atTests = [];
4732 if oTestVm.isWindows():
4733 atTests.extend([
4734 # Source is missing.
4735 [ tdTestUpdateAdditions(sSrc = ''), tdTestResultFailure() ],
4736
4737 # Wrong flags.
4738 [ tdTestUpdateAdditions(sSrc = self.oTstDrv.getGuestAdditionsIso(),
4739 afFlags = [ 1234 ]), tdTestResultFailure() ],
4740
4741 # Non-existing .ISO.
4742 [ tdTestUpdateAdditions(sSrc = "non-existing.iso"), tdTestResultFailure() ],
4743
4744 # Wrong .ISO.
4745 [ tdTestUpdateAdditions(sSrc = sVBoxValidationKitIso), tdTestResultFailure() ],
4746
4747 # The real thing.
4748 [ tdTestUpdateAdditions(sSrc = self.oTstDrv.getGuestAdditionsIso()),
4749 tdTestResultSuccess() ],
4750 # Test the (optional) installer arguments. This will extract the
4751 # installer into our guest's scratch directory.
4752 [ tdTestUpdateAdditions(sSrc = self.oTstDrv.getGuestAdditionsIso(),
4753 asArgs = [ '/extract', '/D=' + sScratch ]),
4754 tdTestResultSuccess() ]
4755 # Some debg ISO. Only enable locally.
4756 #[ tdTestUpdateAdditions(
4757 # sSrc = "V:\\Downloads\\VBoxGuestAdditions-r80354.iso"),
4758 # tdTestResultSuccess() ]
4759 ]);
4760 else:
4761 reporter.log('No OS-specific tests for non-Windows yet!');
4762
4763 fRc = True;
4764 for (i, tTest) in enumerate(atTests):
4765 oCurTest = tTest[0] # type: tdTestUpdateAdditions
4766 oCurRes = tTest[1] # type: tdTestResult
4767 reporter.log('Testing #%d, sSrc="%s", afFlags="%s" ...' % (i, oCurTest.sSrc, oCurTest.afFlags,));
4768
4769 oCurTest.setEnvironment(oSession, oTxsSession, oTestVm);
4770 fRc, _ = oCurTest.createSession('Test #%d' % (i,));
4771 if fRc is not True:
4772 fRc = reporter.error('Test #%d failed: Could not create session' % (i,));
4773 break;
4774
4775 try:
4776 oCurProgress = oCurTest.oGuest.updateGuestAdditions(oCurTest.sSrc, oCurTest.asArgs, oCurTest.afFlags);
4777 except:
4778 reporter.maybeErrXcpt(oCurRes.fRc, 'Updating Guest Additions exception for sSrc="%s", afFlags="%s":'
4779 % (oCurTest.sSrc, oCurTest.afFlags,));
4780 fRc = False;
4781 else:
4782 if oCurProgress is not None:
4783 oWrapperProgress = vboxwrappers.ProgressWrapper(oCurProgress, self.oTstDrv.oVBoxMgr,
4784 self.oTstDrv, "gctrlUpGA");
4785 oWrapperProgress.wait();
4786 if not oWrapperProgress.isSuccess():
4787 oWrapperProgress.logResult(fIgnoreErrors = not oCurRes.fRc);
4788 fRc = False;
4789 else:
4790 fRc = reporter.error('No progress object returned');
4791
4792 oCurTest.closeSession();
4793 if fRc is oCurRes.fRc:
4794 if fRc:
4795 ## @todo Verify if Guest Additions were really updated (build, revision, ...).
4796 ## @todo r=bird: Not possible since you're installing the same GAs as before...
4797 ## Maybe check creation dates on certain .sys/.dll/.exe files?
4798 pass;
4799 else:
4800 fRc = reporter.error('Test #%d failed: Got %s, expected %s' % (i, fRc, oCurRes.fRc));
4801 break;
4802
4803 return (fRc, oTxsSession);
4804
4805
4806
4807class tdAddGuestCtrl(vbox.TestDriver): # pylint: disable=too-many-instance-attributes,too-many-public-methods
4808 """
4809 Guest control using VBoxService on the guest.
4810 """
4811
4812 def __init__(self):
4813 vbox.TestDriver.__init__(self);
4814 self.oTestVmSet = self.oTestVmManager.getSmokeVmSet('nat');
4815 self.asRsrcs = None;
4816 self.fQuick = False; # Don't skip lengthly tests by default.
4817 self.addSubTestDriver(SubTstDrvAddGuestCtrl(self));
4818
4819 #
4820 # Overridden methods.
4821 #
4822 def showUsage(self):
4823 """
4824 Shows the testdriver usage.
4825 """
4826 rc = vbox.TestDriver.showUsage(self);
4827 reporter.log('');
4828 reporter.log('tdAddGuestCtrl Options:');
4829 reporter.log(' --quick');
4830 reporter.log(' Same as --virt-modes hwvirt --cpu-counts 1.');
4831 return rc;
4832
4833 def parseOption(self, asArgs, iArg): # pylint: disable=too-many-branches,too-many-statements
4834 """
4835 Parses the testdriver arguments from the command line.
4836 """
4837 if asArgs[iArg] == '--quick':
4838 self.parseOption(['--virt-modes', 'hwvirt'], 0);
4839 self.parseOption(['--cpu-counts', '1'], 0);
4840 self.fQuick = True;
4841 else:
4842 return vbox.TestDriver.parseOption(self, asArgs, iArg);
4843 return iArg + 1;
4844
4845 def actionConfig(self):
4846 if not self.importVBoxApi(): # So we can use the constant below.
4847 return False;
4848
4849 eNic0AttachType = vboxcon.NetworkAttachmentType_NAT;
4850 sGaIso = self.getGuestAdditionsIso();
4851 return self.oTestVmSet.actionConfig(self, eNic0AttachType = eNic0AttachType, sDvdImage = sGaIso);
4852
4853 def actionExecute(self):
4854 return self.oTestVmSet.actionExecute(self, self.testOneCfg);
4855
4856 #
4857 # Test execution helpers.
4858 #
4859 def testOneCfg(self, oVM, oTestVm): # pylint: disable=too-many-statements
4860 """
4861 Runs the specified VM thru the tests.
4862
4863 Returns a success indicator on the general test execution. This is not
4864 the actual test result.
4865 """
4866
4867 self.logVmInfo(oVM);
4868
4869 fRc = True;
4870 oSession, oTxsSession = self.startVmAndConnectToTxsViaTcp(oTestVm.sVmName, fCdWait = False);
4871 reporter.log("TxsSession: %s" % (oTxsSession,));
4872 if oSession is not None:
4873 self.addTask(oTxsSession);
4874
4875 fManual = False; # Manual override for local testing. (Committed version shall be False.)
4876 if not fManual:
4877 fRc, oTxsSession = self.aoSubTstDrvs[0].testIt(oTestVm, oSession, oTxsSession);
4878 else:
4879 fRc, oTxsSession = self.testGuestCtrlManual(oSession, oTxsSession, oTestVm);
4880
4881 # Cleanup.
4882 self.removeTask(oTxsSession);
4883 if not fManual:
4884 self.terminateVmBySession(oSession);
4885 else:
4886 fRc = False;
4887 return fRc;
4888
4889 def gctrlReportError(self, progress):
4890 """
4891 Helper function to report an error of a
4892 given progress object.
4893 """
4894 if progress is None:
4895 reporter.log('No progress object to print error for');
4896 else:
4897 errInfo = progress.errorInfo;
4898 if errInfo:
4899 reporter.log('%s' % (errInfo.text,));
4900 return False;
4901
4902 def gctrlGetRemainingTime(self, msTimeout, msStart):
4903 """
4904 Helper function to return the remaining time (in ms)
4905 based from a timeout value and the start time (both in ms).
4906 """
4907 if msTimeout == 0:
4908 return 0xFFFFFFFE; # Wait forever.
4909 msElapsed = base.timestampMilli() - msStart;
4910 if msElapsed > msTimeout:
4911 return 0; # No time left.
4912 return msTimeout - msElapsed;
4913
4914 def testGuestCtrlManual(self, oSession, oTxsSession, oTestVm): # pylint: disable=too-many-locals,too-many-statements,unused-argument,unused-variable
4915 """
4916 For manually testing certain bits.
4917 """
4918
4919 reporter.log('Manual testing ...');
4920 fRc = True;
4921
4922 sUser = 'Administrator';
4923 sPassword = 'password';
4924
4925 oGuest = oSession.o.console.guest;
4926 oGuestSession = oGuest.createSession(sUser,
4927 sPassword,
4928 "", "Manual Test");
4929
4930 aWaitFor = [ vboxcon.GuestSessionWaitForFlag_Start ];
4931 _ = oGuestSession.waitForArray(aWaitFor, 30 * 1000);
4932
4933 sCmd = SubTstDrvAddGuestCtrl.getGuestSystemShell(oTestVm);
4934 asArgs = [ sCmd, '/C', 'dir', '/S', 'c:\\windows' ];
4935 aEnv = [];
4936 afFlags = [];
4937
4938 for _ in xrange(100):
4939 oProc = oGuestSession.processCreate(sCmd, asArgs if self.fpApiVer >= 5.0 else asArgs[1:],
4940 aEnv, afFlags, 30 * 1000);
4941
4942 aWaitFor = [ vboxcon.ProcessWaitForFlag_Terminate ];
4943 _ = oProc.waitForArray(aWaitFor, 30 * 1000);
4944
4945 oGuestSession.close();
4946 oGuestSession = None;
4947
4948 time.sleep(5);
4949
4950 oSession.o.console.PowerDown();
4951
4952 return (fRc, oTxsSession);
4953
4954if __name__ == '__main__':
4955 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