def testOk(self): mock_passphrase = 'random keychain passphrase' mock_full_keychain = self.mox.CreateMockAnything() mock_full_keychain_file = self.mox.CreateMockAnything() mock_pub_keychain = self.mox.CreateMockAnything() mock_pub_keychain_file = self.mox.CreateMockAnything() open_ = self.mox.CreateMockAnything() self.mox.StubOutWithMock(base64, 'b32encode') self.mox.StubOutWithMock(util, 'Exec') self.mox.StubOutWithMock(keychain, 'Remove') base64.b32encode(mox.IsA(basestring)).AndReturn(mock_passphrase) util.Exec(mox.In('/usr/bin/certtool'), mox.IsA(basestring)).AndReturn( (0, '', '')) open_(mox.IsA(basestring), 'r').AndReturn(mock_full_keychain_file) mock_full_keychain_file.read().AndReturn(mock_full_keychain) keychain.Remove() util.Exec(mox.In('/usr/bin/security')).AndReturn((0, '', '')) util.Exec(mox.In('/usr/bin/certtool')).AndReturn((0, '', '')) open_(mox.IsA(basestring), 'r').AndReturn(mock_pub_keychain_file) mock_pub_keychain_file.read().AndReturn(mock_pub_keychain) mox.Replay(open_) self.mox.ReplayAll() self.assertEquals( (mock_pub_keychain, mock_full_keychain, mock_passphrase), keychain.Create(open_=open_)) self.mox.VerifyAll() mox.Verify(open_)
def _mockRpcUtils(self, to_return, control_file_substring=''): """Fake out the autotest rpc_utils module with a mockable class. @param to_return: the value that rpc_utils.create_job_common() should be mocked out to return. @param control_file_substring: A substring that is expected to appear in the control file output string that is passed to create_job_common. Default: '' """ download_started_time = constants.DOWNLOAD_STARTED_TIME payload_finished_time = constants.PAYLOAD_FINISHED_TIME self.mox.StubOutWithMock(rpc_utils, 'create_job_common') rpc_utils.create_job_common( mox.And(mox.StrContains(self._NAME), mox.StrContains(self._BUILD)), priority=self._PRIORITY, timeout_mins=self._TIMEOUT * 60, max_runtime_mins=self._TIMEOUT * 60, control_type='Server', control_file=mox.And(mox.StrContains(self._BOARD), mox.StrContains(self._BUILD), mox.StrContains(control_file_substring)), hostless=True, keyvals=mox.And( mox.In(download_started_time), mox.In(payload_finished_time))).AndReturn(to_return)
def testGetCoreStorageStateEnabled(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_ENABLED) pl2 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LVF_INFO_ENABLED) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl2) self.mox.ReplayAll() self.assertEquals(corestorage.GetState(), corestorage.State.enabled) self.mox.VerifyAll()
def testGetCoreStorageStateFailed(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_ENABLED) pl2 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LVF_INFO_ENABLED) pl3 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LV_INFO) pl3['CoreStorageLogicalVolumeConversionState'] = 'Failed' util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl2) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl3) self.mox.ReplayAll() self.assertEquals(corestorage.GetState(), corestorage.State.FAILED) self.mox.VerifyAll()
def testIsBootVolumeEncryptedWhenNotCoreStorage(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') corestorage.util.GetPlistFromExec(mox.In(DISKUTIL)).AndRaise( util.ExecError) self.mox.ReplayAll() self.assertEquals(False, corestorage.IsBootVolumeEncrypted()) self.mox.VerifyAll()
def testGetRecoveryPartition(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') pl = plistlib.readPlistFromString(DISKUTIL_LIST_PLIST) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) self.mox.ReplayAll() self.assertEquals(corestorage.GetRecoveryPartition(), '/dev/disk0s3') self.mox.VerifyAll()
def testGetRecoveryPartitionWhenDiskutilFail(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') util.GetPlistFromExec(mox.In(DISKUTIL)).AndRaise( corestorage.util.ExecError) self.mox.ReplayAll() self.assertEquals(corestorage.GetRecoveryPartition(), None) self.mox.VerifyAll()
def testGetCoreStorageStateNone(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_EMPTY) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) self.mox.ReplayAll() self.assertEquals(corestorage.GetState(), corestorage.State.NONE) self.mox.VerifyAll()
def testFullBeaconShowerShowsAllAvailable(self): """Test that if there are a few results, FullBeaconShower shows them.""" self.mox.StubOutWithMock(record_results.FullResultRecord, 'all') # Object under test: results_show_handler = record_results.FullBeaconShower() self.SetupRequestHandlerObjs(results_show_handler) # Ask for all FullResultRecord datastore records: ps_result_query = self.mox.CreateMockAnything() record_results.FullResultRecord.all().AndReturn(ps_result_query) ps_result_all = self.mox.CreateMockAnything() ps_result_query.order('-time_received').AndReturn(ps_result_all) # The fetch returns two objects. ps_result_all.fetch(mox.IsA(int)).AndReturn([{}, {}]) # Check that the template is told that there are no results. self.mox.StubOutWithMock(template, 'render') template.render( mox.IsA(str), # The path to the template. # Test that the template dictionary has {numresults = 0} mox.And(mox.IsA(dict), mox.In('num_results'), mox.Func(lambda d: d['num_results'] == 2)), ).AndReturn('Render This String') results_show_handler.response.out.write('Render This String') self.mox.ReplayAll() results_show_handler.get() self.mox.VerifyAll()
def testAdvancedUsage(self): """And should work with other Comparators. Note: this test is reliant on In and ContainsKeyValue. """ test_dict = {"mock" : "obj", "testing" : "isCOOL"} self.assert_(mox.And(mox.In("testing"), mox.ContainsKeyValue("mock", "obj")) == test_dict)
def testGetVolumeSize(self): mock_uuid = str(uuid.uuid4()) self.mox.StubOutWithMock(corestorage.util, 'GetPlistFromExec') pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LV_INFO) corestorage.util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) self.mox.ReplayAll() self.assertEqual('55.00 GiB', corestorage.GetVolumeSize(mock_uuid)) self.mox.VerifyAll()
def testGerritQueryTruncation(self): """Verify that we detect gerrit truncating our query, and handle it.""" query1 = self.mox.CreateMock(cros_build_lib.CommandResult) query1.output = "%s%s" % (self.merged_record * 500, self.footer_template % {'count':500}) query2 = self.mox.CreateMock(cros_build_lib.CommandResult) query2.output = '%s%s' % (self.merged_record * 313, self.footer_template % {'count':313}) self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') cros_build_lib.RunCommand(mox.In('gerrit.chromium.org'), redirect_stdout=True).AndReturn(query1) cros_build_lib.RunCommand(mox.In('resume_sortkey:00166e8700001052'), redirect_stdout=True).AndReturn(query2) self.mox.ReplayAll() helper = self._GetHelper() changes = helper.Query('monkeys') self.assertEqual(len(changes), 813)
def exc_retrier_sequence(self, exc_id=None, timestamp=None, exc_count=None): self.exception_to_raise().AndReturn( Exception('unexpected %d' % exc_id)) time.time().AndReturn(timestamp) if exc_count != 0: logging.exception(mox.In( 'Unexpected exception occurred %d time(s)' % exc_count))
def testUnlockVolumeOk(self): mock_uuid = str(uuid.uuid4()) mock_passphrase = str(uuid.uuid4()) self.mox.StubOutWithMock(corestorage.util, 'Exec') corestorage.util.Exec(mox.In(DISKUTIL), stdin=mock_passphrase).AndReturn((0, '', '')) self.mox.ReplayAll() corestorage.UnlockVolume(mock_uuid, mock_passphrase) self.mox.VerifyAll()
def testAuthFail(self): mock_exc = glue.util.ExecError(returncode=self.RETURN_AUTH_FAIL) glue.util.GetPlistFromExec(mox.In(self.PATH), stdin=mox.StrContains( self.mock_pass)).AndRaise(mock_exc) self.mox.ReplayAll() self.assertRaises(glue.InputError, glue.ApplyEncryption, self.mock_fvclient, self.mock_user, self.mock_pass) self.mox.VerifyAll()
def testUnlockVolumeCantUnlock(self): mock_uuid = str(uuid.uuid4()) mock_passphrase = str(uuid.uuid4()) self.mox.StubOutWithMock(corestorage.util, 'Exec') corestorage.util.Exec(mox.In(DISKUTIL), stdin=mock_passphrase).AndReturn((1, '', '')) self.mox.ReplayAll() self.assertRaises(corestorage.CouldNotUnlockError, corestorage.UnlockVolume, mock_uuid, mock_passphrase) self.mox.VerifyAll()
def testIsBootVolumeEncryptedWhenNoLVFInfo(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') lvf_uuid = 'bad uuid' corestorage.util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn( {'MemberOfCoreStorageLogicalVolumeFamily': lvf_uuid}) corestorage.util.GetPlistFromExec((DISKUTIL, 'cs', 'info', '-plist', lvf_uuid)).AndRaise(util.ExecError) self.mox.ReplayAll() self.assertEquals(False, corestorage.IsBootVolumeEncrypted()) self.mox.VerifyAll()
def testIsBootVolumeEncryptedWhenEncrypted(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') lvf_uuid = 'bad uuid' corestorage.util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn( {'MemberOfCoreStorageLogicalVolumeFamily': lvf_uuid}) corestorage.util.GetPlistFromExec( (DISKUTIL, 'cs', 'info', '-plist', lvf_uuid)).AndReturn( {'CoreStorageLogicalVolumeFamilyEncryptionType': 'AES-XTS'}) self.mox.ReplayAll() self.assertEquals(True, corestorage.IsBootVolumeEncrypted()) self.mox.VerifyAll()
def testUnlockVolumeAlreadyUnlockedYosemite(self): mock_uuid = str(uuid.uuid4()) mock_passphrase = str(uuid.uuid4()) self.mox.StubOutWithMock(corestorage.util, 'Exec') corestorage.util.Exec( mox.In(DISKUTIL), stdin=mock_passphrase).AndReturn( (1, '', '%s is already unlocked and is attached as disk1' % mock_uuid)) self.mox.ReplayAll() corestorage.UnlockVolume(mock_uuid, mock_passphrase) self.mox.VerifyAll()
def testUnlockVolumeAlreadyUnlockedMavericks(self): mock_uuid = str(uuid.uuid4()) mock_passphrase = str(uuid.uuid4()) self.mox.StubOutWithMock(corestorage.util, 'Exec') corestorage.util.Exec( mox.In(DISKUTIL), stdin=mock_passphrase).AndReturn( (1, '', 'Error beginning CoreStorage Logical Volume unlock: ' 'The target Core Storage volume is not locked (-69748)')) self.mox.ReplayAll() corestorage.UnlockVolume(mock_uuid, mock_passphrase) self.mox.VerifyAll()
def testIsChangeCommitted(self): """Tests that we can parse a json to check if a change is committed.""" changeid = 'Ia6e663415c004bdaa77101a7e3258657598b0468' changeid_bad = 'I97663415c004bdaa77101a7e3258657598b0468' fake_result_from_gerrit = self.mox.CreateMock(cros_build_lib.CommandResult) fake_result_from_gerrit.output = self.merged_change fake_bad_result_from_gerrit = self.mox.CreateMock( cros_build_lib.CommandResult) fake_bad_result_from_gerrit.output = self.no_results self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') cros_build_lib.RunCommand(mox.In('change:%s' % changeid), redirect_stdout=True).AndReturn( fake_result_from_gerrit) cros_build_lib.RunCommand(mox.In('change:%s' % changeid_bad), redirect_stdout=True).AndReturn( fake_bad_result_from_gerrit) self.mox.ReplayAll() helper = self._GetHelper() self.assertTrue(helper.IsChangeCommitted(changeid)) self.assertFalse(helper.IsChangeCommitted(changeid_bad, must_match=False)) self.mox.VerifyAll()
def testAuthFail(self): self._Prep() mock_exc = glue.util.ExecError(returncode=glue.CSFDE_RETURN_AUTH_FAIL) glue.util.GetPlistFromExec( mox.In(self.csfde_path), stdin=self.mock_pass).AndRaise(mock_exc) self.mox.ReplayAll() self.assertRaises( glue.InputError, glue.ApplyEncryption, self.mock_fvclient, self.mock_user, self.mock_pass) self.mox.VerifyAll()
def testBranchSpecifiedNoChanges(self): """Test when no changes on the branch specified by user.""" output_obj = self.mox.CreateMock(cros_build_lib.CommandResult) output_obj.output = '' self.manifest.GetProjectPath('my/project', True).AndReturn('mydir') self.manifest.GetProjectsLocalRevision('my/project').AndReturn( 'm/master') self.manifest.GetAttributeForProject('my/project', 'remote').AndReturn('cros') git.RunGit('mydir', mox.In('m/master..mybranch')).AndReturn(output_obj) self.mox.ReplayAll() self.assertRaises(SystemExit, cros_patch.PrepareLocalPatches, self.manifest, self.patches)
def _test_missing(self, patches): output_obj = cros_build_lib.CommandResult() output_obj.returncode = 0 output_obj.output = '%s\n%s\n%s' % \ (self.raw_json, self.raw_json, self.good_footer) cros_build_lib.RunCommand(mox.In('gerrit.chromium.org'), redirect_stdout=True).AndReturn(output_obj) self.mox.ReplayAll() self.assertRaises(gerrit.GerritException, gerrit.GetGerritPatchInfo, patches) self.mox.VerifyAll()
def testGenericFail(self): self.mox.StubOutWithMock(logging, 'error') mock_exc = glue.util.ExecError(returncode=1) glue.util.GetPlistFromExec(mox.In(self.PATH), stdin=mox.StrContains( self.mock_pass)).AndRaise(mock_exc) logging.error(mox.IsA(basestring), mox.IsA(basestring), mox.IgnoreArg()) self.mox.ReplayAll() self.assertRaises(glue.Error, glue.ApplyEncryption, self.mock_fvclient, self.mock_user, self.mock_pass) self.mox.VerifyAll()
def testParseFakeResults(self): """Parses our own fake gerrit query results to verify we parse correctly.""" fake_result = self.mox.CreateMock(cros_build_lib.CommandResult) fake_result.output = self.results self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') cros_build_lib.RunCommand(mox.In('gerrit.chromium.org'), redirect_stdout=True).AndReturn(fake_result) self.mox.ReplayAll() helper = self._GetHelper() changes = helper.Query("monkey") self.assertEqual(set(x.change_id for x in changes), set(['Iee5c89d929f1850d7d4e1a4ff5f21adda800025f', 'Iee5c89d929f1850d7d4e1a4ff5f21adda800025d', 'Iee5c89d929f1850d7d4e1a4ff5f21adda800025e'])) self.mox.VerifyAll()
def testParseFakeResultsWithInternalURL(self): """Parses our own fake gerrit query results but sets internal bit.""" fake_result = self.mox.CreateMock(cros_build_lib.CommandResult) fake_result.output = self.results self.mox.StubOutWithMock(cros_build_lib, 'RunCommand') cros_build_lib.RunCommand(mox.In('gerrit-int.chromium.org'), redirect_stdout=True).AndReturn(fake_result) self.mox.ReplayAll() helper = self._GetHelper(constants.INTERNAL_REMOTE) changes = helper.Query("monkeys") self.assertEqual(set(x.change_id for x in changes), set(['Iee5c89d929f1850d7d4e1a4ff5f21adda800025f', 'Iee5c89d929f1850d7d4e1a4ff5f21adda800025d', 'Iee5c89d929f1850d7d4e1a4ff5f21adda800025e'])) self.mox.VerifyAll()
def testOk(self): self._Prep() pl = plistlib.readPlistFromString(CSFDE_OUTPUT) glue.util.GetPlistFromExec( mox.In(self.csfde_path), stdin=self.mock_pass).AndReturn(pl) self.mock_fvclient.SetOwner(self.mock_user) glue.GetEncryptionResults(pl).AndReturn( ('volume_uuid', 'recovery_token')) self.mox.ReplayAll() result = glue.ApplyEncryption( self.mock_fvclient, self.mock_user, self.mock_pass) self.assertEquals(('volume_uuid', 'recovery_token'), result) self.mox.VerifyAll()
def _common_test(self, patches, server='gerrit.chromium.org', remote=constants.EXTERNAL_REMOTE, calls_allowed=1): output_obj = cros_build_lib.CommandResult() output_obj.returncode = 0 output_obj.output = self.result for _ in xrange(calls_allowed): cros_build_lib.RunCommand(mox.In(server), redirect_stdout=True).AndReturn(output_obj) self.mox.ReplayAll() patch_info = gerrit.GetGerritPatchInfo(patches) self.assertEquals(patch_info[0].remote, remote) self.mox.VerifyAll() return patch_info
def testPatchNotFound1(self): """Test case where ChangeID isn't found on internal server.""" patches = ['Icb8e1d315d465a07'] output_obj = cros_build_lib.CommandResult() output_obj.returncode = 0 output_obj.output = ('{"type":"error",' '"message":"Unsupported query:5S2D4D2D4"}') cros_build_lib.RunCommand(mox.In('gerrit.chromium.org'), redirect_stdout=True).AndReturn(output_obj) self.mox.ReplayAll() self.assertRaises(gerrit.GerritException, gerrit.GetGerritPatchInfo, patches) self.mox.VerifyAll()