WorkspaceResourceUsageTracker implements ResourceUsageTracker { @Override public Optional<Resource> getUsedResource(String accountId) throws NotFoundException, ServerException { final Account account = accountManager.getById(accountId); final List<WorkspaceImpl> accountWorkspaces = Pages.stream( (maxItems, skipCount) -> workspaceManagerProvider .get() .getByNamespace(account.getName(), false, maxItems, skipCount)) .collect(Collectors.toList()); if (!accountWorkspaces.isEmpty()) { return Optional.of( new ResourceImpl( WorkspaceResourceType.ID, accountWorkspaces.size(), WorkspaceResourceType.UNIT)); } else { return Optional.empty(); } } @Inject  WorkspaceResourceUsageTracker(
      Provider<WorkspaceManager> workspaceManagerProvider, AccountManager accountManager); @Override Optional<Resource> getUsedResource(String accountId);  }
@Test( expectedExceptions = NotFoundException.class, expectedExceptionsMessageRegExp = "Account was not found") public void shouldThrowNotFoundExceptionWhenAccountDoesNotExistOnGettingUsedWorkspaces() throws Exception { when(accountManager.getById(any())).thenThrow(new NotFoundException("Account was not found")); workspaceResourceUsageTracker.getUsedResource("account123"); }
@Test public void shouldReturnEmptyOptionalWhenAccountDoesNotUseWorkspaces() throws Exception { when(accountManager.getById(any())).thenReturn(account); when(account.getName()).thenReturn("testAccount"); when(workspaceManager.getByNamespace(anyString(), anyBoolean(), anyInt(), anyLong())) .thenReturn(new Page<>(Collections.emptyList(), 0, 1, 0)); Optional<Resource> usedWorkspacesOpt = workspaceResourceUsageTracker.getUsedResource("account123"); assertFalse(usedWorkspacesOpt.isPresent()); }
@Test public void shouldReturnUsedWorkspacesForGivenAccount() throws Exception { when(accountManager.getById(any())).thenReturn(account); when(account.getName()).thenReturn("testAccount"); when(workspaceManager.getByNamespace(anyString(), anyBoolean(), anyInt(), anyLong())) .thenReturn( new Page<>( Arrays.asList(new WorkspaceImpl(), new WorkspaceImpl(), new WorkspaceImpl()), 0, 3, 3)); Optional<Resource> usedWorkspacesOpt = workspaceResourceUsageTracker.getUsedResource("account123"); assertTrue(usedWorkspacesOpt.isPresent()); Resource usedWorkspaces = usedWorkspacesOpt.get(); assertEquals(usedWorkspaces.getType(), WorkspaceResourceType.ID); assertEquals(usedWorkspaces.getAmount(), 3); assertEquals(usedWorkspaces.getUnit(), WorkspaceResourceType.UNIT); verify(accountManager).getById(eq("account123")); verify(workspaceManager).getByNamespace(eq("testAccount"), eq(false), anyInt(), anyLong()); }