method2testcases
stringlengths 118
3.08k
|
---|
### Question:
CommonResource extends ServerResource { public List<String> getParameterAsList(final String name) { return Arrays.asList(getQuery().getValuesArray(name)); } APISession getEngineSession(); HttpSession getHttpSession(); HttpServletRequest getHttpRequest(); Integer getIntegerParameter(final String parameterName, final boolean mandatory); Long getLongParameter(final String parameterName, final boolean mandatory); String getParameter(final String parameterName, final boolean mandatory); List<String> getParameterAsList(final String name); SearchOptions buildSearchOptions(); @Override String getAttribute(final String name); Long getPathParamAsLong(final String parameterName); List<Long> getParameterAsLongList(final String parameterName); String getPathParam(final String name); }### Answer:
@Test public void getParametersAsList_should_support_value_with_comma() throws Exception { final CommonResource resource = spy(new CommonResource()); final Form form = new Form("f=a=b&f=c=d,e"); given(resource.getQuery()).willReturn(form); final List<String> parametersValues = resource.getParameterAsList("f"); assertThat(parametersValues).containsExactly("a=b", "c=d,e"); }
@Test public void getParametersAsList_should_support_values_with_slash() throws Exception { final CommonResource resource = spy(new CommonResource()); final Form form = new Form("f=a%3Db&f=c%3D%2Fd%2Fd%2Ce"); given(resource.getQuery()).willReturn(form); final List<String> parametersValues = resource.getParameterAsList("f"); assertThat(parametersValues).containsExactly("a=b", "c=/d/d,e"); }
@Test public void getParametersAsList_should_return_emptyList_when_parameter_does_not_exist() throws Exception { final CommonResource resource = spy(new CommonResource()); final Form form = new Form("f=a=b&f=c=d,e"); given(resource.getQuery()).willReturn(form); final List<String> parametersValues = resource.getParameterAsList("anyAbsent"); assertThat(parametersValues).isEmpty(); }
|
### Question:
ResourceExtensionResolver { public String generateMappingKey() { final StringBuilder builder = new StringBuilder(); final String requestAsString = getHttpServletRequest().getRequestURI(); final String pathTemplate = StringUtils.substringAfter(requestAsString, API_EXTENSION_TEMPLATE_PREFIX); builder.append(MAPPING_KEY_PREFIX) .append(MAPPING_KEY_SEPARATOR) .append(request.getMethod().getName()) .append(MAPPING_KEY_SEPARATOR) .append(pathTemplate); return builder.toString(); } ResourceExtensionResolver(Request request, PageMappingService pageMappingService); Long resolvePageId(APISession apiSession); String generateMappingKey(); File resolveRestApiControllerFile(PageResourceProviderImpl pageResourceProvider); static final String MAPPING_KEY_SEPARATOR; static final String MAPPING_KEY_PREFIX; static final String API_EXTENSION_TEMPLATE_PREFIX; }### Answer:
@Test public void should_generate_mapping_key() throws Exception { final Request request = new Request(Method.POST, "/bonita/API/extension/myPostResource"); final ResourceExtensionResolver resourceExtensionResolver = createSpy(request, "/bonita/API/extension/myPostResource"); final String mappingKey = resourceExtensionResolver.generateMappingKey(); assertThat(mappingKey).isEqualTo(API_EXTENSION_POST_MAPPING_KEY); }
@Test public void should_mapping_key_exclude_parameters() throws Exception { final Request request = new Request(Method.GET, "/bonita/API/extension/helloWorld?param1=a¶m2=b"); final ResourceExtensionResolver resourceExtensionResolver = createSpy(request, "/bonita/API/extension/helloWorld"); final String mappingKey = resourceExtensionResolver.generateMappingKey(); assertThat(mappingKey).isEqualTo(API_EXTENSION_GET_MAPPING_KEY); }
|
### Question:
UserDeployer implements Deployer { @Override public void deployIn(IItem item) { if (isDeployable(attribute, item)) { item.setDeploy(attribute, getUser(getUserId(item))); } } UserDeployer(DatastoreHasGet<UserItem> getter, String attribute); @Override String getDeployedAttribute(); @Override void deployIn(IItem item); }### Answer:
@Test public void testDeployableAttributeIsDeployed() throws Exception { UserItem user = prepareGetterToReturnAUser(); ReportItem report = aReportInstalledBy(APIID.makeAPIID(6L)); UserDeployer installedByDeployer = new UserDeployer(getter, ReportItem.ATTRIBUTE_INSTALLED_BY); installedByDeployer.deployIn(report); assertEquals(user, report.getInstalledBy()); }
@Test public void testNotDeployableAttributeIsNotDeployed() throws Exception { prepareGetterToReturnAUser(); ReportItem report = aReportInstalledBy(null); UserDeployer nameDeployer = new UserDeployer(getter, ReportItem.ATTRIBUTE_INSTALLED_BY); nameDeployer.deployIn(report); assertNull(report.getInstalledBy()); }
|
### Question:
UserRightsBuilder { public List<String> build() { List<String> rights = new ArrayList<String>(); for (String token : provider.getTokens()) { rights.add(generator.getHash(token.concat(String.valueOf(session.getId())))); } return rights; } UserRightsBuilder(org.bonitasoft.engine.session.APISession session, TokenProvider provider); List<String> build(); }### Answer:
@Test public void should_build_rights_for_a_token_add_to_it() throws Exception { given(session.getId()).willReturn(56L); UserRightsBuilder builder = new UserRightsBuilder(session, new TokenListProvider(Arrays.asList( "token"))); assertEquals(builder.build().get(0), generator.getHash("token56")); }
@Test public void should_build_rights_for_all_tokens_progressively_add_to_it() throws Exception { given(session.getId()).willReturn(85L); UserRightsBuilder builder = new UserRightsBuilder(session, new TokenListProvider(Arrays.asList( "token 1", "token 2"))); List<String> rights = builder.build(); assertEquals(rights.get(0), generator.getHash("token 185")); assertEquals(rights.get(1), generator.getHash("token 285")); }
|
### Question:
TokenListProvider implements UserRightsBuilder.TokenProvider { @Override public List<String> getTokens() { return tokens; } TokenListProvider(List<String> tokens); @Override List<String> getTokens(); }### Answer:
@Test public void should_return_the_list_of_provided_token_without_null() throws Exception { TokenListProvider provider = new TokenListProvider(Arrays.asList( "token 1", null, "token 2")); assertThat(provider.getTokens()).containsExactly("token 1", "token 2"); }
|
### Question:
BonitaVersion { public String getVersion() { if (metadata == null) { metadata = read(file.getStream()); } if (metadata.size() > 0) { return metadata.get(0).trim(); } else { return ""; } } BonitaVersion(final VersionFile file); String getVersion(); String getCopyright(); }### Answer:
@Test public void should_read_version_stream_to_return_its_version() throws Exception { final InputStream stream = IOUtils.toInputStream("1.0.0"); given(file.getStream()).willReturn(stream); final BonitaVersion version = new BonitaVersion(file); assertThat(version.getVersion()).isEqualTo("1.0.0"); IOUtils.closeQuietly(stream); }
@Test public void should_trim_extra_new_line_character() throws Exception { final InputStream stream = IOUtils.toInputStream("1.0.0\n"); given(file.getStream()).willReturn(stream); final BonitaVersion version = new BonitaVersion(file); assertThat(version.getVersion()).isEqualTo("1.0.0"); IOUtils.closeQuietly(stream); }
|
### Question:
TokenProfileProvider implements UserRightsBuilder.TokenProvider { @Override public List<String> getTokens() { return tokens; } TokenProfileProvider(List<Profile> profiles, ProfileEntryEngineClient client); @Override List<String> getTokens(); }### Answer:
@Test public void should_return_all_page_tokens_for_each_profile_entries() throws Exception { given(entry1.getPage()).willReturn("token 1"); given(entry2.getPage()).willReturn("token 2"); TokenProfileProvider provider = new TokenProfileProvider(Arrays.asList( profile1, profile2), client); assertThat(provider.getTokens().toString()).isEqualTo("[token 1, token 2]"); }
@Test public void should_not_return_a_token_if_the_page_from_the_profile_entry_is_null() throws Exception { given(entry1.getPage()).willReturn(null); given(entry2.getPage()).willReturn("token 2"); TokenProfileProvider provider = new TokenProfileProvider(Arrays.asList( profile1, profile2), client); assertThat(provider.getTokens().toString()).isEqualTo("[token 2]"); }
|
### Question:
APIApplicationPage extends ConsoleAPI<ApplicationPageItem> implements APIHasAdd<ApplicationPageItem>, APIHasSearch<ApplicationPageItem>, APIHasGet<ApplicationPageItem>, APIHasDelete { @Override public ApplicationPageItem add(final ApplicationPageItem item) { return factory.createApplicationPageDataStore(getEngineSession()).add(item); } APIApplicationPage(final APIApplicationDataStoreFactory factory); @Override ApplicationPageItem add(final ApplicationPageItem item); @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void add_should_return_the_result_of_dataStore_add() throws Exception { final ApplicationPageItem itemToCreate = mock(ApplicationPageItem.class); final ApplicationPageItem createdItem = mock(ApplicationPageItem.class); given(applicationPageDataStore.add(itemToCreate)).willReturn(createdItem); final ApplicationPageItem retrievedItem = apiApplicationPage.add(itemToCreate); assertThat(retrievedItem).isEqualTo(createdItem); }
|
### Question:
APIApplicationPage extends ConsoleAPI<ApplicationPageItem> implements APIHasAdd<ApplicationPageItem>, APIHasSearch<ApplicationPageItem>, APIHasGet<ApplicationPageItem>, APIHasDelete { @Override public String defineDefaultSearchOrder() { return ApplicationPageItem.ATTRIBUTE_TOKEN; } APIApplicationPage(final APIApplicationDataStoreFactory factory); @Override ApplicationPageItem add(final ApplicationPageItem item); @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void defineDefaultSearchOrder_should_return_attribute_token() throws Exception { final String defaultSearchOrder = apiApplicationPage.defineDefaultSearchOrder(); assertThat(defaultSearchOrder).isEqualTo("token"); }
|
### Question:
APIApplicationPage extends ConsoleAPI<ApplicationPageItem> implements APIHasAdd<ApplicationPageItem>, APIHasSearch<ApplicationPageItem>, APIHasGet<ApplicationPageItem>, APIHasDelete { @Override protected ItemDefinition<ApplicationPageItem> defineItemDefinition() { return ApplicationPageDefinition.get(); } APIApplicationPage(final APIApplicationDataStoreFactory factory); @Override ApplicationPageItem add(final ApplicationPageItem item); @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void defineItemDefinition_return_an_instance_of_ApplicationDefinition() throws Exception { final ItemDefinition<ApplicationPageItem> itemDefinition = apiApplicationPage.defineItemDefinition(); assertThat(itemDefinition).isExactlyInstanceOf(ApplicationPageDefinition.class); }
|
### Question:
APIApplicationPage extends ConsoleAPI<ApplicationPageItem> implements APIHasAdd<ApplicationPageItem>, APIHasSearch<ApplicationPageItem>, APIHasGet<ApplicationPageItem>, APIHasDelete { @Override protected void fillDeploys(final ApplicationPageItem item, final List<String> deploys) { addDeployer(new PageDeployer( factory.createPageDataStore(getEngineSession()), ApplicationPageItem.ATTRIBUTE_PAGE_ID)); addDeployer(new ApplicationDeployer( factory.createApplicationDataStore(getEngineSession()), ApplicationPageItem.ATTRIBUTE_APPLICATION_ID)); super.fillDeploys(item, deploys); } APIApplicationPage(final APIApplicationDataStoreFactory factory); @Override ApplicationPageItem add(final ApplicationPageItem item); @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void should_fill_application_deploy_when_requested() { final ApplicationPageItem applicationPage = new ApplicationPageItem(); applicationPage.setApplicationId(1L); final ApplicationItem application = new ApplicationItem(); application.setDisplayName("foo"); given(applicationDataStore.get(APIID.makeAPIID(1L))).willReturn(application); apiApplicationPage.fillDeploys(applicationPage, singletonList(ApplicationPageItem.ATTRIBUTE_APPLICATION_ID)); assertThat(applicationPage.getApplication()).isEqualTo(application); }
@Test public void should_fill_page_deploy_when_requested() { final ApplicationPageItem applicationPage = new ApplicationPageItem(); applicationPage.setPageId(2L); final PageItem customPage = new PageItem(); customPage.setContentName("bar"); given(pageDataStore.get(APIID.makeAPIID(2L))).willReturn(customPage); apiApplicationPage.fillDeploys(applicationPage, singletonList(ApplicationPageItem.ATTRIBUTE_PAGE_ID)); assertThat(applicationPage.getPage()).isEqualTo(customPage); }
|
### Question:
APICaseDocument extends ConsoleAPI<CaseDocumentItem> { @Override public CaseDocumentItem get(final APIID id) { return getCaseDocumentDatastore().get(id); } @Override CaseDocumentItem get(final APIID id); @Override CaseDocumentItem add(final CaseDocumentItem item); @Override CaseDocumentItem update(final APIID id, final Map<String, String> attributes); @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<CaseDocumentItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override void delete(final List<APIID> ids); }### Answer:
@Test public void it_should_call_the_datastore_get_method() { final APIID id = APIID.makeAPIID(1l); apiDocument.get(id); verify(datastore).get(id); }
|
### Question:
APICaseDocument extends ConsoleAPI<CaseDocumentItem> { @Override public CaseDocumentItem add(final CaseDocumentItem item) { return getCaseDocumentDatastore().add(item); } @Override CaseDocumentItem get(final APIID id); @Override CaseDocumentItem add(final CaseDocumentItem item); @Override CaseDocumentItem update(final APIID id, final Map<String, String> attributes); @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<CaseDocumentItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override void delete(final List<APIID> ids); }### Answer:
@Test public void it_should_call_the_datastore_add_method() { apiDocument.add(documentItemMock); verify(datastore).add(documentItemMock); }
|
### Question:
APICaseDocument extends ConsoleAPI<CaseDocumentItem> { @Override public CaseDocumentItem update(final APIID id, final Map<String, String> attributes) { return getCaseDocumentDatastore().update(id, attributes); } @Override CaseDocumentItem get(final APIID id); @Override CaseDocumentItem add(final CaseDocumentItem item); @Override CaseDocumentItem update(final APIID id, final Map<String, String> attributes); @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<CaseDocumentItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override void delete(final List<APIID> ids); }### Answer:
@Test public void it_should_call_the_datastore_update_method() { final APIID id = APIID.makeAPIID(1l); final Map<String, String> attributes = null; apiDocument.update(id, attributes); verify(datastore).update(id, attributes); }
|
### Question:
APICaseDocument extends ConsoleAPI<CaseDocumentItem> { @Override public ItemSearchResult<CaseDocumentItem> search(final int page, final int resultsByPage, final String search, final String orders, final Map<String, String> filters) { final ItemSearchResult<CaseDocumentItem> results = getCaseDocumentDatastore().search(page, resultsByPage, search, filters, orders); return results; } @Override CaseDocumentItem get(final APIID id); @Override CaseDocumentItem add(final CaseDocumentItem item); @Override CaseDocumentItem update(final APIID id, final Map<String, String> attributes); @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<CaseDocumentItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override void delete(final List<APIID> ids); }### Answer:
@Test public void it_should_call_the_datastore_search_method() { apiDocument.search(0, 10, "hello", "documentName ASC", null); verify(datastore).search(0, 10, "hello", null, "documentName ASC"); }
|
### Question:
CaseContextResource extends CommonResource { private Serializable getContextResultElement(Serializable executionContextElementValue) { return resourceHandler.getContextResultElement(executionContextElementValue); } CaseContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getCaseContext(); }### Answer:
@Test public void should_return_a_context_of_type_SingleBusinessDataRef_for_a_given_case() throws Exception { final Map<String, Serializable> context = new HashMap<String, Serializable>(); String engineResult = "object returned by engine"; context.put("Ticket", engineResult); when(processAPI.getProcessInstanceExecutionContext(2L)).thenReturn(context); doReturn("clientResult").when(finderFactory).getContextResultElement(engineResult); final Response response = request("/bpm/case/2/context").get(); assertThat(response).hasStatus(Status.SUCCESS_OK); assertThat(response).hasJsonEntityEqualTo("{\"Ticket\":\"clientResult\"}"); }
|
### Question:
CaseContextResource extends CommonResource { protected long getCaseIdParameter() { final String caseId = getAttribute(CASE_ID); if (caseId == null) { throw new APIException("Attribute '" + CASE_ID + "' is mandatory in order to get the case context"); } return Long.parseLong(caseId); } CaseContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getCaseContext(); }### Answer:
@Test public void should_getTaskIDParameter_throws_an_exception_when_task_id_parameter_is_null() throws Exception { doReturn(null).when(caseContextResource).getAttribute(CaseContextResource.CASE_ID); try { caseContextResource.getCaseIdParameter(); } catch (final Exception e) { Assertions.assertThat(e).isInstanceOf(APIException.class); Assertions.assertThat(e.getMessage()).isEqualTo("Attribute '" + CaseContextResource.CASE_ID + "' is mandatory in order to get the case context"); } }
|
### Question:
APICaseVariableAttributeChecker { public void checkUpdateAttributes(Map<String, String> attributes) { if (attributes == null || attributes.isEmpty()) { throw new APIException(format("Attributes '%s' and '%s' must be specified", CaseVariableItem.ATTRIBUTE_TYPE, CaseVariableItem.ATTRIBUTE_VALUE)); } if (!attributes.containsKey(CaseVariableItem.ATTRIBUTE_TYPE)) { throw new APIException(format("Attribute '%s' must be specified", CaseVariableItem.ATTRIBUTE_TYPE)); } if (!attributes.containsKey(CaseVariableItem.ATTRIBUTE_VALUE)) { throw new APIException(format("Attribute '%s' must be specified", CaseVariableItem.ATTRIBUTE_VALUE)); } } void checkUpdateAttributes(Map<String, String> attributes); void checkSearchFilters(Map<String, String> filters); }### Answer:
@Test public void checkUpdateAttributesPassForSuitableValues() throws Exception { Map<String, String> attributes = buildSuitableUpdateAttributes(); attributeChecker.checkUpdateAttributes(attributes); }
@Test(expected = APIException.class) public void checkUpdateAttributesCheckForAttributeType() throws Exception { Map<String, String> attributes = buildSuitableUpdateAttributes(); attributes.remove(CaseVariableItem.ATTRIBUTE_TYPE); attributeChecker.checkUpdateAttributes(attributes); }
@Test(expected = APIException.class) public void checkUpdateAttributesCheckForAttributeValue() throws Exception { Map<String, String> attributes = buildSuitableUpdateAttributes(); attributes.remove(CaseVariableItem.ATTRIBUTE_VALUE); attributeChecker.checkUpdateAttributes(attributes); }
@Test(expected = APIException.class) public void should_throw_exception_when_attributes_are_null() throws Exception { attributeChecker.checkUpdateAttributes(null); }
|
### Question:
APICaseVariableAttributeChecker { public void checkSearchFilters(Map<String, String> filters) { if (filters == null || !filters.containsKey(CaseVariableItem.ATTRIBUTE_CASE_ID)) { throw new APIException(format("Filter '%s' must be specified", CaseVariableItem.ATTRIBUTE_CASE_ID)); } } void checkUpdateAttributes(Map<String, String> attributes); void checkSearchFilters(Map<String, String> filters); }### Answer:
@Test public void checkSearchFiltersPassForSuitableValues() throws Exception { Map<String, String> filters = buildSuitableSearchFilters(); attributeChecker.checkSearchFilters(filters); }
@Test(expected = APIException.class) public void checkSearchFiltersCheckForCaseIdFilters() throws Exception { Map<String, String> filters = buildSuitableSearchFilters(); filters.remove(CaseVariableItem.ATTRIBUTE_CASE_ID); attributeChecker.checkSearchFilters(filters); }
@Test(expected = APIException.class) public void should_throw_exception_when_filters_are_null() throws Exception { attributeChecker.checkSearchFilters(null); }
|
### Question:
APICaseVariable extends ConsoleAPI<CaseVariableItem> implements APIHasSearch<CaseVariableItem>,
APIHasUpdate<CaseVariableItem>, APIHasGet<CaseVariableItem> { @Override public CaseVariableItem runUpdate(APIID id, Map<String, String> attributes) { attributeChecker.checkUpdateAttributes(attributes); id.setItemDefinition(CaseVariableDefinition.get()); CaseVariableItem item = CaseVariableItem.fromIdAndAttributes(id, attributes); ((CaseVariableDatastore) getDefaultDatastore()).updateVariableValue(item.getCaseId(), item.getName(), item.getType(), item.getValue()); return item; } @Override CaseVariableItem runUpdate(APIID id, Map<String, String> attributes); @Override ItemSearchResult<CaseVariableItem> runSearch(int page, int resultsByPage, String search, String orders,
Map<String, String> filters, List<String> deploys, List<String> counters); @Override CaseVariableItem runGet(APIID id, List<String> deploys, List<String> counters); void setAttributeChecker(APICaseVariableAttributeChecker attributeChecker); }### Answer:
@Test public void updateUpdateTheVariableValue() throws Exception { long caseId = 1L; String variableName = "aName"; String newValue = "newValue"; Map<String, String> parameters = buildUpdateParameters(newValue, String.class.getName()); APIID apiid = buildAPIID(caseId, variableName); apiCaseVariable.runUpdate(apiid, parameters); verify(datastore).updateVariableValue(caseId, variableName, String.class.getName(), newValue); }
|
### Question:
APICaseVariable extends ConsoleAPI<CaseVariableItem> implements APIHasSearch<CaseVariableItem>,
APIHasUpdate<CaseVariableItem>, APIHasGet<CaseVariableItem> { @Override public ItemSearchResult<CaseVariableItem> runSearch(int page, int resultsByPage, String search, String orders, Map<String, String> filters, List<String> deploys, List<String> counters) { attributeChecker.checkSearchFilters(filters); long caseId = Long.valueOf(filters.get(CaseVariableItem.ATTRIBUTE_CASE_ID)); return ((CaseVariableDatastore) getDefaultDatastore()).findByCaseId(caseId, page, resultsByPage); } @Override CaseVariableItem runUpdate(APIID id, Map<String, String> attributes); @Override ItemSearchResult<CaseVariableItem> runSearch(int page, int resultsByPage, String search, String orders,
Map<String, String> filters, List<String> deploys, List<String> counters); @Override CaseVariableItem runGet(APIID id, List<String> deploys, List<String> counters); void setAttributeChecker(APICaseVariableAttributeChecker attributeChecker); }### Answer:
@Test public void searchIsFilteredByCaseId() throws Exception { long expectedCaseId = 1L; Map<String, String> filters = buildCaseIdFilter(expectedCaseId); apiCaseVariable.runSearch(0, 10, null, null, filters, null, null); verify(datastore).findByCaseId(expectedCaseId, 0, 10); }
|
### Question:
APICaseVariable extends ConsoleAPI<CaseVariableItem> implements APIHasSearch<CaseVariableItem>,
APIHasUpdate<CaseVariableItem>, APIHasGet<CaseVariableItem> { @Override public CaseVariableItem runGet(APIID id, List<String> deploys, List<String> counters) { id.setItemDefinition(CaseVariableDefinition.get()); long caseId = id.getPartAsLong(CaseVariableItem.ATTRIBUTE_CASE_ID); String variableName = id.getPart(CaseVariableItem.ATTRIBUTE_NAME); return ((CaseVariableDatastore) getDefaultDatastore()).findById(caseId, variableName); } @Override CaseVariableItem runUpdate(APIID id, Map<String, String> attributes); @Override ItemSearchResult<CaseVariableItem> runSearch(int page, int resultsByPage, String search, String orders,
Map<String, String> filters, List<String> deploys, List<String> counters); @Override CaseVariableItem runGet(APIID id, List<String> deploys, List<String> counters); void setAttributeChecker(APICaseVariableAttributeChecker attributeChecker); }### Answer:
@Test public void getSearchInDatastoreById() throws Exception { long expectedCaseId = 1L; String expectedVariableName = "aName"; APIID apiid = buildAPIID(expectedCaseId, expectedVariableName); apiCaseVariable.runGet(apiid, null, null); verify(datastore).findById(expectedCaseId, expectedVariableName); }
|
### Question:
ArchivedCaseContextResource extends CommonResource { private Serializable getContextResultElement(Serializable executionContextElementValue) { return resourceHandler.getContextResultElement(executionContextElementValue); } ArchivedCaseContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getArchivedCaseContext(); }### Answer:
@Test public void should_return_a_context_of_type_SingleBusinessDataRef_for_a_given_archived_case() throws Exception { final Map<String, Serializable> context = new HashMap<String, Serializable>(); String engineResult = "object returned by engine"; context.put("Ticket", engineResult); when(processAPI.getArchivedProcessInstanceExecutionContext(2L)).thenReturn(context); doReturn("clientResult").when(finderFactory).getContextResultElement(engineResult); final Response response = request("/bpm/archivedCase/2/context").get(); assertThat(response).hasStatus(Status.SUCCESS_OK); assertThat(response).hasJsonEntityEqualTo("{\"Ticket\":\"clientResult\"}"); }
|
### Question:
ArchivedCaseContextResource extends CommonResource { protected long getArchivedCaseIdParameter() { final String caseId = getAttribute(ARCHIVED_CASE_ID); if (caseId == null) { throw new APIException("Attribute '" + ARCHIVED_CASE_ID + "' is mandatory in order to get the archived case context"); } return Long.parseLong(caseId); } ArchivedCaseContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getArchivedCaseContext(); }### Answer:
@Test public void should_getTaskIDParameter_throws_an_exception_when_archived_case_id_parameter_is_null() throws Exception { doReturn(null).when(archivedCaseContextResource).getAttribute(ArchivedCaseContextResource.ARCHIVED_CASE_ID); try { archivedCaseContextResource.getArchivedCaseIdParameter(); } catch (final Exception e) { Assertions.assertThat(e).isInstanceOf(APIException.class); Assertions.assertThat(e.getMessage()).isEqualTo("Attribute '" + ArchivedCaseContextResource.ARCHIVED_CASE_ID + "' is mandatory in order to get the archived case context"); } }
|
### Question:
APICase extends ConsoleAPI<CaseItem> implements APIHasGet<CaseItem>, APIHasAdd<CaseItem>, APIHasSearch<CaseItem>, APIHasDelete { @Override public String defineDefaultSearchOrder() { return ProcessInstanceCriterion.CREATION_DATE_DESC.name(); } @Override CaseItem add(final CaseItem caseItem); @Override CaseItem get(final APIID id); @Override ItemSearchResult<CaseItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override String defineDefaultSearchOrder(); @Override void delete(final List<APIID> ids); }### Answer:
@Test public final void defineDefaultSearchOrder_should_be_descending_creation_date() { final String defineDefaultSearchOrder = apiCase.defineDefaultSearchOrder(); assertEquals(ProcessInstanceCriterion.CREATION_DATE_DESC.name(), defineDefaultSearchOrder); }
|
### Question:
APICase extends ConsoleAPI<CaseItem> implements APIHasGet<CaseItem>, APIHasAdd<CaseItem>, APIHasSearch<CaseItem>, APIHasDelete { @Override public void delete(final List<APIID> ids) { getCaseDatastore().delete(ids); } @Override CaseItem add(final CaseItem caseItem); @Override CaseItem get(final APIID id); @Override ItemSearchResult<CaseItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override String defineDefaultSearchOrder(); @Override void delete(final List<APIID> ids); }### Answer:
@Test public final void delete_should_delete_case_items_on_CaseDatastore() { final List<APIID> ids = Arrays.asList(APIID.makeAPIID(78L)); apiCase.delete(ids); verify(caseDatastore).delete(ids); }
|
### Question:
APICase extends ConsoleAPI<CaseItem> implements APIHasGet<CaseItem>, APIHasAdd<CaseItem>, APIHasSearch<CaseItem>, APIHasDelete { @Override public CaseItem add(final CaseItem caseItem) { return getCaseDatastore().add(caseItem); } @Override CaseItem add(final CaseItem caseItem); @Override CaseItem get(final APIID id); @Override ItemSearchResult<CaseItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override String defineDefaultSearchOrder(); @Override void delete(final List<APIID> ids); }### Answer:
@Test public final void add_should_add_case_item_on_CaseDatastore() { final CaseItem item = mock(CaseItem.class); doReturn(item).when(caseDatastore).add(item); final CaseItem result = apiCase.add(item); assertEquals(item, result); verify(caseDatastore).add(item); }
|
### Question:
FormsResourcesUtils { protected static ClassLoader setCorrectHierarchicalClassLoader(ClassLoader processClassLoader, final ClassLoader parentClassLoader) { if (processClassLoader == null) { processClassLoader = parentClassLoader; } return processClassLoader; } static synchronized void retrieveApplicationFiles(final APISession session, final long processDefinitionID, final Date processDeployementDate); ClassLoader getProcessClassLoader(final APISession session, final long processDefinitionID); static synchronized void removeApplicationFiles(final APISession session, final long processDefinitionID); static File getApplicationResourceDir(final APISession session, final long processDefinitionID, final Date processDeployementDate); static String getBusinessDataModelVersion(final APISession session); final static String FORMS_DIRECTORY_IN_BAR; final static String LIB_DIRECTORY_IN_BAR; final static String VALIDATORS_DIRECTORY_IN_BAR; final static String UUID_SEPARATOR; }### Answer:
@Test public void setCorrectHierarchicalClassLoaderShouldsetParentClassloaderIfCLIsNull() throws Exception { final ClassLoader processClassLoader = null; final ClassLoader parentClassLoader = mock(ClassLoader.class); final ClassLoader realCL = FormsResourcesUtils.setCorrectHierarchicalClassLoader(processClassLoader, parentClassLoader); assertThat(realCL).isEqualTo(parentClassLoader); }
|
### Question:
APICase extends ConsoleAPI<CaseItem> implements APIHasGet<CaseItem>, APIHasAdd<CaseItem>, APIHasSearch<CaseItem>, APIHasDelete { @Override public CaseItem get(final APIID id) { return getCaseDatastore().get(id); } @Override CaseItem add(final CaseItem caseItem); @Override CaseItem get(final APIID id); @Override ItemSearchResult<CaseItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override String defineDefaultSearchOrder(); @Override void delete(final List<APIID> ids); }### Answer:
@Test public final void get_should_get_case_item_on_CaseDatastore() { final APIID id = APIID.makeAPIID(78L); final CaseItem item = mock(CaseItem.class); doReturn(item).when(caseDatastore).get(id); final CaseItem result = apiCase.get(id); assertEquals(item, result); verify(caseDatastore).get(id); }
|
### Question:
APICase extends ConsoleAPI<CaseItem> implements APIHasGet<CaseItem>, APIHasAdd<CaseItem>, APIHasSearch<CaseItem>, APIHasDelete { @Override protected void fillDeploys(final CaseItem item, final List<String> deploys) { fillStartedBy(item, deploys); fillStartedBySubstitute(item, deploys); fillProcess(item, deploys); } @Override CaseItem add(final CaseItem caseItem); @Override CaseItem get(final APIID id); @Override ItemSearchResult<CaseItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override String defineDefaultSearchOrder(); @Override void delete(final List<APIID> ids); }### Answer:
@Test public final void fillDeploys_should_do_nothing_when_deploy_of_started_by_is_not_active() { final CaseItem item = mock(CaseItem.class); final List<String> deploys = new ArrayList<String>(); apiCase.fillDeploys(item, deploys); verify(item, never()).setDeploy(anyString(), any(Item.class)); }
@Test public final void fillDeploys_should_do_nothing_when_deploy_of_started_by_substitute_is_not_active() { final CaseItem item = mock(CaseItem.class); final List<String> deploys = new ArrayList<String>(); apiCase.fillDeploys(item, deploys); verify(item, never()).setDeploy(anyString(), any(Item.class)); }
@Test public final void fillDeploys_should_do_nothing_when_deploy_of_process_is_not_active() { final CaseItem item = mock(CaseItem.class); final List<String> deploys = new ArrayList<String>(); apiCase.fillDeploys(item, deploys); verify(item, never()).setDeploy(anyString(), any(Item.class)); }
|
### Question:
CaseInfoResource extends CommonResource { @Get("json") public CaseInfo getCaseInfo() { try { final long caseId = Long.parseLong(getAttribute(CASE_ID)); final CaseInfo caseInfo = new CaseInfo(); caseInfo.setId(caseId); caseInfo.setFlowNodeStatesCounters(getFlownodeCounters(caseId)); return caseInfo; } catch (final Exception e) { throw new APIException(e); } } CaseInfoResource(final ProcessAPI processAPI); @Get("json") CaseInfo getCaseInfo(); static final String CASE_ID; }### Answer:
@Test(expected = APIException.class) public void shouldDoGetWithNothingThowsAnApiException() throws DataNotFoundException { caseInfoResource.getCaseInfo(); }
@Test(expected = APIException.class) public void should_throw_exception_if_attribute_is_not_found() throws Exception { doReturn(null).when(caseInfoResource).getAttribute(anyString()); caseInfoResource.getCaseInfo(); }
@Test public void should_return_case_info_123() throws DataNotFoundException { final long id = 123; doReturn(String.valueOf(id)).when(caseInfoResource).getAttribute(CaseInfoResource.CASE_ID); final HashMap<String, Map<String, Long>> taskWithCounters = new HashMap<String, Map<String, Long>>(); when(processAPI.getFlownodeStateCounters(anyLong())).thenReturn(taskWithCounters); final CaseInfo caseInfo = caseInfoResource.getCaseInfo(); assertThat(caseInfo).isNotNull(); assertThat(caseInfo.getId()).isSameAs(id); assertThat(caseInfo.getFlowNodeStatesCounters()).isEqualTo(taskWithCounters); }
|
### Question:
APIArchivedActivity extends AbstractAPIActivity<ArchivedActivityItem> { @Override public String defineDefaultSearchOrder() { return ArchivedActivityItem.ATTRIBUTE_REACHED_STATE_DATE + ISearchDirection.SORT_ORDER_ASCENDING; } @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void should_have_default_search_order() throws Exception { final APIArchivedActivity apiActivity = new APIArchivedActivity(); final String defineDefaultSearchOrder = apiActivity.defineDefaultSearchOrder(); assertThat(defineDefaultSearchOrder).as("sould have a default search order").isEqualTo("reached_state_date ASC"); }
|
### Question:
ArchivedUserTaskContextResource extends CommonResource { private Serializable getContextResultElement(Serializable executionContextElementValue) { return resourceHandler.getContextResultElement(executionContextElementValue); } ArchivedUserTaskContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getArchivedUserTaskContext(); }### Answer:
@Test public void should_return_a_context_of_type_SingleBusinessDataRef_for_a_given_archived_task_instance() throws Exception { final Map<String, Serializable> context = new HashMap<String, Serializable>(); String engineResult = "object returned by engine"; context.put("Ticket", engineResult); when(processAPI.getArchivedUserTaskExecutionContext(2L)).thenReturn(context); doReturn("clientResult").when(finderFactory).getContextResultElement(engineResult); final Response response = request("/bpm/archivedUserTask/2/context").get(); assertThat(response).hasStatus(Status.SUCCESS_OK); assertThat(response).hasJsonEntityEqualTo("{\"Ticket\":\"clientResult\"}"); }
|
### Question:
ArchivedUserTaskContextResource extends CommonResource { protected long getArchivedTaskIdParameter() { final String taskId = getAttribute(ARCHIVED_TASK_ID); if (taskId == null) { throw new APIException("Attribute '" + ARCHIVED_TASK_ID + "' is mandatory in order to get the archived task context"); } return Long.parseLong(taskId); } ArchivedUserTaskContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getArchivedUserTaskContext(); }### Answer:
@Test public void should_getArchivedTaskIDParameter_throws_an_exception_when_archived_task_id_parameter_is_null() throws Exception { doReturn(null).when(archviedTaskContextResource).getAttribute(ArchivedUserTaskContextResource.ARCHIVED_TASK_ID); try { archviedTaskContextResource.getArchivedTaskIdParameter(); } catch (final Exception e) { Assertions.assertThat(e).isInstanceOf(APIException.class); Assertions.assertThat(e.getMessage()).isEqualTo("Attribute '" +ArchivedUserTaskContextResource.ARCHIVED_TASK_ID + "' is mandatory in order to get the archived task context"); } }
|
### Question:
TimerEventTriggerResource extends CommonResource { @Get("json") public void searchTimerEventTriggers() { try { final Long caseId = getLongParameter("caseId", true); final SearchResult<TimerEventTriggerInstance> searchResult = processAPI.searchTimerEventTriggerInstances(caseId, buildSearchOptions()); Representation representation = getConverterService().toRepresentation(searchResult.getResult(), MediaType.APPLICATION_JSON); representation.setCharacterSet(CharacterSet.UTF_8); getResponse().setEntity(representation); setContentRange(searchResult); } catch (final Exception e) { throw new APIException(e); } } TimerEventTriggerResource(final ProcessAPI processAPI); @Get("json") void searchTimerEventTriggers(); @Put("json") TimerEventTrigger updateTimerEventTrigger(final TimerEventTrigger trigger); @Override String getAttribute(final String attributeName); static final String ID_PARAM_NAME; }### Answer:
@Test public void searchTimerEventTriggersShouldCallEngine() throws Exception { final SearchOptions searchOptions = mock(SearchOptions.class); doReturn(1L).when(restResource).getLongParameter(anyString(), anyBoolean()); doReturn(1).when(restResource).getIntegerParameter(anyString(), anyBoolean()); Response mockResponse = mock(Response.class); doReturn(mockResponse).when(restResource).getResponse(); doReturn(mock(Representation.class)).when(mockResponse).getEntity(); doReturn(searchOptions).when(restResource).buildSearchOptions(); SearchResult<TimerEventTriggerInstance> searchResult = mock(SearchResult.class); doReturn(Collections.emptyList()).when(searchResult).getResult(); doReturn(1L).when(searchResult).getCount(); doReturn(searchResult).when(processAPI).searchTimerEventTriggerInstances(anyLong(), eq(searchOptions)); restResource.searchTimerEventTriggers(); verify(processAPI).searchTimerEventTriggerInstances(1L, searchOptions); }
@Test(expected = APIException.class) public void searchTimerEventTriggersShouldThrowExceptionIfParameterNotFound() throws Exception { doReturn(null).when(restResource).getParameter(anyString(), anyBoolean()); restResource.searchTimerEventTriggers(); }
|
### Question:
TimerEventTriggerResource extends CommonResource { @Put("json") public TimerEventTrigger updateTimerEventTrigger(final TimerEventTrigger trigger) throws Exception { final String triggerId = getAttribute(ID_PARAM_NAME); if (triggerId == null) { throw new APIException("Attribute '" + ID_PARAM_NAME + "' is mandatory"); } final long timerEventTriggerInstanceId = Long.parseLong(triggerId); final Date executionDate = new Date(trigger.getExecutionDate()); return createTimerEventTrigger(processAPI.updateExecutionDateOfTimerEventTriggerInstance(timerEventTriggerInstanceId, executionDate) .getTime()); } TimerEventTriggerResource(final ProcessAPI processAPI); @Get("json") void searchTimerEventTriggers(); @Put("json") TimerEventTrigger updateTimerEventTrigger(final TimerEventTrigger trigger); @Override String getAttribute(final String attributeName); static final String ID_PARAM_NAME; }### Answer:
@Test(expected = APIException.class) public void updateShouldHandleNullID() throws Exception { doReturn(Collections.EMPTY_MAP).when(restResource).getRequestAttributes(); restResource.updateTimerEventTrigger(null); }
|
### Question:
UserTaskContextResource extends CommonResource { private Serializable getContextResultElement(Serializable executionContextElementValue) { return resourceHandler.getContextResultElement(executionContextElementValue); } UserTaskContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getUserTaskContext(); }### Answer:
@Test public void should_return_a_context_of_type_SingleBusinessDataRef_for_a_given_task_instance() throws Exception { final Map<String, Serializable> context = new HashMap<String, Serializable>(); String engineResult = "object returned by engine"; context.put("Ticket", engineResult); when(processAPI.getUserTaskExecutionContext(2L)).thenReturn(context); doReturn("clientResult").when(finderFactory).getContextResultElement(engineResult); final Response response = request("/bpm/userTask/2/context").get(); assertThat(response).hasStatus(Status.SUCCESS_OK); assertThat(response).hasJsonEntityEqualTo("{\"Ticket\":\"clientResult\"}"); }
|
### Question:
UserTaskContextResource extends CommonResource { protected long getTaskIdParameter() { final String taskId = getAttribute(TASK_ID); if (taskId == null) { throw new APIException("Attribute '" + TASK_ID + "' is mandatory in order to get the task context"); } return Long.parseLong(taskId); } UserTaskContextResource(final ProcessAPI processAPI, FinderFactory resourceHandler); @Get("json") Map<String, Serializable> getUserTaskContext(); }### Answer:
@Test public void should_getTaskIDParameter_throws_an_exception_when_task_id_parameter_is_null() throws Exception { doReturn(null).when(taskContextResource).getAttribute(UserTaskContextResource.TASK_ID); try { taskContextResource.getTaskIdParameter(); } catch (final Exception e) { assertThat(e).isInstanceOf(APIException.class); assertThat(e.getMessage()).isEqualTo("Attribute '" + UserTaskContextResource.TASK_ID + "' is mandatory in order to get the task context"); } }
|
### Question:
APITask extends AbstractAPITask<TaskItem> { @Override public String defineDefaultSearchOrder() { return TaskItem.ATTRIBUTE_LAST_UPDATE_DATE + ISearchDirection.SORT_ORDER_DESCENDING; } @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void should_have_default_search_order() throws Exception { final APITask apiActivity = new APITask(); final String defineDefaultSearchOrder = apiActivity.defineDefaultSearchOrder(); assertThat(defineDefaultSearchOrder).as("sould have a default search order").isEqualTo("last_update_date DESC"); }
|
### Question:
APIActivity extends AbstractAPIActivity<ActivityItem> { @Override public String defineDefaultSearchOrder() { return ActivityInstanceSearchDescriptor.STATE_NAME + ISearchDirection.SORT_ORDER_ASCENDING; } @Override String defineDefaultSearchOrder(); }### Answer:
@Test public void should_have_default_search_order() throws Exception { final APIActivity apiActivity = new APIActivity(); final String defineDefaultSearchOrder = apiActivity.defineDefaultSearchOrder(); assertThat(defineDefaultSearchOrder).as("sould have a default search order").isEqualTo("state ASC"); }
|
### Question:
UserTaskContractResource extends CommonResource { protected long getTaskIdParameter() { final String taskId = getAttribute(TASK_ID); if (taskId == null) { throw new APIException("Attribute '" + TASK_ID + "' is mandatory"); } return Long.parseLong(taskId); } UserTaskContractResource(final ProcessAPI processAPI); @Get("json") ContractDefinition getContract(); }### Answer:
@Test public void should_getTaskIDParameter_throws_an_exception_when_task_id_parameter_is_null() throws Exception { doReturn(null).when(taskContractResource).getAttribute(UserTaskContractResource.TASK_ID); try { taskContractResource.getTaskIdParameter(); } catch (final Exception e) { assertThat(e).isInstanceOf(APIException.class); assertThat(e.getMessage()).isEqualTo("Attribute '" + UserTaskContractResource.TASK_ID + "' is mandatory"); } }
|
### Question:
UserTaskExecutionResource extends CommonResource { protected long getTaskIdParameter() { final String taskId = getAttribute(TASK_ID); if (taskId == null) { throw new APIException("Attribute '" + TASK_ID + "' is mandatory"); } return Long.parseLong(taskId); } UserTaskExecutionResource(final ProcessAPI processAPI, final APISession apiSession); @Post("json") void executeTask(final Map<String, Serializable> inputs); }### Answer:
@Test public void should_getProcessDefinitionIdParameter_throws_an_exception_when_task_id_parameter_is_null() throws Exception { doReturn(null).when(userTaskExecutionResource).getAttribute(UserTaskExecutionResource.TASK_ID); try { userTaskExecutionResource.getTaskIdParameter(); } catch (final Exception e) { assertThat(e).isInstanceOf(APIException.class); assertThat(e.getMessage()).isEqualTo("Attribute '" + UserTaskExecutionResource.TASK_ID + "' is mandatory"); } }
|
### Question:
ConfigurationFile { public String getProperty(final String propertyName) { return getPropertiesOfScope().getProperty(propertyName); } ConfigurationFile(final String propertiesFilename); ConfigurationFile(String propertiesFilename, long tenantId); String getProperty(final String propertyName); void removeProperty(final String propertyName); void setProperty(final String propertyName, final String propertyValue); Set<String> getPropertyAsSet(final String propertyName); void setPropertyAsSet(final String property, final Set<String> permissions); }### Answer:
@Test public void should_getProperty_return_the_right_custom_permissions_with_special_characters() throws Exception { final ConfigurationFile tenantProperties = new ConfigurationFile(CUSTOM_PERMISSIONS_MAPPING_FILE, TENANT_ID); final String customValue = tenantProperties.getProperty("profile|HR manager"); Assert.assertEquals("[ManageProfiles]", customValue); }
@Test public void should_getProperty_return_the_right_compound_permissions() throws Exception { final ConfigurationFile tenantProperties = new ConfigurationFile(COMPOUND_PERMISSIONS_MAPPING_FILE, TENANT_ID); final String compoundValue = tenantProperties.getProperty("taskListingPage"); Assert.assertEquals("[TaskVisualization, CaseVisualization]", compoundValue); }
@Test public void should_getProperty_return_the_right_resource_permissions() throws Exception { final ConfigurationFile tenantProperties = new ConfigurationFile(RESOURCES_PERMISSIONS_MAPPING_FILE, TENANT_ID); final String resourcesValue = tenantProperties.getProperty("GET|bpm/identity"); Assert.assertEquals("[UserVisualization, groupVisualization]", resourcesValue); }
@Test public void should_getProperty_return_the_right_custom_permissions() throws Exception { final ConfigurationFile tenantProperties = new ConfigurationFile(CUSTOM_PERMISSIONS_MAPPING_FILE, TENANT_ID); final String customValue = tenantProperties.getProperty("profile|User"); Assert.assertEquals("[ManageLooknFeel, ManageProfiles]", customValue); }
|
### Question:
ProcessInstantiationResource extends CommonResource { protected long getProcessDefinitionIdParameter() { final String processDefinitionId = getAttribute(PROCESS_DEFINITION_ID); if (processDefinitionId == null) { throw new APIException("Attribute '" + PROCESS_DEFINITION_ID + "' is mandatory"); } return Long.parseLong(processDefinitionId); } ProcessInstantiationResource(final ProcessAPI processAPI, final APISession apiSession); @Post("json") String instantiateProcess(final Map<String, Serializable> inputs); }### Answer:
@Test public void should_getProcessDefinitionIdParameter_throws_an_exception_when_task_id_parameter_is_null() throws Exception { doReturn(null).when(processInstantiationResource).getAttribute(ProcessInstantiationResource.PROCESS_DEFINITION_ID); try { processInstantiationResource.getProcessDefinitionIdParameter(); } catch (final Exception e) { assertThat(e).isInstanceOf(APIException.class); assertThat(e.getMessage()).isEqualTo("Attribute '" + ProcessInstantiationResource.PROCESS_DEFINITION_ID + "' is mandatory"); } }
|
### Question:
APIProcessConnector extends ConsoleAPI<ProcessConnectorItem> implements
APIHasGet<ProcessConnectorItem>,
APIHasSearch<ProcessConnectorItem> { @Override public ItemSearchResult<ProcessConnectorItem> search(final int page, final int resultsByPage, final String search, final String orders, final Map<String, String> filters) { if (MapUtil.isBlank(filters, ATTRIBUTE_PROCESS_ID)) { throw new APIFilterMandatoryException(ATTRIBUTE_PROCESS_ID); } return super.search(page, resultsByPage, search, orders, filters); } @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<ProcessConnectorItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); }### Answer:
@Test(expected = APIFilterMandatoryException.class) public void whenSearchingFilterProcessIdIsMandatory() throws Exception { this.apiProcessConnector.search(0, 10, null, null, EMPTY_MAP); }
@Test public void searchIsDoneWhenProcessIdFilterIsSet() throws Exception { final Map<String, String> filters = new HashMap<String, String>(); filters.put(ProcessConnectorItem.ATTRIBUTE_PROCESS_ID, "1"); this.apiProcessConnector.search(0, 10, null, null, filters); verify(this.processConnectorDatastore).search(0, 10, null, null, filters); }
|
### Question:
ProcessContractResource extends CommonResource { @Get("json") public ContractDefinition getContract() throws ProcessDefinitionNotFoundException { ContractDefinition processContract = processAPI.getProcessContract(getProcessDefinitionIdParameter()); return typeConverterUtil.getAdaptedContractDefinition(processContract); } ProcessContractResource(final ProcessAPI processAPI); @Get("json") ContractDefinition getContract(); }### Answer:
@Test(expected = APIException.class) public void should_throw_exception_if_attribute_is_not_found() throws Exception { doReturn(null).when(processContractResource).getAttribute(anyString()); processContractResource.getContract(); }
|
### Question:
ProcessDefinitionDesignResource extends CommonResource { @Get("json") public String getDesign() throws ProcessDefinitionNotFoundException, IOException { final DesignProcessDefinition design = processAPI.getDesignProcessDefinition(getProcessDefinitionIdParameter()); final JacksonRepresentation<DesignProcessDefinition> jacksonRepresentation = new JacksonRepresentation<DesignProcessDefinition>(design); jacksonRepresentation.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); jacksonRepresentation.setCharacterSet(CharacterSet.UTF_8); return replaceLongIdToString(jacksonRepresentation.getText()); } ProcessDefinitionDesignResource(final ProcessAPI processAPI); @Get("json") String getDesign(); }### Answer:
@Test(expected = APIException.class) public void should_throw_exception_if_attribute_is_not_found() throws Exception { doReturn(null).when(processDefinitionDesignResource).getAttribute(anyString()); processDefinitionDesignResource.getDesign(); }
|
### Question:
ProcessDefinitionDesignResource extends CommonResource { protected String replaceLongIdToString(final String design) throws IOException { return design.replaceAll("([^\\\\]\"id\"\\s*:\\s*)(\\d+)", "$1\"$2\""); } ProcessDefinitionDesignResource(final ProcessAPI processAPI); @Get("json") String getDesign(); }### Answer:
@Test public void testReplaceLongIdToString() throws Exception { assertThat(processDefinitionDesignResource.replaceLongIdToString("{ \"id\": 123}")).isEqualToIgnoringCase("{ \"id\": \"123\"}"); assertThat(processDefinitionDesignResource.replaceLongIdToString("{ \"id\":123, \"test\": [ otherid: \"zerze\"]}")).isEqualToIgnoringCase( "{ \"id\":\"123\", \"test\": [ otherid: \"zerze\"]}"); assertThat(processDefinitionDesignResource.replaceLongIdToString("{ \"iaed\": 123}")).isEqualToIgnoringCase("{ \"iaed\": 123}"); assertThat(processDefinitionDesignResource.replaceLongIdToString("{ \"name\": \"\\\"id\\\": 123\"}")).isEqualToIgnoringCase( "{ \"name\": \"\\\"id\\\": 123\"}"); assertThat(processDefinitionDesignResource.replaceLongIdToString("{ \"name\": \"\\\"id\\\": 123\"}")).isEqualToIgnoringCase( "{ \"name\": \"\\\"id\\\": 123\"}"); }
|
### Question:
APIProcessConnectorDependency extends ConsoleAPI<ProcessConnectorDependencyItem> implements
APIHasSearch<ProcessConnectorDependencyItem> { protected void checkMandatoryAttributes(final Map<String, String> filters) { if (MapUtil.isBlank(filters, ATTRIBUTE_PROCESS_ID)) { throw new APIFilterMandatoryException(ATTRIBUTE_PROCESS_ID); } if (MapUtil.isBlank(filters, ATTRIBUTE_CONNECTOR_NAME)) { throw new APIFilterMandatoryException(ATTRIBUTE_CONNECTOR_NAME); } if (MapUtil.isBlank(filters, ATTRIBUTE_CONNECTOR_VERSION)) { throw new APIFilterMandatoryException(ATTRIBUTE_CONNECTOR_VERSION); } } @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<ProcessConnectorDependencyItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); }### Answer:
@Test(expected = APIFilterMandatoryException.class) public void checkProcessIdIsMandatory() throws Exception { Map<String, String> filters = buildFilters(null, "aConnectorName", "aConnectorVersion"); apiProcessConnectorDependency.checkMandatoryAttributes(filters); }
@Test(expected = APIFilterMandatoryException.class) public void checkConnectorNameIsMandatory() throws Exception { Map<String, String> filters = buildFilters("1", "", "aConnectorVersion"); apiProcessConnectorDependency.checkMandatoryAttributes(filters); }
@Test(expected = APIFilterMandatoryException.class) public void checkConnectorVersionIsMandatory() throws Exception { Map<String, String> filters = buildFilters("1", "aConnectorName", ""); apiProcessConnectorDependency.checkMandatoryAttributes(filters); }
@Test public void checkMandatoryAttributesDontThrowExceptionIfAllAtributesAreSet() throws Exception { Map<String, String> filters = buildFilters("1", "aConnectorName", "aConnectorVersion"); apiProcessConnectorDependency.checkMandatoryAttributes(filters); assertTrue("no exception thrown", true); }
|
### Question:
APIProcessConnectorDependency extends ConsoleAPI<ProcessConnectorDependencyItem> implements
APIHasSearch<ProcessConnectorDependencyItem> { @Override public ItemSearchResult<ProcessConnectorDependencyItem> search(final int page, final int resultsByPage, final String search, final String orders, final Map<String, String> filters) { checkMandatoryAttributes(filters); return super.search(page, resultsByPage, search, orders, filters); } @Override String defineDefaultSearchOrder(); @Override ItemSearchResult<ProcessConnectorDependencyItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); }### Answer:
@Test(expected = APIFilterMandatoryException.class) public void searchCheckMandatoryAttributes() throws Exception { Map<String, String> filtersWithoutProcessId = buildFilters(null, "aConnectorName", "aConnectorVersion"); apiProcessConnectorDependency.search(0, 10, null, null, filtersWithoutProcessId); }
|
### Question:
TenantResourceItem implements Serializable { public String getLastUpdateDate() { return lastUpdateDate; } TenantResourceItem(final TenantResource tenantResource); String getId(); void setId(String id); String getName(); void setName(String name); TenantResourceType getType(); void setType(TenantResourceType type); TenantResourceState getState(); void setState(TenantResourceState state); String getLastUpdatedBy(); void setLastUpdatedBy(final String lastUpdatedBy); String getLastUpdateDate(); }### Answer:
@Test public void should_format_lastUpdateDate_as_ISO8601_string_when_tenantResourceItem_is_created(){ String dateAsString = "2018-01-05T09:04:19Z"; Instant instant = Instant.ofEpochSecond(1515143059); when(tenantResource.getLastUpdateDate()).thenReturn(OffsetDateTime.ofInstant(instant, ZoneOffset.UTC)); TenantResourceItem tenantResourceItem = new TenantResourceItem(tenantResource); assertThat(tenantResourceItem.getLastUpdateDate()).isEqualTo(dateAsString); }
|
### Question:
CustomUserInfoConverter extends ItemConverter<CustomUserInfoItem, CustomUserInfoValue> { public CustomUserInfoDefinitionItem convert(CustomUserInfoDefinition definition) { CustomUserInfoDefinitionItem item = new CustomUserInfoDefinitionItem(); item.setId(APIID.makeAPIID(definition.getId())); item.setName(definition.getName()); item.setDescription(definition.getDescription()); return item; } CustomUserInfoDefinitionItem convert(CustomUserInfoDefinition definition); CustomUserInfoItem convert(CustomUserInfo information); @Override CustomUserInfoItem convert(CustomUserInfoValue value); }### Answer:
@Test public void should_return_a_fully_configured_definition() throws Exception { CustomUserInfoDefinition dummy = new EngineCustomUserInfoDefinition(1L, "foo", "bar"); CustomUserInfoDefinitionItem definition = converter.convert(dummy); assertThat(definition.getAttributes()).containsOnly( entry("id", "1"), entry("name", "foo"), entry("description", "bar")); }
@Test public void should_return_a_fully_configured_custom_information() throws Exception { CustomUserInfoDefinition definition = new EngineCustomUserInfoDefinition(3L); CustomUserInfoValueImpl value = new CustomUserInfoValueImpl(); value.setValue("foo"); CustomUserInfoItem information = converter.convert(new CustomUserInfo(2L, definition, value)); assertThat(information.getAttributes()).containsOnly( entry("userId", "2"), entry("definitionId", "3"), entry("value", "foo")); assertThat(information.getDefinition().getId()).isEqualTo(APIID.makeAPIID(3L)); }
@Test public void should_return_a_fully_configured_custom_information_form_a_value() throws Exception { CustomUserInfoValueImpl value = new CustomUserInfoValueImpl(); value.setUserId(5); value.setDefinitionId(6); value.setValue("foo"); CustomUserInfoItem information = converter.convert(value); assertThat(information.getAttributes()).containsOnly( entry("userId", "5"), entry("definitionId", "6"), entry("value", "foo")); }
|
### Question:
APICustomUserInfoValue extends ConsoleAPI<CustomUserInfoItem> implements APIHasSearch<CustomUserInfoItem>, APIHasUpdate<CustomUserInfoItem> { @Override public CustomUserInfoItem update(APIID id, Map<String, String> attributes) { check(containsOnly(ATTRIBUTE_VALUE, attributes), new _("Only the value attribute can be updated")); return converter.convert(getClient().setCustomUserInfoValue( id.getPartAsLong(1), id.getPartAsLong(0), attributes.get(ATTRIBUTE_VALUE))); } APICustomUserInfoValue(CustomUserInfoEngineClientCreator engineClientCreator); @Override ItemSearchResult<CustomUserInfoItem> search(int page, int resultsByPage, String search, String orders, Map<String, String> filters); @Override String defineDefaultSearchOrder(); @Override CustomUserInfoItem update(APIID id, Map<String, String> attributes); }### Answer:
@Test public void should_update_a_given_custom_item_value() throws Exception { CustomUserInfoValueImpl update = new CustomUserInfoValueImpl(); update.setValue("foo"); given(engine.setCustomUserInfoValue(1L, 2L, "foo")).willReturn(update); CustomUserInfoItem value = api.update(APIID.makeAPIID(2L, 1L), Collections.singletonMap("value", "foo")); assertThat(value.getValue()).isEqualTo("foo"); }
|
### Question:
APICustomUserInfoDefinition extends ConsoleAPI<CustomUserInfoDefinitionItem> implements
APIHasAdd<CustomUserInfoDefinitionItem>,
APIHasSearch<CustomUserInfoDefinitionItem>,
APIHasDelete { public CustomUserInfoDefinitionItem add(CustomUserInfoDefinitionItem definition) { return converter.convert(engineClientCreator.create(getEngineSession()) .createDefinition(new CustomUserInfoDefinitionCreator( definition.getName(), definition.getDescription()))); } APICustomUserInfoDefinition(CustomUserInfoEngineClientCreator engineClientCreator); CustomUserInfoDefinitionItem add(CustomUserInfoDefinitionItem definition); void delete(final List<APIID> ids); ItemSearchResult<CustomUserInfoDefinitionItem> search(
final int page,
final int resultsByPage,
final String search,
final String orders,
final Map<String, String> filters); String defineDefaultSearchOrder(); static final String FIX_ORDER; }### Answer:
@Test public void add_should_return_the_added_item() throws Exception { given(engine.createDefinition(any(CustomUserInfoDefinitionCreator.class))) .willReturn(new EngineCustomUserInfoDefinition(2L)); CustomUserInfoDefinitionItem added = api.add(new CustomUserInfoDefinitionItem()); assertThat(added.getId()).isEqualTo(APIID.makeAPIID(2L)); }
@Test public void add_should_create_an_item_based_on_item_passed_in_parameter() throws Exception { given(engine.createDefinition(any(CustomUserInfoDefinitionCreator.class))) .willReturn(new EngineCustomUserInfoDefinition(1L)); ArgumentCaptor<CustomUserInfoDefinitionCreator> argument = ArgumentCaptor.forClass(CustomUserInfoDefinitionCreator.class); CustomUserInfoDefinitionItem item = new CustomUserInfoDefinitionItem(); item.setName("foo"); item.setDescription("bar"); api.add(item); verify(engine).createDefinition(argument.capture()); assertThat(argument.getValue().getName()).isEqualTo("foo"); assertThat(argument.getValue().getDescription()).isEqualTo("bar"); }
|
### Question:
APICustomUserInfoDefinition extends ConsoleAPI<CustomUserInfoDefinitionItem> implements
APIHasAdd<CustomUserInfoDefinitionItem>,
APIHasSearch<CustomUserInfoDefinitionItem>,
APIHasDelete { public void delete(final List<APIID> ids) { for (APIID id : ids) { engineClientCreator.create(getEngineSession()).deleteDefinition(id.toLong()); } } APICustomUserInfoDefinition(CustomUserInfoEngineClientCreator engineClientCreator); CustomUserInfoDefinitionItem add(CustomUserInfoDefinitionItem definition); void delete(final List<APIID> ids); ItemSearchResult<CustomUserInfoDefinitionItem> search(
final int page,
final int resultsByPage,
final String search,
final String orders,
final Map<String, String> filters); String defineDefaultSearchOrder(); static final String FIX_ORDER; }### Answer:
@Test public void delete_should_delete_all_items_with_id_passed_through() throws Exception { ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class); api.delete(Arrays.asList( APIID.makeAPIID(1L), APIID.makeAPIID(2L))); verify(engine, times(2)).deleteDefinition(argument.capture()); assertThat(argument.getAllValues()).containsOnly(1L, 2L); }
|
### Question:
APIUser extends ConsoleAPI<UserItem> implements APIHasAdd<UserItem>, APIHasDelete, APIHasUpdate<UserItem>,
APIHasGet<UserItem>, APIHasSearch<UserItem> { @Override public UserItem update(final APIID id, final Map<String, String> item) { MapUtil.removeIfBlank(item, UserItem.ATTRIBUTE_PASSWORD); if (item.get(UserItem.ATTRIBUTE_PASSWORD) != null) { checkPasswordRobustness(item.get(UserItem.ATTRIBUTE_PASSWORD)); } return getUserDatastore().update(id, item); } @Override String defineDefaultSearchOrder(); @Override UserItem add(final UserItem item); @Override UserItem update(final APIID id, final Map<String, String> item); @Override UserItem get(final APIID id); @Override ItemSearchResult<UserItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override void delete(final List<APIID> ids); }### Answer:
@Test public void should_not_update_password_if_empty() throws Exception { apiUser.update(USER_ID, map(UserItem.ATTRIBUTE_PASSWORD, "")); verify(userDatastore).update(eq(USER_ID), eq(Collections.<String, String> emptyMap())); }
@Test public void should_check_password_robustness_on_update() throws Exception { expectedException.expect(ValidationException.class); expectedException.expectMessage("the validator TestValidator rejected this password"); apiUser.update(USER_ID, map(UserItem.ATTRIBUTE_PASSWORD, "this password is not accepted by the TestValidator validator")); }
@Test public void should_update_password_if_valid() throws Exception { apiUser.update(USER_ID, map(UserItem.ATTRIBUTE_PASSWORD, "accepted password")); verify(userDatastore).update(eq(USER_ID), eq(map(UserItem.ATTRIBUTE_PASSWORD, "accepted password"))); }
|
### Question:
APIUser extends ConsoleAPI<UserItem> implements APIHasAdd<UserItem>, APIHasDelete, APIHasUpdate<UserItem>,
APIHasGet<UserItem>, APIHasSearch<UserItem> { @Override public UserItem add(final UserItem item) { if (StringUtil.isBlank(item.getPassword())) { throw new ValidationException(Collections.singletonList(new ValidationError("Password", "%attribute% is mandatory"))); } checkPasswordRobustness(item.getPassword()); return getUserDatastore().add(item); } @Override String defineDefaultSearchOrder(); @Override UserItem add(final UserItem item); @Override UserItem update(final APIID id, final Map<String, String> item); @Override UserItem get(final APIID id); @Override ItemSearchResult<UserItem> search(final int page, final int resultsByPage, final String search, final String orders,
final Map<String, String> filters); @Override void delete(final List<APIID> ids); }### Answer:
@Test public void should_check_password_robustness_on_add() throws Exception { UserItem userItem = new UserItem(); userItem.setUserName("John"); userItem.setPassword("this password is not accepted by the TestValidator validator"); expectedException.expect(ValidationException.class); expectedException.expectMessage("the validator TestValidator rejected this password"); apiUser.add(userItem); }
@Test public void should_throw_exception_when_adding_a_user_with_no_password() throws Exception { UserItem userItem = new UserItem(); userItem.setUserName("John"); expectedException.expect(ValidationException.class); apiUser.add(userItem); }
@Test public void should_add_user_if_password_is_valid() throws Exception { UserItem userItem = new UserItem(); userItem.setUserName("John"); userItem.setPassword("accepted password"); apiUser.add(userItem); }
|
### Question:
ConfigurationFile { public Set<String> getPropertyAsSet(final String propertyName) { final String propertyAsString = getProperty(propertyName); return stringToSet(propertyAsString); } ConfigurationFile(final String propertiesFilename); ConfigurationFile(String propertiesFilename, long tenantId); String getProperty(final String propertyName); void removeProperty(final String propertyName); void setProperty(final String propertyName, final String propertyValue); Set<String> getPropertyAsSet(final String propertyName); void setPropertyAsSet(final String property, final Set<String> permissions); }### Answer:
@Test public void should_getProperty_return_the_right_permissions_list() throws Exception { final ConfigurationFile tenantProperties = new ConfigurationFile(COMPOUND_PERMISSIONS_MAPPING_FILE, TENANT_ID); final Set<String> compoundPermissionsList = tenantProperties.getPropertyAsSet("taskListingPage"); assertThat(compoundPermissionsList).containsOnly("TaskVisualization", "CaseVisualization"); }
@Test public void should_getProperty_return_the_right_permissions_list_with_single_value() throws Exception { final ConfigurationFile tenantProperties = new ConfigurationFile(COMPOUND_PERMISSIONS_MAPPING_FILE, TENANT_ID); final Set<String> compoundPermissionsList = tenantProperties.getPropertyAsSet("processListingPage"); assertThat(compoundPermissionsList).containsOnly("processVisualization"); }
|
### Question:
JacksonDeserializer { public <T> T deserialize(String json, Class<T> clazz) { return deserialize(json, mapper.getTypeFactory().constructType(clazz)); } T deserialize(String json, Class<T> clazz); List<T> deserializeList(String json, Class<T> clazz); @SuppressWarnings("unchecked") T convertValue(Object fromValue, Class<?> toValue); }### Answer:
@Test(expected = APIException.class) public void deserialize_throw_exception_if_json_is_non_well_formed() throws Exception { String nonWellFormedJson = "someJsonNonWellFormedJson"; jacksonDeserializer.deserialize(nonWellFormedJson, String.class); }
@Test(expected = APIException.class) public void deserialize_throw_exception_if_mapping_bettween_class_and_json_is_incorrect() throws Exception { String notUserJson = "{\"unknownUserAttribute\": \"unknownAttributeValue\"}"; jacksonDeserializer.deserialize(notUserJson, User.class); }
@Test public void deserialize_can_deserialize_primitives_types() throws Exception { Long deserializedLong = jacksonDeserializer.deserialize("1", Long.class); assertThat(deserializedLong, is(1L)); }
@Test public void deserialize_can_deserialize_complex_types() throws Exception { User expectedUser = new User(1, "Colin", "Puy", new Date(428558400000L), new Address("310 La Gouterie", "Charnecles")); String json = "{\"address\":{\"street\":\"310 La Gouterie\",\"city\":\"Charnecles\"},\"id\":1,\"firstName\":\"Colin\",\"lastName\":\"Puy\",\"birthday\":428558400000}"; User deserializedUser = jacksonDeserializer.deserialize(json, User.class); assertThat(deserializedUser, equalTo(expectedUser)); }
|
### Question:
ServerProperties { public String getValue(final String propertyName) { return serverProperties.getProperty(propertyName); } private ServerProperties(); static synchronized ServerProperties getInstance(); String getValue(final String propertyName); }### Answer:
@Test public void should_return_property_value() { assertThat(serverProperties.getValue("auth.UserLogger")).isEqualTo("org.bonitasoft.console.common.server.login.credentials.UserLogger"); }
|
### Question:
JacksonSerializer { public String serialize(Object obj) throws JsonGenerationException, JsonMappingException, IOException { try{ return mapper.writeValueAsString(obj); }catch(Throwable e){ e.printStackTrace(); throw new RuntimeException(e); } } String serialize(Object obj); }### Answer:
@Test public void testSerialize() throws Exception { JacksonSerializer serializer = new JacksonSerializer(); ProfileImportStatusMessageFake message = new ProfileImportStatusMessageFake("profile1", "repalce"); message.addError("Organization: skks"); message.addError("Page: page1"); String serialize = serializer.serialize(message); assertThat(serialize).isEqualTo("{\"errors\":[\"Organization: skks\",\"Page: page1\"],\"profielName\":\"profile1\"}"); }
|
### Question:
RestRequestParser { public RestRequestParser invoke() { String pathInfo = request.getPathInfo(); if (pathInfo == null || pathInfo.split("/").length < 3) { pathInfo = request.getServletPath(); } final String[] path = pathInfo.split("/"); if (path.length < 3) { throw new APIMalformedUrlException("Missing API or resource name [" + request.getRequestURL() + "]"); } apiName = path[1]; resourceName = path[2]; if (path.length > 3) { final List<String> pathList = Arrays.asList(path); resourceQualifiers = APIID.makeAPIID(pathList.subList(3, pathList.size())); } else { resourceQualifiers = null; } return this; } RestRequestParser(final HttpServletRequest request); String getApiName(); String getResourceName(); APIID getResourceQualifiers(); RestRequestParser invoke(); }### Answer:
@Test(expected = APIMalformedUrlException.class) public void should_parsePath_with_bad_request() { doReturn("API/bpm").when(httpServletRequest).getPathInfo(); doReturn("/API").when(httpServletRequest).getServletPath(); restRequestParser.invoke(); }
|
### Question:
DateConverter implements Converter<Date> { @Override public Date convert(String toBeConverted) throws ConversionException { if (toBeConverted == null || toBeConverted.isEmpty()) { return null; } try { SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", DateFormatSymbols.getInstance(Locale.ENGLISH)); return formatter.parse(toBeConverted); } catch (ParseException e) { throw new ConversionException(toBeConverted + " cannot be converted to Date", e); } } @Override Date convert(String toBeConverted); }### Answer:
@Test public void nullIsConvertedToNull() throws Exception { Date converted = converter.convert(null); assertNull(converted); }
@Test public void emptyIsConvertedToNull() throws Exception { Date converted = converter.convert(""); assertNull(converted); }
@Test public void shouldConvertDateStringIntoDate() throws Exception { Calendar c = Calendar.getInstance(); int hourOfDay = 11; int minute = 43; int second = 30; int dayOfDateate = 18; int year = 2014; c.set(year, Calendar.AUGUST, dayOfDateate, hourOfDay, minute, second); String timeZone = "GMT"; c.setTimeZone(TimeZone.getTimeZone(timeZone)); c.set(Calendar.MILLISECOND, 0); Date date = c.getTime(); Date converted = converter.convert("Mon Aug " + dayOfDateate + " " + hourOfDay + ":" + minute + ":" + second + " " + timeZone + " " + year); assertEquals(date.toString() + " is not well converted", date, converted); }
@Test(expected = ConversionException.class) public void nonParsableStringThrowAConversionException() throws Exception { converter.convert("nonParsable"); }
|
### Question:
LongConverter implements Converter<Long> { @Override public Long convert(String toBeConverted) throws ConversionException { if (toBeConverted == null || toBeConverted.isEmpty()) { return null; } try { return Long.parseLong(toBeConverted); } catch (NumberFormatException e) { throw new ConversionException(toBeConverted + " cannot be converted to Long", e); } } @Override Long convert(String toBeConverted); }### Answer:
@Test public void nullIsConvertedToNull() throws Exception { Long converted = converter.convert(null); assertNull(converted); }
@Test public void emptyIsConvertedToNull() throws Exception { Long converted = converter.convert(""); assertNull(converted); }
@Test public void longNumberIsParsedToLong() throws Exception { long converted = converter.convert("456789"); assertEquals(456789L, converted); }
@Test(expected = ConversionException.class) public void nonParsableStringThrowAConversionException() throws Exception { converter.convert("nonParsable"); }
|
### Question:
IntegerConverter implements Converter<Integer> { @Override public Integer convert(String toBeConverted) throws ConversionException { if (toBeConverted == null || toBeConverted.isEmpty()) { return null; } try { return Integer.parseInt(toBeConverted); } catch (NumberFormatException e) { throw new ConversionException(toBeConverted + " cannot be converted to Integer", e); } } @Override Integer convert(String toBeConverted); }### Answer:
@Test public void nullIsConvertedToNull() throws Exception { Integer converted = converter.convert(null); assertNull(converted); }
@Test public void emptyIsConvertedToNull() throws Exception { Integer converted = converter.convert(""); assertNull(converted); }
@Test public void intNumberIsParsedToInteger() throws Exception { int converted = converter.convert("456789"); assertEquals(456789, converted); }
@Test(expected = ConversionException.class) public void nonParsableStringThrowAConversionException() throws Exception { converter.convert("nonParsable"); }
|
### Question:
DoubleConverter implements Converter<Double> { @Override public Double convert(String toBeConverted) throws ConversionException { if (toBeConverted == null || toBeConverted.isEmpty()) { return null; } try { return Double.parseDouble(toBeConverted); } catch (NumberFormatException e) { throw new ConversionException(toBeConverted + " cannot be converted to Double", e); } } @Override Double convert(String toBeConverted); }### Answer:
@Test public void nullIsConvertedToNull() throws Exception { Double converted = converter.convert(null); assertNull(converted); }
@Test public void emptyIsConvertedToNull() throws Exception { Double converted = converter.convert(""); assertNull(converted); }
@Test public void doubleNumberIsParsedToDouble() throws Exception { double converted = converter.convert("1.23"); assertEquals(1.23d, converted, 0d); }
@Test(expected = ConversionException.class) public void nonParsableStringThrowAConversionException() throws Exception { converter.convert("nonParsable"); }
|
### Question:
BooleanConverter implements Converter<Boolean> { @Override public Boolean convert(String toBeConverted) { if (toBeConverted == null || toBeConverted.isEmpty()) { return null; } return Boolean.valueOf(toBeConverted); } @Override Boolean convert(String toBeConverted); }### Answer:
@Test public void trueIsConvertedToTrue() throws Exception { Boolean converted = converter.convert("true"); assertTrue(converted); }
@Test public void falseIsConvertedToFalse() throws Exception { Boolean converted = converter.convert("false"); assertFalse(converted); }
@Test public void nullIsConvertedToNull() throws Exception { Boolean converted = converter.convert(null); assertNull(converted); }
@Test public void emptyIsConvertedToNull() throws Exception { Boolean converted = converter.convert(""); assertNull(converted); }
@Test public void anythingElseIsConvertedToFalse() throws Exception { Boolean converted = converter.convert("something"); assertFalse(converted); }
|
### Question:
StringConverter implements Converter<String> { @Override public String convert(String convert) { return convert; } @Override String convert(String convert); }### Answer:
@Test public void stringConverterIsDummy() throws Exception { String converted = new StringConverter().convert("any string"); assertEquals("any string", converted); }
|
### Question:
ConverterFactory { public Converter<?> createConverter(String className) { if (isClass(String.class, className)) { return new StringConverter(); } else if (isClass(Date.class, className)) { return new DateConverter(); } else if (isClass(Double.class, className)) { return new DoubleConverter(); } else if (isClass(Long.class, className)) { return new LongConverter(); } else if (isClass(Boolean.class, className)) { return new BooleanConverter(); } else if (isClass(Integer.class, className)) { return new IntegerConverter(); } throw new UnsupportedOperationException("Canno't create converter for class name : " + className); } Converter<?> createConverter(String className); }### Answer:
@Test public void factoryCreateABooleanConverterForBooleanClassName() throws Exception { Converter<?> createConverter = factory.createConverter(Boolean.class.getName()); assertTrue(createConverter instanceof BooleanConverter); }
@Test @Ignore("until ENGINE-1099 is resolved") public void factoryCreateADateConverterForDateClassName() throws Exception { Converter<?> createConverter = factory.createConverter(Date.class.getName()); assertTrue(createConverter instanceof DateConverter); }
@Test public void factoryCreateADoubleConverterForDoubleClassName() throws Exception { Converter<?> createConverter = factory.createConverter(Double.class.getName()); assertTrue(createConverter instanceof DoubleConverter); }
@Test public void factoryCreateALongConverterForLongClassName() throws Exception { Converter<?> createConverter = factory.createConverter(Long.class.getName()); assertTrue(createConverter instanceof LongConverter); }
@Test public void factoryCreateAStringConverterForStringClassName() throws Exception { Converter<?> createConverter = factory.createConverter(String.class.getName()); assertTrue(createConverter instanceof StringConverter); }
@Test public void factoryCreateAnIntegerConverterForIntegerClassName() throws Exception { Converter<?> createConverter = factory.createConverter(Integer.class.getName()); assertTrue(createConverter instanceof IntegerConverter); }
@Test(expected = UnsupportedOperationException.class) public void factoryThrowExceptionForUnsuportedConverter() throws Exception { factory.createConverter(Servlet.class.getName()); }
|
### Question:
TypeConverter { public Serializable convert(String className, String convert) throws ConversionException { return factory.createConverter(className).convert(convert); } TypeConverter(); TypeConverter(ConverterFactory factory); Serializable convert(String className, String convert); }### Answer:
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void convertCreateAFactoryAndConvertStringValueToSerializableObject() throws Exception { Converter typedConverter = mock(Converter.class); when(factory.createConverter(anyString())).thenReturn(typedConverter); converter.convert("aClassName", "somethingToconvert"); verify(typedConverter).convert("somethingToconvert"); }
|
### Question:
FilePathBuilder { public FilePathBuilder append(final String path) { if (path == null || path.isEmpty()) { return this; } this.path.append(File.separator); insert(path); return this; } FilePathBuilder(final String path); FilePathBuilder append(final String path); @Override String toString(); }### Answer:
@Test public void testAppend() throws Exception { String path1 = "org", path2 = "bonita", path3 = "web/service"; FilePathBuilder path = new FilePathBuilder(path1).append(path2).append(path3); assertEquals(buildExpectedPath(path1, path2, path3), path.toString()); }
|
### Question:
WebBonitaConstantsUtils { public File getFormsWorkFolder() { return getFolder(webBonitaConstants.getFormsTempFolderPath()); } protected WebBonitaConstantsUtils(final long tenantId); protected WebBonitaConstantsUtils(); synchronized static WebBonitaConstantsUtils getInstance(final long tenantId); synchronized static WebBonitaConstantsUtils getInstance(); File getTempFolder(); File getConfFolder(); File getPortalThemeFolder(); File getConsoleDefaultIconsFolder(); File getReportFolder(); File getPagesFolder(); File getFormsWorkFolder(); File geBDMWorkFolder(); File getTenantsFolder(); }### Answer:
@Test public void testWeCanGetFormsWorkFolder() throws Exception { WebBonitaConstantsTenancyImpl constantsTenants = new WebBonitaConstantsTenancyImpl(1L); final File expected = new File(constantsTenants.getFormsTempFolderPath()); final File folder = webBonitaConstantsUtilsWithTenantId.getFormsWorkFolder(); assertThat(folder.getPath()).isEqualTo(expected.getPath()); assertThat(folder).exists(); }
|
### Question:
JsonExceptionSerializer { public String end() { return json.append("}").toString(); } JsonExceptionSerializer(Throwable exception); String end(); JsonExceptionSerializer appendAttribute(final String name, final Object value); }### Answer:
@Test public void testWeCanConvertExceptionWithoutMessage() throws Exception { HttpException exception = new HttpException(); JsonExceptionSerializer serializer = new JsonExceptionSerializer(exception); String json = serializer.end(); assertEquals(exception, json); }
@Test public void testWeCanConvertExceptionWithMessageToJson() throws Exception { HttpException exception = new HttpException("message"); JsonExceptionSerializer serializer = new JsonExceptionSerializer(exception); String json = serializer.end(); assertEquals(exception, json); }
@Test public void testJsonContainsInternationalizedMessageWhenLocalIsSet() throws Exception { APIException exception = new APIException(new _("message")); fakeI18n.setL10n("localization"); exception.setLocale(LOCALE.en); JsonExceptionSerializer serializer = new JsonExceptionSerializer(exception); String json = serializer.end(); assertThat(json, equalTo( "{\"exception\":\"" + exception.getClass().toString() + "\"," + "\"message\":\"localization\"" + "}")); }
|
### Question:
JSonSerializer extends JSonUtil { public static String serialize(final JsonSerializable object) { return serializeInternal(object).toString(); } static String serialize(final JsonSerializable object); static String serialize(final Object object); static String serialize(final Object key, final Object value); static String serializeCollection(final Collection<? extends Object> list); static String serializeMap(final Map<? extends Object, ? extends Object> map); static String serializeException(final Throwable e); static String serializeStringMap(final Map<? extends Object, String> map); }### Answer:
@Test public void should_serialize_an_exception() throws Exception { Exception exception = new Exception("an exception"); String serialize = JSonSerializer.serialize(exception); assertThat(serialize).isEqualTo("{\"exception\":\"class java.lang.Exception\",\"message\":\"an exception\"}"); }
@Test public void should_serialize_only_first_cause_of_an_exception() throws Exception { Exception exception = new Exception("first one", new Exception("second one", new Exception("third one"))); String serialize = JSonSerializer.serialize(exception); assertThat(serialize).isEqualTo( "{\"exception\":\"class java.lang.Exception\"," + "\"message\":\"first one\"," + "\"cause\":{" + "\"exception\":\"class java.lang.Exception\"," + "\"message\":\"second one\"" + "}" + "}"); }
|
### Question:
JSonUtil { public static String escape(final String string) { return escapeInternal(string).toString(); } static String quote(final String value); static StringBuilder quoteInternal(final String value); static String escape(final String string); static String unquote(final String string); static String unescape(final String string); static HashMap<String, String> unescape(final HashMap<String, String> values); }### Answer:
@Test public void should_escape_unsafe_html_characters() { assertThat(escape("<script>alert('bad')</script>")) .isEqualTo("\\u003cscript\\u003ealert(\\u0027bad\\u0027)\\u003c\\/script\\u003e"); }
|
### Question:
AngularParameterCleaner { public String getHashWithoutAngularParameters() { return hash .replaceAll("&?" + token + "_id=[^&\\?#]*", "") .replaceAll("&?" + token + "_tab=[^&\\?#]*", ""); } AngularParameterCleaner(final String token, final String hash); String getHashWithoutAngularParameters(); }### Answer:
@Test public void appendTabFromTokensToUrlWithArchivedTabTokenShouldBeAppendToUrl() throws Exception { assertEquals("", new AngularParameterCleaner("cases", "cases_tab=archived").getHashWithoutAngularParameters()); assertEquals("", new AngularParameterCleaner("cases", "&cases_tab=archived").getHashWithoutAngularParameters()); assertEquals("&", new AngularParameterCleaner("cases", "cases_tab=archived&").getHashWithoutAngularParameters()); assertEquals("&test=faux", new AngularParameterCleaner("cases", "cases_tab=archived&test=faux").getHashWithoutAngularParameters()); assertEquals("test=faux", new AngularParameterCleaner("cases", "test=faux&cases_tab=archived").getHashWithoutAngularParameters()); assertEquals("test=vrai&test=faux", new AngularParameterCleaner("cases", "test=vrai&cases_tab=archived&test=faux").getHashWithoutAngularParameters()); assertEquals("&", new AngularParameterCleaner("cases", "&cases_tab=archived&cases_tab=archived&cases_tab=archived&").getHashWithoutAngularParameters()); assertEquals("?", new AngularParameterCleaner("cases", "?cases_tab=archived").getHashWithoutAngularParameters()); assertEquals("?test#", new AngularParameterCleaner("cases", "?test&cases_tab=archived#").getHashWithoutAngularParameters()); assertEquals("#?test", new AngularParameterCleaner("cases", "#?test&cases_tab=archived").getHashWithoutAngularParameters()); assertEquals("test=vrai }
|
### Question:
Plugin extends PluginAdapter { @Override public void initialize(PluginLoaderData plugindata, Toolbox toolbox) { } @Override void initialize(PluginLoaderData plugindata, Toolbox toolbox); static final Logger LOG; }### Answer:
@Test public void testInitialize() { fail("Not yet implemented."); }
|
### Question:
GroupByAvailableActiveLayersTreeBuilder extends GroupByDefaultTreeBuilder { @Override public String getGroupByName() { return "Active"; } @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); }### Answer:
@Test public void testGetGroupByName() { GroupByAvailableActiveLayersTreeBuilder builder = new GroupByAvailableActiveLayersTreeBuilder(); assertEquals("Active", builder.getGroupByName()); }
|
### Question:
GroupByTagsTreeBuilder extends GroupByDefaultTreeBuilder { @Override public String getGroupByName() { return "Tag"; } @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); }### Answer:
@Test public void testGetGroupByName() { GroupByTagsTreeBuilder builder = new GroupByTagsTreeBuilder(); assertEquals("Tag", builder.getGroupByName()); }
|
### Question:
GroupByDefaultTreeBuilder implements ActiveGroupByTreeBuilder, AvailableGroupByTreeBuilder { @Override public String getGroupByName() { return "Source"; } Set<String> getCategories(); DataGroupController getDataGroupController(); @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); @Override Comparator<? super DataGroupInfo> getGroupComparator(); @Override Predicate<DataGroupInfo> getDataCategoryFilter(); @Override Predicate<DataGroupInfo> getGroupFilter(); Toolbox getToolbox(); @Override TreeOptions getTreeOptions(); @Override Comparator<? super DataTypeInfo> getTypeComparator(); @Override void initializeForActive(Toolbox toolbox); @Override void initializeForAvailable(Toolbox toolbox); @Override void setGroupComparator(Comparator<? super DataGroupInfo> comp); void setTypeComparator(Comparator<? super DataTypeInfo> comp); boolean isActiveGroupsOnly(); boolean isSubNodesForMultiMemberGroups(); }### Answer:
@Test public void testGetGroupByName() { GroupByDefaultTreeBuilder builder = new GroupByDefaultTreeBuilder(); assertEquals("Source", builder.getGroupByName()); }
|
### Question:
DefaultTimeSpanSet implements TimeSpanSet { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } DefaultTimeSpanSet other = (DefaultTimeSpanSet)obj; return Objects.equals(myElementList, other.myElementList); } DefaultTimeSpanSet(); DefaultTimeSpanSet(TimeSpan ts); DefaultTimeSpanSet(TimeSpanSet other); @Override boolean add(TimeSpan e); @Override final boolean add(TimeSpanSet other); @Override boolean addAll(Collection<? extends TimeSpan> c); @Override void clear(); @Override boolean contains(Date aDate); @Override boolean contains(long aTime); @Override boolean contains(Object o); @Override boolean contains(TimeSpan value); @Override boolean containsAll(Collection<?> c); @Override boolean equals(Object obj); @Override List<TimeSpan> getTimeSpans(); @Override int hashCode(); @Override TimeSpanSet intersection(TimeSpan ts); @Override TimeSpanSet intersection(TimeSpanSet otherSet); @Override boolean intersects(TimeSpan value); @Override boolean intersects(TimeSpanProvider ts); @Override boolean intersects(TimeSpanSet other); @Override boolean isEmpty(); @Override Iterator<TimeSpan> iterator(); @Override boolean remove(Object o); @Override boolean remove(TimeSpan spanToRemove); @Override boolean remove(TimeSpanSet other); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); @Override int size(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override String toString(); @Override TimeSpanSet union(TimeSpanSet other); }### Answer:
@Test public void testEqualsWrongType() { DefaultTimeSpanSet rlsA = new DefaultTimeSpanSet(); assertFalse(rlsA.equals(RandomStringUtils.randomAlphabetic(5))); }
|
### Question:
TimeInstant implements Comparable<TimeInstant>, Serializable, SizeProvider { public String toISO8601String() { return DateTimeUtilities.generateISO8601DateString(toDate()); } static TimeInstant get(); static TimeInstant get(Calendar time); static TimeInstant get(Date time); static TimeInstant get(long epochMillis); static TimeInstant max(TimeInstant t1, TimeInstant t2); static TimeInstant min(TimeInstant t1, TimeInstant t2); @Override int compareTo(TimeInstant o); @Override boolean equals(Object obj); abstract long getEpochMillis(); @Override int hashCode(); boolean isAfter(TimeInstant other); boolean isBefore(TimeInstant other); boolean isOverlapped(Collection<? extends TimeSpan> timeSpans); TimeInstant minus(Duration dur); Duration minus(TimeInstant other); TimeInstant plus(Duration dur); Date toDate(); String toDisplayString(); String toDisplayString(String fmt); String toISO8601String(); @Override String toString(); }### Answer:
@Test public void testToISO8601String() throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat(DateTimeFormats.DATE_TIME_FORMAT); TimeInstant timeInstant = TimeInstant.get(fmt.parse("2010-03-13 12:35:17")); String actual = timeInstant.toISO8601String(); String expected = "2010-03-13T12:35:17Z"; Assert.assertEquals(expected, actual); fmt = new SimpleDateFormat(DateTimeFormats.DATE_TIME_MILLIS_FORMAT); timeInstant = TimeInstant.get(fmt.parse("2010-03-13 12:35:17.001")); actual = timeInstant.toISO8601String(); expected = "2010-03-13T12:35:17.001Z"; Assert.assertEquals(expected, actual); }
|
### Question:
GroupByDefaultTreeBuilder implements ActiveGroupByTreeBuilder, AvailableGroupByTreeBuilder { @Override public void initializeForActive(Toolbox toolbox) { setToolbox(toolbox); myActiveGroupsOnly = true; mySubNodesForMultiMemberGroups = true; } Set<String> getCategories(); DataGroupController getDataGroupController(); @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); @Override Comparator<? super DataGroupInfo> getGroupComparator(); @Override Predicate<DataGroupInfo> getDataCategoryFilter(); @Override Predicate<DataGroupInfo> getGroupFilter(); Toolbox getToolbox(); @Override TreeOptions getTreeOptions(); @Override Comparator<? super DataTypeInfo> getTypeComparator(); @Override void initializeForActive(Toolbox toolbox); @Override void initializeForAvailable(Toolbox toolbox); @Override void setGroupComparator(Comparator<? super DataGroupInfo> comp); void setTypeComparator(Comparator<? super DataTypeInfo> comp); boolean isActiveGroupsOnly(); boolean isSubNodesForMultiMemberGroups(); }### Answer:
@Test public void testInitializeForActive() { EasyMockSupport support = new EasyMockSupport(); Toolbox toolbox = support.createMock(Toolbox.class); support.replayAll(); GroupByDefaultTreeBuilder builder = new GroupByDefaultTreeBuilder(); builder.initializeForActive(toolbox); assertEquals(toolbox, builder.getToolbox()); assertTrue(builder.isActiveGroupsOnly()); assertTrue(builder.isSubNodesForMultiMemberGroups()); support.verifyAll(); }
|
### Question:
BinaryTimeTree { public BinaryTimeTree() { this(DEFAULT_MAX_VALUES_PER_NODE, DEFAULT_MAX_DEPTH); } BinaryTimeTree(); BinaryTimeTree(int maxValuesPerNode, int maxDepth); void clear(); int countInRange(TimeSpan range); CountReport countsInBins(TimeSpan overAllRange, int numberOfBins); TIntList countsInRanges(List<TimeSpan> countTimes); List<E> findInRange(TimeSpan range); boolean insert(E tsProvider); boolean insert(List<E> collection); int internalSize(BTreeNode<E> node); int maxValuesPerNodeInteral(BTreeNode<E> node, int maxValues); int queryMaxValuesPerNode(); int size(); }### Answer:
@Test public void testBinaryTimeTree() { assertNotNull(myTestObject); }
|
### Question:
BinaryTimeTree { public void clear() { nodeClear(myTopNode); myTopNode.setRange(null); } BinaryTimeTree(); BinaryTimeTree(int maxValuesPerNode, int maxDepth); void clear(); int countInRange(TimeSpan range); CountReport countsInBins(TimeSpan overAllRange, int numberOfBins); TIntList countsInRanges(List<TimeSpan> countTimes); List<E> findInRange(TimeSpan range); boolean insert(E tsProvider); boolean insert(List<E> collection); int internalSize(BTreeNode<E> node); int maxValuesPerNodeInteral(BTreeNode<E> node, int maxValues); int queryMaxValuesPerNode(); int size(); }### Answer:
@Test public void testClear() { myTestObject.clear(); assertEquals(0, myTestObject.size()); }
|
### Question:
BinaryTimeTree { public int countInRange(TimeSpan range) { return myTopNode.countInRange(range); } BinaryTimeTree(); BinaryTimeTree(int maxValuesPerNode, int maxDepth); void clear(); int countInRange(TimeSpan range); CountReport countsInBins(TimeSpan overAllRange, int numberOfBins); TIntList countsInRanges(List<TimeSpan> countTimes); List<E> findInRange(TimeSpan range); boolean insert(E tsProvider); boolean insert(List<E> collection); int internalSize(BTreeNode<E> node); int maxValuesPerNodeInteral(BTreeNode<E> node, int maxValues); int queryMaxValuesPerNode(); int size(); }### Answer:
@Test(expected = NullPointerException.class) public void testCountInRangeEmptyNode() { assertEquals(0, myTestObject.countInRange(TimeSpan.ZERO)); }
@Test public void testCountInRange() { TimeSpan span1 = new TimeSpanLongLong(0, 1); TimeSpan span2 = new TimeSpanLongLong(1, 2); TimeSpanProvider mock1 = createNiceMock(TimeSpanProvider.class); TimeSpanProvider mock2 = createNiceMock(TimeSpanProvider.class); expect(mock1.getTimeSpan()).andReturn(span1).anyTimes(); expect(mock2.getTimeSpan()).andReturn(span2).anyTimes(); replay(mock1, mock2); myTestObject.insert(Arrays.asList(mock1, mock2)); assertEquals(1, myTestObject.countInRange(span1)); }
|
### Question:
BinaryTimeTree { public TIntList countsInRanges(List<TimeSpan> countTimes) { Utilities.checkNull(countTimes, "countTimes"); if (countTimes.isEmpty()) { return new TIntArrayList(0); } TIntList resultList = new TIntArrayList(countTimes.size()); for (TimeSpan span : countTimes) { resultList.add(countInRange(span)); } return resultList; } BinaryTimeTree(); BinaryTimeTree(int maxValuesPerNode, int maxDepth); void clear(); int countInRange(TimeSpan range); CountReport countsInBins(TimeSpan overAllRange, int numberOfBins); TIntList countsInRanges(List<TimeSpan> countTimes); List<E> findInRange(TimeSpan range); boolean insert(E tsProvider); boolean insert(List<E> collection); int internalSize(BTreeNode<E> node); int maxValuesPerNodeInteral(BTreeNode<E> node, int maxValues); int queryMaxValuesPerNode(); int size(); }### Answer:
@Test public void testCountsInRanges() { TimeSpan span1 = new TimeSpanLongLong(0, 100); TimeSpan span2 = new TimeSpanLongLong(0, 50); TimeSpanProvider mock1 = createNiceMock(TimeSpanProvider.class); TimeSpanProvider mock2 = createNiceMock(TimeSpanProvider.class); expect(mock1.getTimeSpan()).andReturn(span1).anyTimes(); expect(mock2.getTimeSpan()).andReturn(span2).anyTimes(); replay(mock1, mock2); myTestObject.insert(Arrays.asList(mock1, mock2)); TIntList list = myTestObject.countsInRanges(Arrays.asList(span1, span2)); assertEquals(2, list.size()); }
@Test public void testCountsInRangesEmpty() { TIntList list = myTestObject.countsInRanges(new ArrayList<>()); assertTrue(list.isEmpty()); }
|
### Question:
GroupByDefaultTreeBuilder implements ActiveGroupByTreeBuilder, AvailableGroupByTreeBuilder { @Override public void initializeForAvailable(Toolbox toolbox) { setToolbox(toolbox); } Set<String> getCategories(); DataGroupController getDataGroupController(); @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); @Override Comparator<? super DataGroupInfo> getGroupComparator(); @Override Predicate<DataGroupInfo> getDataCategoryFilter(); @Override Predicate<DataGroupInfo> getGroupFilter(); Toolbox getToolbox(); @Override TreeOptions getTreeOptions(); @Override Comparator<? super DataTypeInfo> getTypeComparator(); @Override void initializeForActive(Toolbox toolbox); @Override void initializeForAvailable(Toolbox toolbox); @Override void setGroupComparator(Comparator<? super DataGroupInfo> comp); void setTypeComparator(Comparator<? super DataTypeInfo> comp); boolean isActiveGroupsOnly(); boolean isSubNodesForMultiMemberGroups(); }### Answer:
@Test public void testInitializeForAvailable() { EasyMockSupport support = new EasyMockSupport(); Toolbox toolbox = support.createMock(Toolbox.class); support.replayAll(); GroupByDefaultTreeBuilder builder = new GroupByDefaultTreeBuilder(); builder.initializeForAvailable(toolbox); assertEquals(toolbox, builder.getToolbox()); assertFalse(builder.isActiveGroupsOnly()); assertFalse(builder.isSubNodesForMultiMemberGroups()); support.verifyAll(); }
|
### Question:
BinaryTimeTree { protected TimeSpan enlargeTimeRange(Collection<E> collection, TimeSpan range) { TimeSpan maxRange = range; if (maxRange == null) { maxRange = TimeSpan.get(0, OUR_MAX_TIME); } for (TimeSpanProvider tsp : collection) { if (!maxRange.contains(tsp.getTimeSpan())) { maxRange = maxRange.simpleUnion(tsp.getTimeSpan()); } } return maxRange; } BinaryTimeTree(); BinaryTimeTree(int maxValuesPerNode, int maxDepth); void clear(); int countInRange(TimeSpan range); CountReport countsInBins(TimeSpan overAllRange, int numberOfBins); TIntList countsInRanges(List<TimeSpan> countTimes); List<E> findInRange(TimeSpan range); boolean insert(E tsProvider); boolean insert(List<E> collection); int internalSize(BTreeNode<E> node); int maxValuesPerNodeInteral(BTreeNode<E> node, int maxValues); int queryMaxValuesPerNode(); int size(); }### Answer:
@Test public void testEnlargeTimeRange() { TimeSpan span = new TimeSpanLongLong(10, 20); TimeSpan span1 = new TimeSpanLongLong(0, 8); TimeSpan span2 = new TimeSpanLongLong(26, 50); TimeSpan result = myTestObject.enlargeTimeRange(Arrays.asList(span1, span2), span); assertEquals(0, result.getStart()); assertEquals(50, result.getEnd()); }
|
### Question:
TimeSpanList extends AbstractList<TimeSpan> implements Serializable { public abstract TimeSpanList clone(Collection<? extends TimeSpan> spans); static TimeSpanList emptyList(); static void mergeOverlaps(final List<TimeSpan> list); static void mergeOverlaps(final List<TimeSpan> list, boolean mergeTouching); static TimeSpanList singleton(TimeSpan obj); abstract TimeSpanList clone(Collection<? extends TimeSpan> spans); boolean covers(TimeSpan other); boolean covers(TimeSpanList other); TimeSpan getExtent(); abstract TimeSpanList intersection(TimeSpan ts); abstract TimeSpanList intersection(TimeSpanList other); boolean intersects(TimeSpan timeSpan); abstract TimeSpanList union(TimeSpan ts); abstract TimeSpanList union(TimeSpanList other); static final TimeSpanList TIMELESS; }### Answer:
@Test public void testClone() { final TimeSpan ts1 = TimeSpan.get(8L, 20L); TimeSpanList singleton = TimeSpanList.singleton(ts1); List<TimeSpan> tsList = new ArrayList<>(); tsList.add(TimeSpan.get(10L, 20L)); tsList.add(TimeSpan.get(30L, 40L)); tsList.add(TimeSpan.get(50L, 60L)); TimeSpanList clone1 = singleton.clone(tsList); Assert.assertEquals(tsList.size(), clone1.size()); Assert.assertTrue(clone1.containsAll(tsList)); testImmutable(clone1); TimeSpanList emptyList = TimeSpanList.emptyList(); TimeSpanList clone2 = emptyList.clone(tsList); Assert.assertEquals(tsList.size(), clone2.size()); Assert.assertTrue(clone2.containsAll(tsList)); testImmutable(clone2); }
|
### Question:
TimeSpanList extends AbstractList<TimeSpan> implements Serializable { public static TimeSpanList emptyList() { return EMPTY_LIST; } static TimeSpanList emptyList(); static void mergeOverlaps(final List<TimeSpan> list); static void mergeOverlaps(final List<TimeSpan> list, boolean mergeTouching); static TimeSpanList singleton(TimeSpan obj); abstract TimeSpanList clone(Collection<? extends TimeSpan> spans); boolean covers(TimeSpan other); boolean covers(TimeSpanList other); TimeSpan getExtent(); abstract TimeSpanList intersection(TimeSpan ts); abstract TimeSpanList intersection(TimeSpanList other); boolean intersects(TimeSpan timeSpan); abstract TimeSpanList union(TimeSpan ts); abstract TimeSpanList union(TimeSpanList other); static final TimeSpanList TIMELESS; }### Answer:
@Test public void testEmptyList() { TimeSpanList emptyList = TimeSpanList.emptyList(); Assert.assertTrue(emptyList.isEmpty()); testImmutable(emptyList); Assert.assertSame(TimeSpan.ZERO, emptyList.getExtent()); }
|
### Question:
TimeSpanList extends AbstractList<TimeSpan> implements Serializable { public static void mergeOverlaps(final List<TimeSpan> list) { mergeOverlaps(list, false); } static TimeSpanList emptyList(); static void mergeOverlaps(final List<TimeSpan> list); static void mergeOverlaps(final List<TimeSpan> list, boolean mergeTouching); static TimeSpanList singleton(TimeSpan obj); abstract TimeSpanList clone(Collection<? extends TimeSpan> spans); boolean covers(TimeSpan other); boolean covers(TimeSpanList other); TimeSpan getExtent(); abstract TimeSpanList intersection(TimeSpan ts); abstract TimeSpanList intersection(TimeSpanList other); boolean intersects(TimeSpan timeSpan); abstract TimeSpanList union(TimeSpan ts); abstract TimeSpanList union(TimeSpanList other); static final TimeSpanList TIMELESS; }### Answer:
@Test public void testMergeOverlaps() { final TimeSpan ts0 = TimeSpan.get(8L, 20L); final TimeSpan ts1 = TimeSpan.get(1L, 6L); final TimeSpan ts2 = TimeSpan.get(2L, 2L); final TimeSpan ts3 = TimeSpan.get(19L, 25L); final TimeSpan ts4 = TimeSpan.get(24L, 26L); List<TimeSpan> list = new ArrayList<>(); list.add(ts0); list.add(ts1); list.add(ts2); list.add(ts3); list.add(ts4); TimeSpanList.mergeOverlaps(list); Assert.assertEquals(2, list.size()); Assert.assertEquals(TimeSpan.get(8L, 26L), list.get(0)); Assert.assertEquals(TimeSpan.get(1L, 6L), list.get(1)); }
|
### Question:
GroupByTypeTreeBuilder extends GroupByDefaultTreeBuilder { @Override public String getGroupByName() { return "Type"; } @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); }### Answer:
@Test public void testGetGroupByName() { GroupByTypeTreeBuilder builder = new GroupByTypeTreeBuilder(); assertEquals("Type", builder.getGroupByName()); }
|
### Question:
TimeSpanList extends AbstractList<TimeSpan> implements Serializable { public static TimeSpanList singleton(TimeSpan obj) { return new SingletonList(obj); } static TimeSpanList emptyList(); static void mergeOverlaps(final List<TimeSpan> list); static void mergeOverlaps(final List<TimeSpan> list, boolean mergeTouching); static TimeSpanList singleton(TimeSpan obj); abstract TimeSpanList clone(Collection<? extends TimeSpan> spans); boolean covers(TimeSpan other); boolean covers(TimeSpanList other); TimeSpan getExtent(); abstract TimeSpanList intersection(TimeSpan ts); abstract TimeSpanList intersection(TimeSpanList other); boolean intersects(TimeSpan timeSpan); abstract TimeSpanList union(TimeSpan ts); abstract TimeSpanList union(TimeSpanList other); static final TimeSpanList TIMELESS; }### Answer:
@Test public void testSingleton() { final TimeSpan ts = TimeSpan.get(8L, 20L); TimeSpanList singleton = TimeSpanList.singleton(ts); Assert.assertEquals(1, singleton.size()); Assert.assertSame(ts, singleton.get(0)); testImmutable(singleton); Assert.assertSame(ts, singleton.getExtent()); }
|
### Question:
GroupByActiveZOrderTreeBuilder extends GroupByDefaultTreeBuilder { @Override public String getGroupByName() { return "Z-Order"; } @Override String getGroupByName(); @Override GroupCategorizer getGroupCategorizer(); @Override Comparator<? super DataGroupInfo> getGroupComparator(); @Override TreeOptions getTreeOptions(); @Override Comparator<? super DataTypeInfo> getTypeComparator(); }### Answer:
@Test public void testGetGroupByName() { GroupByActiveZOrderTreeBuilder builder = new GroupByActiveZOrderTreeBuilder(); assertEquals("Z-Order", builder.getGroupByName()); }
|
### Question:
TimeSpanArrayList extends TimeSpanList implements RandomAccess { @Override public TimeSpanList clone(Collection<? extends TimeSpan> spans) { return new TimeSpanArrayList(spans); } TimeSpanArrayList(Collection<? extends TimeSpan> timeSpans); @Override TimeSpanList clone(Collection<? extends TimeSpan> spans); @Override TimeSpan get(int index); List<TimeSpan> getTimeSpans(); @Override TimeSpanList intersection(TimeSpan ts); @Override TimeSpanList intersection(TimeSpanList other); @Override int size(); @Override TimeSpanList union(TimeSpan ts); @Override TimeSpanList union(TimeSpanList other); }### Answer:
@Test public void testClone() { List<TimeSpan> list1 = new ArrayList<>(); list1.add(TimeSpan.get(1L, 4L)); list1.add(TimeSpan.get(5L, 7L)); list1.add(TimeSpan.get(9L, 11L)); TimeSpanList tsList = new TimeSpanArrayList(list1); List<TimeSpan> list2 = new ArrayList<>(list1); list2.add(TimeSpan.get(3L, 6L)); list2.add(TimeSpan.get(10L, 12L)); TimeSpanList clone = tsList.clone(list2); List<TimeSpan> expected = new ArrayList<>(); expected.add(TimeSpan.get(1L, 7L)); expected.add(TimeSpan.get(9L, 12L)); Assert.assertEquals(list1.size(), tsList.size()); Assert.assertTrue(tsList.containsAll(list1)); Assert.assertEquals(expected.size(), clone.size()); Assert.assertTrue(clone.containsAll(expected)); }
|
### Question:
ColumnLabels extends Observable implements Serializable { public ObservableList<ColumnLabel> getColumnsInLabel() { return myColumnsInLabel; } ObservableList<ColumnLabel> getColumnsInLabel(); boolean isAlwaysShowLabels(); void setAlwaysShowLabels(boolean alwaysShowLabels); void copyFrom(ColumnLabels other); @Override int hashCode(); @Override boolean equals(Object obj); static final String ALWAYS_SHOW_LABELS_PROP; }### Answer:
@Test public void testSerializeEmpty() throws IOException, ClassNotFoundException { EasyMockSupport support = new EasyMockSupport(); @SuppressWarnings("unchecked") ListDataListener<ColumnLabel> listener = support.createMock(ListDataListener.class); support.replayAll(); ColumnLabels model = new ColumnLabels(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(out); objectOut.writeObject(model); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); ObjectInputStream objectIn = new ObjectInputStream(in); ColumnLabels actual = (ColumnLabels)objectIn.readObject(); actual.getColumnsInLabel().addChangeListener(listener); support.verifyAll(); }
|
### Question:
StateXML { public static NodeList getChildNodes(Node rootNode, String xpath) throws XPathExpressionException { return (NodeList)newXPath().evaluate(xpath, rootNode, XPathConstants.NODESET); } private StateXML(); static Node createChildNode(Node rootNode, Document doc, Node parent, String childPath, String childName); static Element createElement(Document doc, String qname); static Node getChildNode(Node rootNode, String childPath); static NodeList getChildNodes(Node rootNode, String xpath); static Node getChildStateNode(Node rootNode, String childPathFragment); static boolean anyMatch(Node rootNode, String xpath); static T getStateBean(Node node, String childPathFragment, Class<T> target); static XPath newXPath(); }### Answer:
@Test public void testGetChildNodes() throws ParserConfigurationException, XPathExpressionException { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Node parent = doc.appendChild(doc.createElement("parent")); NodeList child = StateXML.getChildNodes(parent, "/parent/child"); assertEquals(0, child.getLength()); Node expectedChild1 = parent.appendChild(doc.createElement("child")); Node expectedChild2 = parent.appendChild(doc.createElement("child")); child = StateXML.getChildNodes(parent, "/parent/child"); assertEquals(2, child.getLength()); assertEquals(expectedChild1, child.item(0)); assertEquals(expectedChild2, child.item(1)); }
|
### Question:
ColumnLabels extends Observable implements Serializable { public void setAlwaysShowLabels(boolean alwaysShowLabels) { myAlwaysShowLabels = alwaysShowLabels; setChanged(); notifyObservers(ALWAYS_SHOW_LABELS_PROP); } ObservableList<ColumnLabel> getColumnsInLabel(); boolean isAlwaysShowLabels(); void setAlwaysShowLabels(boolean alwaysShowLabels); void copyFrom(ColumnLabels other); @Override int hashCode(); @Override boolean equals(Object obj); static final String ALWAYS_SHOW_LABELS_PROP; }### Answer:
@Test public void testUpdate() { EasyMockSupport support = new EasyMockSupport(); Observer alwaysShow = createObserver(support, ColumnLabels.ALWAYS_SHOW_LABELS_PROP); support.replayAll(); ColumnLabels options = new ColumnLabels(); options.addObserver(alwaysShow); options.setAlwaysShowLabels(true); options.deleteObserver(alwaysShow); support.verifyAll(); }
|
### Question:
DefaultContinuousAnimationPlan extends DefaultAnimationPlan implements ContinuousAnimationPlan { @Override public DefaultContinuousAnimationState getInitialState() { DefaultAnimationState initialState = super.getInitialState(); return createStateFromParentState(initialState, true); } DefaultContinuousAnimationPlan(List<? extends TimeSpan> sequence, Duration activeWindowDuration,
Duration advanceDuration, EndBehavior endBehavior, TimeSpan limitWindow); @Override DefaultAnimationState determineNextState(AnimationState state); DefaultContinuousAnimationState determineNextState(DefaultContinuousAnimationState state); @Override DefaultAnimationState determinePreviousState(AnimationState state); DefaultContinuousAnimationState determinePreviousState(DefaultContinuousAnimationState state); @Override boolean equals(Object obj); @Override @Nullable @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") DefaultContinuousAnimationState findState(Date time, Direction direction); @Override @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") DefaultContinuousAnimationState findState(TimeSpan span, Direction direction); @Override Duration getActiveWindowDuration(); @Override Duration getAdvanceDuration(); @Override DefaultContinuousAnimationState getFinalState(); @Override AnimationState getFinalState(AnimationState state); AnimationState getFinalState(DefaultContinuousAnimationState state); @Override DefaultContinuousAnimationState getInitialState(); @Override TimeSpan getLimitWindow(); @Override TimeSpan getTimeSpanForState(AnimationState state); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testGetInitialState() { DefaultContinuousAnimationPlan plan = createPlan(); Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD), plan.getInitialState()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.