RuntimeResourceUsageTracker implements ResourceUsageTracker { @Override public Optional<Resource> getUsedResource(String accountId) throws NotFoundException, ServerException { final Account account = accountManager.getById(accountId); final long currentlyUsedRuntimes = Pages.stream( (maxItems, skipCount) -> workspaceManagerProvider .get() .getByNamespace(account.getName(), false, maxItems, skipCount)) .filter(ws -> STOPPED != ws.getStatus()) .count(); if (currentlyUsedRuntimes > 0) { return Optional.of( new ResourceImpl( RuntimeResourceType.ID, currentlyUsedRuntimes, RuntimeResourceType.UNIT)); } else { return Optional.empty(); } } @Inject  RuntimeResourceUsageTracker(
      Provider<WorkspaceManager> workspaceManagerProvider, AccountManager accountManager); @Override Optional<Resource> getUsedResource(String accountId);  }
@Test( expectedExceptions = NotFoundException.class, expectedExceptionsMessageRegExp = "Account was not found") public void shouldThrowNotFoundExceptionWhenAccountDoesNotExistOnGettingUsedRuntimes() throws Exception { when(accountManager.getById(any())).thenThrow(new NotFoundException("Account was not found")); runtimeResourceUsageTracker.getUsedResource("account123"); }
@Test public void shouldReturnEmptyOptionalWhenAccountDoesNotUseRuntimes() throws Exception { when(accountManager.getById(any())).thenReturn(account); when(account.getName()).thenReturn("testAccount"); when(workspaceManager.getByNamespace(anyString(), anyBoolean(), anyInt(), anyLong())) .thenReturn(new Page<>(singletonList(createWorkspace(WorkspaceStatus.STOPPED)), 0, 1, 1)); Optional<Resource> usedRuntimesOpt = runtimeResourceUsageTracker.getUsedResource("account123"); assertFalse(usedRuntimesOpt.isPresent()); }
@Test public void shouldReturnUsedRuntimesForGivenAccount() throws Exception { when(accountManager.getById(any())).thenReturn(account); when(account.getName()).thenReturn("testAccount"); List<WorkspaceImpl> runtimes = Stream.of(WorkspaceStatus.values()) .map(RuntimeResourceUsageTrackerTest::createWorkspace) .collect(Collectors.toList()); when(workspaceManager.getByNamespace(anyString(), anyBoolean(), anyInt(), anyLong())) .thenReturn(new Page<>(runtimes, 0, runtimes.size(), runtimes.size())); Optional<Resource> usedRuntimesOpt = runtimeResourceUsageTracker.getUsedResource("account123"); assertTrue(usedRuntimesOpt.isPresent()); Resource usedRuntimes = usedRuntimesOpt.get(); assertEquals(usedRuntimes.getType(), RuntimeResourceType.ID); assertEquals( usedRuntimes.getAmount(), WorkspaceStatus.values().length - 1); assertEquals(usedRuntimes.getUnit(), RuntimeResourceType.UNIT); verify(accountManager).getById(eq("account123")); verify(workspaceManager).getByNamespace(eq("testAccount"), eq(false), anyInt(), anyLong()); }