1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tradefed.device; 18 19 import com.android.ddmlib.IDevice; 20 import com.android.ddmlib.IShellOutputReceiver; 21 22 import org.easymock.EasyMock; 23 import org.easymock.IAnswer; 24 25 class MockDeviceHelper { 26 /** 27 * Helper method to build a response to a {@link IDevice#executeShellCommand(String, 28 * IShellOutputReceiver)} call. 29 * 30 * @param mockDevice the EasyMock created {@link IDevice} 31 * @param expectedCommand the shell command to expect or null to skip verification of command 32 * @param response the response to simulate 33 * @param asStub whether to set a single expectation or a stub expectation. A 'stub' expectation 34 * will return the same result for multiple calls to the method 35 */ 36 @SuppressWarnings("unchecked") 37 static void injectShellResponse( 38 IDevice mockDevice, final String expectedCommand, final String response, boolean asStub) 39 throws Exception { 40 IAnswer<Object> shellAnswer = 41 new IAnswer<Object>() { 42 @Override 43 public Object answer() throws Throwable { 44 IShellOutputReceiver receiver = 45 (IShellOutputReceiver) EasyMock.getCurrentArguments()[1]; 46 byte[] inputData = response.getBytes(); 47 receiver.addOutput(inputData, 0, inputData.length); 48 receiver.flush(); 49 return null; 50 } 51 }; 52 if (expectedCommand != null) { 53 mockDevice.executeShellCommand( 54 EasyMock.eq(expectedCommand), EasyMock.<IShellOutputReceiver>anyObject()); 55 } else { 56 mockDevice.executeShellCommand( 57 EasyMock.<String>anyObject(), EasyMock.<IShellOutputReceiver>anyObject()); 58 } 59 if (asStub) { 60 EasyMock.expectLastCall().andStubAnswer(shellAnswer); 61 } else { 62 EasyMock.expectLastCall().andAnswer(shellAnswer); 63 } 64 } 65 } 66