/** * Calculates milliseconds delay before first update based on last update/install time. If * complete update interval or more elapsed, first update is scheduled immediately (returns 0). */ private long getDelayBeforeFirstUpdate() { Optional<Long> lastTimeOfUpdate = CloudSdkServiceUserSettings.getInstance().getLastAutomaticUpdateTimestamp(); long delayBeforeUpdateMillis = SDK_UPDATE_INTERVAL_MS; if (lastTimeOfUpdate.isPresent()) { delayBeforeUpdateMillis = Math.min( SDK_UPDATE_INTERVAL_MS, Math.max(0, SDK_UPDATE_INTERVAL_MS - (getClock().millis() - lastTimeOfUpdate.get()))); } return delayBeforeUpdateMillis; }
/** * Called when managed SDK update operation (update or install) completes, either with success or * failure. */ void notifySdkUpdateCompleted() { CloudSdkServiceUserSettings.getInstance().setLastAutomaticUpdateTimestamp(getClock().millis()); }
@Before public void setUp() { // add timer thread to one not to be checked for 'leaks' ThreadTracker.longRunningThreadCreated( ApplicationManager.getApplication(), ManagedCloudSdkUpdateService.SDK_UPDATER_THREAD_NAME); when(mockPluginInfoService.shouldEnable(GctFeature.MANAGED_SDK_UPDATE)).thenReturn(true); when(mockSdkServiceManager.getCloudSdkService()).thenReturn(mockSdkService); ManagedCloudSdkServiceUiPresenter.setInstance(mockUiPresenter); doReturn(mockClock).when(managedCloudSdkUpdateService).getClock(); doReturn(mockUiTimer).when(managedCloudSdkUpdateService).createUiTimer(anyInt()); when(mockUiPresenter.notifyManagedSdkUpdate(any(), any())).thenReturn(mockNotification); // directly execute scheduled tasks. doAnswer( invocationOnMock -> { ((TimerTask) invocationOnMock.getArgument(0)).run(); return null; }) .when(managedCloudSdkUpdateService) .schedule(any(), anyLong(), anyLong()); // directly call task assigned to UI timer. doAnswer( invocationOnMock -> { ((ActionListener) invocationOnMock.getArgument(0)) .actionPerformed(mock(ActionEvent.class)); return null; }) .when(mockUiTimer) .addActionListener(any()); CloudSdkServiceUserSettings.reset(); }
@Test public void failed_update_writes_lastUpdateTime() throws Exception { makeMockSdkInstalled(MOCK_SDK_PATH); emulateMockSdkUpdateProcess(); SdkUpdater mockUpdater = mockManagedCloudSdk.newUpdater(); doThrow(new CommandExitException(-1, "")).when(mockUpdater).update(any(), any()); // supply custom clock to check update time has been properly set in settings. Clock mockClock = mock(Clock.class); when(mockUpdateService.getClock()).thenReturn(mockClock); long updateTime = 1000L; when(mockClock.millis()).thenReturn(updateTime); doCallRealMethod().when(mockUpdateService).notifySdkUpdateCompleted(); sdkService.update(); verify(mockUpdateService).notifySdkUpdateCompleted(); assertThat( CloudSdkServiceUserSettings.getInstance().getLastAutomaticUpdateTimestamp().isPresent()) .isTrue(); assertThat(CloudSdkServiceUserSettings.getInstance().getLastAutomaticUpdateTimestamp().get()) .isEqualTo(updateTime); }