Home | History | Annotate | Download | only in targetprep
      1 /*
      2  * Copyright (C) 2010 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.targetprep;
     18 
     19 import com.android.tradefed.build.DeviceBuildInfo;
     20 import com.android.tradefed.build.IDeviceBuildInfo;
     21 import com.android.tradefed.command.remote.DeviceDescriptor;
     22 import com.android.tradefed.device.DeviceNotAvailableException;
     23 import com.android.tradefed.device.ITestDevice;
     24 import com.android.tradefed.device.TestDeviceState;
     25 import com.android.tradefed.targetprep.IDeviceFlasher.UserDataFlashOption;
     26 import com.android.tradefed.util.ArrayUtil;
     27 import com.android.tradefed.util.CommandResult;
     28 import com.android.tradefed.util.CommandStatus;
     29 import com.android.tradefed.util.FileUtil;
     30 import com.android.tradefed.util.IRunUtil;
     31 
     32 import junit.framework.TestCase;
     33 
     34 import org.easymock.EasyMock;
     35 
     36 import java.io.BufferedReader;
     37 import java.io.File;
     38 import java.io.IOException;
     39 import java.io.StringReader;
     40 import java.util.ArrayList;
     41 import java.util.Arrays;
     42 
     43 /**
     44  * Unit tests for {@link FastbootDeviceFlasher}.
     45  */
     46 public class FastbootDeviceFlasherTest extends TestCase {
     47 
     48     /** a temp 'don't care value' string to use */
     49     private static final String TEST_STRING = "foo";
     50     private FastbootDeviceFlasher mFlasher;
     51     private ITestDevice mMockDevice;
     52     private IDeviceBuildInfo mMockBuildInfo;
     53     private IFlashingResourcesRetriever mMockRetriever;
     54     private IFlashingResourcesParser mMockParser;
     55     private IRunUtil mMockRunUtil;
     56 
     57     /**
     58      * {@inheritDoc}
     59      */
     60     @Override
     61     protected void setUp() throws Exception {
     62         super.setUp();
     63         mMockDevice = EasyMock.createMock(ITestDevice.class);
     64         EasyMock.expect(mMockDevice.getSerialNumber()).andStubReturn(TEST_STRING);
     65         EasyMock.expect(mMockDevice.getProductType()).andStubReturn(TEST_STRING);
     66         EasyMock.expect(mMockDevice.getBuildId()).andStubReturn("1");
     67         EasyMock.expect(mMockDevice.getBuildFlavor()).andStubReturn("test-debug");
     68         EasyMock.expect(mMockDevice.getDeviceDescriptor()).andStubReturn(null);
     69         mMockBuildInfo = new DeviceBuildInfo("0", TEST_STRING);
     70         mMockBuildInfo.setDeviceImageFile(new File(TEST_STRING), "0");
     71         mMockBuildInfo.setUserDataImageFile(new File(TEST_STRING), "0");
     72         mMockRetriever = EasyMock.createNiceMock(IFlashingResourcesRetriever.class);
     73         mMockParser = EasyMock.createNiceMock(IFlashingResourcesParser.class);
     74         mMockRunUtil = EasyMock.createMock(IRunUtil.class);
     75 
     76         mFlasher = new FastbootDeviceFlasher() {
     77             @Override
     78             protected IFlashingResourcesParser createFlashingResourcesParser(
     79                     IDeviceBuildInfo localBuild, DeviceDescriptor descriptor) {
     80                 return mMockParser;
     81             }
     82             @Override
     83             protected IRunUtil getRunUtil() {
     84                 return mMockRunUtil;
     85             }
     86         };
     87         mFlasher.setFlashingResourcesRetriever(mMockRetriever);
     88         mFlasher.setUserDataFlashOption(UserDataFlashOption.RETAIN);
     89     }
     90 
     91     /**
     92      * Test {@link FastbootDeviceFlasher#flash(ITestDevice, IDeviceBuildInfo)}
     93      * when device is not available.
     94      */
     95     public void testFlash_deviceNotAvailable() throws DeviceNotAvailableException  {
     96        try {
     97             mMockDevice.rebootIntoBootloader();
     98             // TODO: this is fixed to two arguments - how to set to expect a variable arg amount ?
     99             mMockDevice.executeFastbootCommand((String)EasyMock.anyObject(),
    100                     (String)EasyMock.anyObject());
    101             EasyMock.expectLastCall().andThrow(new DeviceNotAvailableException());
    102             EasyMock.replay(mMockDevice);
    103             mFlasher.flash(mMockDevice, mMockBuildInfo);
    104             fail("TargetSetupError not thrown");
    105         } catch (TargetSetupError e) {
    106             // expected
    107         }
    108     }
    109 
    110     /**
    111      * Test DeviceFlasher#flash(ITestDevice, IDeviceBuildInfo)} when required board info is not
    112      * present.
    113      */
    114     public void testFlash_missingBoard() throws DeviceNotAvailableException  {
    115         mMockDevice.rebootIntoBootloader();
    116         EasyMock.expect(mMockParser.getRequiredBoards()).andReturn(null);
    117         EasyMock.replay(mMockDevice);
    118         try {
    119             mFlasher.flash(mMockDevice, mMockBuildInfo);
    120             fail("TargetSetupError not thrown");
    121         } catch (TargetSetupError e) {
    122             // expected
    123         }
    124     }
    125 
    126     /**
    127      * Test {@link FastbootDeviceFlasher#getImageVersion(ITestDevice, String)}
    128      */
    129     public void testGetImageVersion() throws DeviceNotAvailableException, TargetSetupError {
    130         CommandResult fastbootResult = new CommandResult();
    131         fastbootResult.setStatus(CommandStatus.SUCCESS);
    132         // output of getvar is on stderr for some unknown reason
    133         fastbootResult.setStderr("version-bootloader: 1.0.1\nfinished. total time: 0.001s");
    134         fastbootResult.setStdout("");
    135         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "version-bootloader")).
    136                 andReturn(fastbootResult);
    137         EasyMock.replay(mMockDevice, mMockRunUtil);
    138         String actualVersion = mFlasher.getImageVersion(mMockDevice, "bootloader");
    139         assertEquals("1.0.1", actualVersion);
    140         EasyMock.verify(mMockDevice, mMockRunUtil);
    141     }
    142 
    143     /**
    144      * Test {@link FastbootDeviceFlasher#getCurrentSlot(ITestDevice)} when device is in fastboot.
    145      */
    146     public void testGetCurrentSlot_fastboot() throws DeviceNotAvailableException, TargetSetupError {
    147         CommandResult fastbootResult = new CommandResult();
    148         fastbootResult.setStatus(CommandStatus.SUCCESS);
    149         fastbootResult.setStderr("current-slot: _a\nfinished. total time 0.001s");
    150         fastbootResult.setStdout("");
    151         EasyMock.expect(mMockDevice.getDeviceState()).andReturn(TestDeviceState.FASTBOOT);
    152         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "current-slot"))
    153                 .andReturn(fastbootResult);
    154         EasyMock.replay(mMockDevice, mMockRunUtil);
    155         String currentSlot = mFlasher.getCurrentSlot(mMockDevice);
    156         assertEquals("a", currentSlot);
    157         EasyMock.verify(mMockDevice, mMockRunUtil);
    158     }
    159 
    160     /** Test {@link FastbootDeviceFlasher#getCurrentSlot(ITestDevice)} when device is in adb. */
    161     public void testGetCurrentSlot_adb() throws DeviceNotAvailableException, TargetSetupError {
    162         String adbResult = "[ro.boot.slot_suffix]: [_b]\n";
    163         EasyMock.expect(mMockDevice.getDeviceState()).andReturn(TestDeviceState.ONLINE);
    164         EasyMock.expect(mMockDevice.executeShellCommand("getprop ro.boot.slot_suffix"))
    165                 .andReturn(adbResult);
    166         EasyMock.replay(mMockDevice, mMockRunUtil);
    167         String currentSlot = mFlasher.getCurrentSlot(mMockDevice);
    168         assertEquals("b", currentSlot);
    169         EasyMock.verify(mMockDevice, mMockRunUtil);
    170     }
    171 
    172     /**
    173      * Test {@link FastbootDeviceFlasher#getCurrentSlot(ITestDevice)} when device does not support
    174      * A/B.
    175      */
    176     public void testGetCurrentSlot_null() throws DeviceNotAvailableException, TargetSetupError {
    177         String adbResult = "\n";
    178         EasyMock.expect(mMockDevice.getDeviceState()).andReturn(TestDeviceState.ONLINE);
    179         EasyMock.expect(mMockDevice.executeShellCommand("getprop ro.boot.slot_suffix"))
    180                 .andReturn(adbResult);
    181         EasyMock.replay(mMockDevice, mMockRunUtil);
    182         String currentSlot = mFlasher.getCurrentSlot(mMockDevice);
    183         assertNull(currentSlot);
    184         EasyMock.verify(mMockDevice, mMockRunUtil);
    185     }
    186 
    187     /** Test that a fastboot command is retried if it does not output anything. */
    188     public void testRetryGetVersionCommand() throws DeviceNotAvailableException, TargetSetupError {
    189         // The first time command is tried, make it return an empty string.
    190         CommandResult fastbootInValidResult = new CommandResult();
    191         fastbootInValidResult.setStatus(CommandStatus.SUCCESS);
    192         // output of getvar is on stderr for some unknown reason
    193         fastbootInValidResult.setStderr("");
    194         fastbootInValidResult.setStdout("");
    195 
    196         // Return the correct value on second attempt.
    197         CommandResult fastbootValidResult = new CommandResult();
    198         fastbootValidResult.setStatus(CommandStatus.SUCCESS);
    199         fastbootValidResult.setStderr("version-baseband: 1.0.1\nfinished. total time: 0.001s");
    200         fastbootValidResult.setStdout("");
    201 
    202         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "version-baseband")).
    203                 andReturn(fastbootInValidResult);
    204         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "version-baseband")).
    205                 andReturn(fastbootValidResult);
    206         mMockRunUtil.sleep(EasyMock.anyLong());
    207         EasyMock.expectLastCall();
    208 
    209         EasyMock.replay(mMockDevice, mMockRunUtil);
    210         String actualVersion = mFlasher.getImageVersion(mMockDevice, "baseband");
    211         EasyMock.verify(mMockDevice, mMockRunUtil);
    212         assertEquals("1.0.1", actualVersion);
    213     }
    214 
    215     /**
    216      * Test that baseband can be flashed when current baseband version is empty
    217      */
    218     public void testFlashBaseband_noVersion()
    219             throws DeviceNotAvailableException, TargetSetupError {
    220         final String newBasebandVersion = "1.0.1";
    221         ITestDevice mockDevice = EasyMock.createMock(ITestDevice.class);
    222         // expect a fastboot getvar version-baseband command
    223         setFastbootResponseExpectations(mockDevice, "version-baseband: \n");
    224         setFastbootResponseExpectations(mockDevice, "version-baseband: \n");
    225         // expect a 'flash radio' command
    226         setFastbootFlashExpectations(mockDevice, "radio");
    227         mockDevice.rebootIntoBootloader();
    228         EasyMock.replay(mockDevice, mMockRunUtil);
    229 
    230         FastbootDeviceFlasher flasher = getFlasherWithParserData(
    231                 String.format("require version-baseband=%s", newBasebandVersion));
    232 
    233         IDeviceBuildInfo build = new DeviceBuildInfo("1234", "build-name");
    234         build.setBasebandImage(new File("tmp"), newBasebandVersion);
    235         flasher.checkAndFlashBaseband(mockDevice, build);
    236         EasyMock.verify(mockDevice, mMockRunUtil);
    237     }
    238 
    239     /**
    240      * Test flashing of user data with a tests zip
    241      *
    242      * @throws TargetSetupError
    243      */
    244     public void testFlashUserData_testsZip() throws DeviceNotAvailableException, TargetSetupError {
    245         mFlasher.setUserDataFlashOption(UserDataFlashOption.TESTS_ZIP);
    246 
    247         ITestsZipInstaller mockZipInstaller = EasyMock.createMock(ITestsZipInstaller.class);
    248         mFlasher.setTestsZipInstaller(mockZipInstaller);
    249         // expect
    250         mockZipInstaller.pushTestsZipOntoData(EasyMock.eq(mMockDevice), EasyMock.eq(mMockBuildInfo));
    251         // expect
    252         mMockDevice.rebootUntilOnline();
    253         mMockDevice.rebootIntoBootloader();
    254         EasyMock.expect(mMockDevice.isEncryptionSupported()).andReturn(Boolean.FALSE);
    255 
    256         EasyMock.replay(mMockDevice, mockZipInstaller);
    257         mFlasher.flashUserData(mMockDevice, mMockBuildInfo);
    258         EasyMock.verify(mMockDevice, mockZipInstaller);
    259     }
    260 
    261     /**
    262      * Verify that correct fastboot command is called with WIPE data option
    263      * @throws DeviceNotAvailableException
    264      * @throws TargetSetupError
    265      */
    266     public void testFlashUserData_wipe() throws DeviceNotAvailableException, TargetSetupError {
    267         mFlasher.setUserDataFlashOption(UserDataFlashOption.WIPE);
    268         doTestFlashWithWipe();
    269     }
    270 
    271     /**
    272      * Verify that correct fastboot command is called with FORCE_WIPE data option
    273      * @throws DeviceNotAvailableException
    274      * @throws TargetSetupError
    275      */
    276     public void testFlashUserData_forceWipe() throws DeviceNotAvailableException, TargetSetupError {
    277         mFlasher.setUserDataFlashOption(UserDataFlashOption.FORCE_WIPE);
    278         doTestFlashWithWipe();
    279     }
    280 
    281     /**
    282      * Verify call sequence when wiping cache on devices with cache partition
    283      * @throws DeviceNotAvailableException
    284      * @throws TargetSetupError
    285      */
    286     public void testWipeCache_exists() throws DeviceNotAvailableException, TargetSetupError {
    287         mFlasher.setUserDataFlashOption(UserDataFlashOption.WIPE);
    288         CommandResult fastbootOutput = new CommandResult();
    289         fastbootOutput.setStatus(CommandStatus.SUCCESS);
    290         fastbootOutput.setStderr("(bootloader) slot-count: not found\n" +
    291                 "(bootloader) slot-suffixes: not found\n" +
    292                 "(bootloader) slot-suffixes: not found\n" +
    293                 "partition-type:cache: ext4\n" +
    294                 "finished. total time: 0.002s\n");
    295         fastbootOutput.setStdout("");
    296 
    297         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "partition-type:cache")).
    298                 andReturn(fastbootOutput);
    299         EasyMock.expect(mMockDevice.getUseFastbootErase()).andReturn(false);
    300         fastbootOutput = new CommandResult();
    301         fastbootOutput.setStatus(CommandStatus.SUCCESS);
    302         fastbootOutput.setStderr("Creating filesystem with parameters:\n" +
    303                 "    Size: 104857600\n" +
    304                 "    Block size: 4096\n" +
    305                 "    Blocks per group: 32768\n" +
    306                 "    Inodes per group: 6400\n" +
    307                 "    Inode size: 256\n" +
    308                 "    Journal blocks: 1024\n" +
    309                 "    Label: \n" +
    310                 "    Blocks: 25600\n" +
    311                 "    Block groups: 1\n" +
    312                 "    Reserved block group size: 7\n" +
    313                 "Created filesystem with 11/6400 inodes and 1438/25600 blocks\n" +
    314                 "target reported max download size of 494927872 bytes\n" +
    315                 "erasing 'cache'...\n" +
    316                 "OKAY [  0.024s]\n" +
    317                 "sending 'cache' (5752 KB)...\n" +
    318                 "OKAY [  0.178s]\n" +
    319                 "writing 'cache'...\n" +
    320                 "OKAY [  0.107s]\n" +
    321                 "finished. total time: 0.309s\n");
    322         EasyMock.expect(mMockDevice.fastbootWipePartition("cache")).andReturn(fastbootOutput);
    323         EasyMock.replay(mMockDevice);
    324         mFlasher.wipeCache(mMockDevice);
    325         EasyMock.verify(mMockDevice);
    326     }
    327 
    328     /**
    329      * Verify call sequence when wiping cache on devices without cache partition
    330      * @throws DeviceNotAvailableException
    331      * @throws TargetSetupError
    332      */
    333     public void testWipeCache_not_exists() throws DeviceNotAvailableException, TargetSetupError {
    334         mFlasher.setUserDataFlashOption(UserDataFlashOption.WIPE);
    335         CommandResult fastbootOutput = new CommandResult();
    336         fastbootOutput.setStatus(CommandStatus.SUCCESS);
    337         fastbootOutput.setStderr("(bootloader) slot-count: not found\n" +
    338                 "(bootloader) slot-suffixes: not found\n" +
    339                 "(bootloader) slot-suffixes: not found\n" +
    340                 "partition-type:cache: \n" +
    341                 "finished. total time: 0.002s\n");
    342         fastbootOutput.setStdout("");
    343 
    344         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "partition-type:cache")).
    345                 andReturn(fastbootOutput);
    346         EasyMock.replay(mMockDevice);
    347         mFlasher.wipeCache(mMockDevice);
    348         EasyMock.verify(mMockDevice);
    349     }
    350 
    351     /**
    352      * Verify call sequence when wiping cache on devices without cache partition
    353      * @throws DeviceNotAvailableException
    354      * @throws TargetSetupError
    355      */
    356     public void testWipeCache_not_exists_error()
    357             throws DeviceNotAvailableException, TargetSetupError {
    358         mFlasher.setUserDataFlashOption(UserDataFlashOption.WIPE);
    359         CommandResult fastbootOutput = new CommandResult();
    360         fastbootOutput.setStatus(CommandStatus.SUCCESS);
    361         fastbootOutput.setStderr("getvar:partition-type:cache FAILED (remote: unknown command)\n" +
    362                 "finished. total time: 0.051s\n");
    363         fastbootOutput.setStdout("");
    364 
    365         EasyMock.expect(mMockDevice.executeFastbootCommand("getvar", "partition-type:cache")).
    366                 andReturn(fastbootOutput);
    367         EasyMock.replay(mMockDevice);
    368         mFlasher.wipeCache(mMockDevice);
    369         EasyMock.verify(mMockDevice);
    370     }
    371 
    372     /**
    373      * Convenience function to set expectations for `fastboot -w` and execute test
    374      * @throws DeviceNotAvailableException
    375      * @throws TargetSetupError
    376      */
    377     private void doTestFlashWithWipe()  throws DeviceNotAvailableException, TargetSetupError {
    378         CommandResult result = new CommandResult();
    379         result.setStatus(CommandStatus.SUCCESS);
    380         result.setStderr("");
    381         result.setStdout("");
    382         EasyMock.expect(mMockDevice.executeFastbootCommand(EasyMock.anyLong(),
    383                 EasyMock.eq("-w"))).andReturn(result);
    384 
    385         EasyMock.replay(mMockDevice);
    386         mFlasher.handleUserDataFlashing(mMockDevice, mMockBuildInfo);
    387         EasyMock.verify(mMockDevice);
    388     }
    389 
    390     /**
    391      * Test doing a user data with with rm
    392      *
    393      * @throws TargetSetupError
    394      */
    395     public void testFlashUserData_wipeRm() throws DeviceNotAvailableException, TargetSetupError {
    396         mFlasher.setUserDataFlashOption(UserDataFlashOption.WIPE_RM);
    397 
    398         ITestsZipInstaller mockZipInstaller = EasyMock.createMock(ITestsZipInstaller.class);
    399         mFlasher.setTestsZipInstaller(mockZipInstaller);
    400         // expect
    401         mockZipInstaller.deleteData(EasyMock.eq(mMockDevice));
    402         // expect
    403         mMockDevice.rebootUntilOnline();
    404         mMockDevice.rebootIntoBootloader();
    405 
    406         EasyMock.replay(mMockDevice, mockZipInstaller);
    407         mFlasher.flashUserData(mMockDevice, mMockBuildInfo);
    408         EasyMock.verify(mMockDevice, mockZipInstaller);
    409     }
    410 
    411     /**
    412      * Test that
    413      * {@link FastbootDeviceFlasher#downloadFlashingResources(ITestDevice, IDeviceBuildInfo)}
    414      * throws an exception when device product is null.
    415      */
    416     public void testDownloadFlashingResources_nullDeviceProduct() throws Exception {
    417         mMockDevice = EasyMock.createMock(ITestDevice.class);
    418         EasyMock.expect(mMockDevice.getDeviceDescriptor()).andStubReturn(null);
    419         EasyMock.expect(mMockDevice.getProductType()).andReturn(null);
    420         EasyMock.expect(mMockDevice.getSerialNumber()).andStubReturn(TEST_STRING);
    421         EasyMock.expect(mMockParser.getRequiredBoards()).andReturn(new ArrayList<String>());
    422         EasyMock.replay(mMockDevice, mMockParser);
    423         try {
    424             mFlasher.downloadFlashingResources(mMockDevice, mMockBuildInfo);
    425             fail("Should have thrown an exception");
    426         } catch (DeviceNotAvailableException expected) {
    427             assertEquals(String.format("Could not determine product type for device %s",
    428                     TEST_STRING), expected.getMessage());
    429         } finally {
    430             EasyMock.verify(mMockDevice, mMockParser);
    431         }
    432     }
    433 
    434     /**
    435      * Test that
    436      * {@link FastbootDeviceFlasher#downloadFlashingResources(ITestDevice, IDeviceBuildInfo)}
    437      * throws an exception when the device product is not found in required board.
    438      */
    439     public void testDownloadFlashingResources_NotFindBoard() throws Exception {
    440         final String boardName = "AWESOME_PRODUCT";
    441         mMockDevice = EasyMock.createMock(ITestDevice.class);
    442         EasyMock.expect(mMockDevice.getDeviceDescriptor()).andStubReturn(null);
    443         EasyMock.expect(mMockDevice.getProductType()).andReturn("NOT_FOUND");
    444         EasyMock.expect(mMockDevice.getSerialNumber()).andStubReturn(TEST_STRING);
    445         EasyMock.expect(mMockParser.getRequiredBoards()).andStubReturn(ArrayUtil.list(boardName));
    446         EasyMock.replay(mMockDevice, mMockParser);
    447         try {
    448             mFlasher.downloadFlashingResources(mMockDevice, mMockBuildInfo);
    449             fail("Should have thrown an exception");
    450         } catch (TargetSetupError expected) {
    451             assertEquals(String.format("Device %s is NOT_FOUND. Expected %s null",
    452                     TEST_STRING, ArrayUtil.list(boardName)), expected.getMessage());
    453         } finally {
    454             EasyMock.verify(mMockDevice, mMockParser);
    455         }
    456     }
    457 
    458     /**
    459      * Test that
    460      * {@link FastbootDeviceFlasher#downloadFlashingResources(ITestDevice, IDeviceBuildInfo)}
    461      * proceeds to the end without throwing.
    462      */
    463     public void testDownloadFlashingResources() throws Exception {
    464         final String boardName = "AWESOME_PRODUCT";
    465         mMockDevice = EasyMock.createMock(ITestDevice.class);
    466         EasyMock.expect(mMockDevice.getDeviceDescriptor()).andStubReturn(null);
    467         EasyMock.expect(mMockDevice.getProductType()).andReturn(boardName);
    468         EasyMock.expect(mMockDevice.getSerialNumber()).andStubReturn(TEST_STRING);
    469         EasyMock.expect(mMockParser.getRequiredBoards()).andStubReturn(ArrayUtil.list(boardName));
    470         EasyMock.replay(mMockDevice, mMockParser);
    471         mFlasher.downloadFlashingResources(mMockDevice, mMockBuildInfo);
    472         EasyMock.verify(mMockDevice, mMockParser);
    473     }
    474 
    475     /**
    476      * Test that
    477      * {@link FastbootDeviceFlasher#checkAndFlashBootloader(ITestDevice, IDeviceBuildInfo)} returns
    478      * false because bootloader version is already good.
    479      */
    480     public void testCheckAndFlashBootloader_SkippingFlashing() throws Exception {
    481         final String version = "version 5";
    482         mFlasher = new FastbootDeviceFlasher() {
    483             @Override
    484             protected String getImageVersion(ITestDevice device, String imageName)
    485                     throws DeviceNotAvailableException, TargetSetupError {
    486                 return version;
    487             }
    488         };
    489         IDeviceBuildInfo mockBuild = EasyMock.createMock(IDeviceBuildInfo.class);
    490         EasyMock.expect(mockBuild.getBootloaderVersion()).andStubReturn(version);
    491         EasyMock.replay(mMockDevice, mockBuild);
    492         assertFalse(mFlasher.checkAndFlashBootloader(mMockDevice, mockBuild));
    493         EasyMock.verify(mMockDevice, mockBuild);
    494     }
    495 
    496     /**
    497      * Test that
    498      * {@link FastbootDeviceFlasher#checkAndFlashBootloader(ITestDevice, IDeviceBuildInfo)} returns
    499      * true after flashing the device bootloader.
    500      */
    501     public void testCheckAndFlashBootloader() throws Exception {
    502         final String version = "version 5";
    503         mFlasher = new FastbootDeviceFlasher() {
    504             @Override
    505             protected String getImageVersion(ITestDevice device, String imageName)
    506                     throws DeviceNotAvailableException, TargetSetupError {
    507                 return "version 6";
    508             }
    509         };
    510         IDeviceBuildInfo mockBuild = EasyMock.createMock(IDeviceBuildInfo.class);
    511         EasyMock.expect(mockBuild.getBootloaderVersion()).andStubReturn(version);
    512         File bootloaderFake = FileUtil.createTempFile("fakeBootloader", "");
    513         try {
    514             EasyMock.expect(mockBuild.getBootloaderImageFile()).andReturn(bootloaderFake);
    515             CommandResult res = new CommandResult(CommandStatus.SUCCESS);
    516             res.setStderr("flashing");
    517             EasyMock.expect(mMockDevice.executeFastbootCommand(EasyMock.eq("flash"),
    518                     EasyMock.eq("hboot"), EasyMock.eq(bootloaderFake.getAbsolutePath())))
    519                     .andReturn(res);
    520             mMockDevice.rebootIntoBootloader();
    521             EasyMock.expectLastCall();
    522             EasyMock.replay(mMockDevice, mockBuild);
    523             assertTrue(mFlasher.checkAndFlashBootloader(mMockDevice, mockBuild));
    524             EasyMock.verify(mMockDevice, mockBuild);
    525         } finally {
    526             FileUtil.deleteFile(bootloaderFake);
    527         }
    528     }
    529 
    530     /**
    531      * Test {@link FastbootDeviceFlasher#checkAndFlashSystem(ITestDevice,
    532      * String, String, IDeviceBuildInfo)} when there is no need to flash the system.
    533      */
    534     public void testCheckAndFlashSystem_noFlashing() throws Exception {
    535         final String buildId = "systemBuildId";
    536         final String buildFlavor = "systemBuildFlavor";
    537         IDeviceBuildInfo mockBuild = EasyMock.createMock(IDeviceBuildInfo.class);
    538         EasyMock.expect(mockBuild.getDeviceBuildId()).andReturn(buildId);
    539         EasyMock.expect(mockBuild.getBuildFlavor()).andReturn(buildFlavor);
    540         mMockDevice.rebootUntilOnline();
    541         EasyMock.expectLastCall();
    542         EasyMock.replay(mMockDevice, mockBuild);
    543         assertFalse(mFlasher.checkAndFlashSystem(mMockDevice, buildId, buildFlavor, mockBuild));
    544         EasyMock.verify(mMockDevice, mockBuild);
    545         assertNull("system flash status should be null when partitions are not flashed",
    546                 mFlasher.getSystemFlashingStatus());
    547     }
    548 
    549     /**
    550      * Test {@link FastbootDeviceFlasher#checkAndFlashSystem(ITestDevice,
    551      * String, String, IDeviceBuildInfo)} when it needs to be flashed.
    552      */
    553     public void testCheckAndFlashSystem_flashing() throws Exception {
    554         final String buildId = "systemBuildId";
    555         IDeviceBuildInfo mockBuild = EasyMock.createMock(IDeviceBuildInfo.class);
    556         EasyMock.expect(mockBuild.getDeviceBuildId()).andReturn(buildId);
    557         File deviceImage = FileUtil.createTempFile("fakeDeviceImage", "");
    558         try {
    559             EasyMock.expect(mockBuild.getDeviceImageFile()).andStubReturn(deviceImage);
    560             CommandResult res = new CommandResult(CommandStatus.SUCCESS);
    561             res.setStderr("flashing");
    562             EasyMock.expect(mMockDevice.executeLongFastbootCommand(EasyMock.eq("update"),
    563                     EasyMock.eq(deviceImage.getAbsolutePath())))
    564                     .andReturn(res);
    565             EasyMock.replay(mMockDevice, mockBuild);
    566             assertTrue(mFlasher.checkAndFlashSystem(mMockDevice, buildId, null, mockBuild));
    567             EasyMock.verify(mMockDevice, mockBuild);
    568             assertEquals("system flashing status should be \"SUCCESS\"",
    569                     CommandStatus.SUCCESS, mFlasher.getSystemFlashingStatus());
    570         } finally {
    571             FileUtil.deleteFile(deviceImage);
    572         }
    573     }
    574 
    575     /**
    576      * Test {@link FastbootDeviceFlasher#checkAndFlashSystem(ITestDevice, String, String,
    577      * IDeviceBuildInfo)} with flash options
    578      */
    579     public void testCheckAndFlashSystem_withFlashOptions() throws Exception {
    580         mFlasher.setFlashOptions(Arrays.asList("--foo", " --bar"));
    581         final String buildId = "systemBuildId";
    582         IDeviceBuildInfo mockBuild = EasyMock.createMock(IDeviceBuildInfo.class);
    583         EasyMock.expect(mockBuild.getDeviceBuildId()).andReturn(buildId);
    584         File deviceImage = FileUtil.createTempFile("fakeDeviceImage", "");
    585         try {
    586             EasyMock.expect(mockBuild.getDeviceImageFile()).andStubReturn(deviceImage);
    587             CommandResult res = new CommandResult(CommandStatus.SUCCESS);
    588             res.setStderr("flashing");
    589             EasyMock.expect(
    590                             mMockDevice.executeLongFastbootCommand(
    591                                     EasyMock.eq("--foo"),
    592                                     EasyMock.eq("--bar"),
    593                                     EasyMock.eq("update"),
    594                                     EasyMock.eq(deviceImage.getAbsolutePath())))
    595                     .andReturn(res);
    596             EasyMock.replay(mMockDevice, mockBuild);
    597             assertTrue(mFlasher.checkAndFlashSystem(mMockDevice, buildId, null, mockBuild));
    598             EasyMock.verify(mMockDevice, mockBuild);
    599             assertEquals(
    600                     "system flashing status should be \"SUCCESS\"",
    601                     CommandStatus.SUCCESS,
    602                     mFlasher.getSystemFlashingStatus());
    603         } finally {
    604             FileUtil.deleteFile(deviceImage);
    605         }
    606     }
    607 
    608     /**
    609      * Test {@link FastbootDeviceFlasher#checkAndFlashSystem(ITestDevice, String, String,
    610      * IDeviceBuildInfo)} when it needs to be flashed but throws an exception.
    611      */
    612     public void testCheckAndFlashSystem_exception() throws Exception {
    613         final String buildId = "systemBuildId";
    614         IDeviceBuildInfo mockBuild = EasyMock.createMock(IDeviceBuildInfo.class);
    615         EasyMock.expect(mockBuild.getDeviceBuildId()).andReturn(buildId);
    616         File deviceImage = FileUtil.createTempFile("fakeDeviceImage", "");
    617         try {
    618             EasyMock.expect(mockBuild.getDeviceImageFile()).andStubReturn(deviceImage);
    619             CommandResult res = new CommandResult(CommandStatus.SUCCESS);
    620             res.setStderr("flashing");
    621             EasyMock.expect(mMockDevice.executeLongFastbootCommand(EasyMock.eq("update"),
    622                     EasyMock.eq(deviceImage.getAbsolutePath())))
    623                     .andThrow(new DeviceNotAvailableException());
    624             EasyMock.replay(mMockDevice, mockBuild);
    625             try {
    626                 mFlasher.checkAndFlashSystem(mMockDevice, buildId, null, mockBuild);
    627                 fail("Expected DeviceNotAvailableException not thrown");
    628             } catch (DeviceNotAvailableException dnae) {
    629                 // expected
    630                 EasyMock.verify(mMockDevice, mockBuild);
    631                 assertEquals("system flashing status should be \"EXCEPTION\"",
    632                         CommandStatus.EXCEPTION, mFlasher.getSystemFlashingStatus());
    633             }
    634         } finally {
    635             FileUtil.deleteFile(deviceImage);
    636         }
    637     }
    638 
    639     /**
    640      * Set EasyMock expectations to simulate the response to some fastboot command
    641      *
    642      * @param mockDevice the EasyMock mock {@link ITestDevice} to configure
    643      * @param response the fastboot command response to inject
    644      */
    645     private static void setFastbootResponseExpectations(ITestDevice mockDevice, String response)
    646             throws DeviceNotAvailableException {
    647         CommandResult result = new CommandResult();
    648         result.setStatus(CommandStatus.SUCCESS);
    649         result.setStderr(response);
    650         result.setStdout("");
    651         EasyMock.expect(
    652                 mockDevice.executeFastbootCommand((String)EasyMock.anyObject(),
    653                         (String)EasyMock.anyObject())).andReturn(result);
    654     }
    655 
    656     /**
    657      * Set EasyMock expectations to simulate the response to a fastboot flash command
    658      *
    659      * @param image the expected image name to flash
    660      * @param mockDevice the EasyMock mock {@link ITestDevice} to configure
    661      */
    662     private static void setFastbootFlashExpectations(ITestDevice mockDevice, String image)
    663             throws DeviceNotAvailableException {
    664         CommandResult result = new CommandResult();
    665         result.setStatus(CommandStatus.SUCCESS);
    666         result.setStderr("success");
    667         result.setStdout("");
    668         EasyMock.expect(
    669                 mockDevice.executeLongFastbootCommand(EasyMock.eq("flash"), EasyMock.eq(image),
    670                         (String)EasyMock.anyObject())).andReturn(result);
    671     }
    672 
    673     private FastbootDeviceFlasher getFlasherWithParserData(final String androidInfoData) {
    674         FastbootDeviceFlasher flasher = new FastbootDeviceFlasher() {
    675             @Override
    676             protected IFlashingResourcesParser createFlashingResourcesParser(
    677                     IDeviceBuildInfo localBuild, DeviceDescriptor desc) throws TargetSetupError {
    678                 BufferedReader reader = new BufferedReader(new StringReader(androidInfoData));
    679                 try {
    680                     return new FlashingResourcesParser(reader);
    681                 } catch (IOException e) {
    682                     return null;
    683                 }
    684             }
    685 
    686             @Override
    687             protected void flashBootloader(ITestDevice device, File bootloaderImageFile)
    688                     throws DeviceNotAvailableException, TargetSetupError {
    689                 throw new DeviceNotAvailableException("error", "fakeserial");
    690             }
    691         };
    692         flasher.setFlashingResourcesRetriever(EasyMock.createNiceMock(
    693                 IFlashingResourcesRetriever.class));
    694         return flasher;
    695     }
    696 }
    697